Merge branch 'master' into BAEL-1267-programmatic-tomcat
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import org.eclipse.jetty.server.Handler;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.server.ServerConnector;
|
||||
import org.eclipse.jetty.server.handler.HandlerCollection;
|
||||
import org.eclipse.jetty.webapp.WebAppContext;
|
||||
|
||||
/**
|
||||
* Simple factory for creating Jetty basic instances.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class JettyServerFactory {
|
||||
|
||||
/**
|
||||
* Exposed context of the app.
|
||||
*/
|
||||
public final static String APP_PATH = "/myApp";
|
||||
|
||||
/**
|
||||
* The server port.
|
||||
*/
|
||||
public final static int SERVER_PORT = 13133;
|
||||
|
||||
/**
|
||||
* Private constructor to avoid instantiation.
|
||||
*/
|
||||
private JettyServerFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a simple server listening on port 80 with a timeout of 30 seconds
|
||||
* for connections and no handlers.
|
||||
*
|
||||
* @return a server
|
||||
*/
|
||||
public static Server createBaseServer() {
|
||||
Server server = new Server();
|
||||
|
||||
// Adds a connector for port 80 with a timeout of 30 seconds.
|
||||
ServerConnector connector = new ServerConnector(server);
|
||||
connector.setPort(SERVER_PORT);
|
||||
connector.setHost("127.0.0.1");
|
||||
connector.setIdleTimeout(30000);
|
||||
server.addConnector(connector);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a server which delegates the request handling to a web
|
||||
* application.
|
||||
*
|
||||
* @return a server
|
||||
*/
|
||||
public static Server createWebAppServer() {
|
||||
// Adds an handler to a server and returns it.
|
||||
Server server = createBaseServer();
|
||||
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war")
|
||||
.getPath();
|
||||
Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
|
||||
server.setHandler(webAppHandler);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a server which delegates the request handling to both a logging
|
||||
* handler and to a web application, in this order.
|
||||
*
|
||||
* @return a server
|
||||
*/
|
||||
public static Server createMultiHandlerServer() {
|
||||
Server server = createBaseServer();
|
||||
|
||||
// Creates the handlers and adds them to the server.
|
||||
HandlerCollection handlers = new HandlerCollection();
|
||||
|
||||
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war")
|
||||
.getPath();
|
||||
Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
|
||||
handlers.addHandler(customRequestHandler);
|
||||
|
||||
Handler loggingRequestHandler = new LoggingRequestHandler();
|
||||
handlers.addHandler(loggingRequestHandler);
|
||||
|
||||
server.setHandler(handlers);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.eclipse.jetty.server.Handler;
|
||||
import org.eclipse.jetty.server.Request;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Handler implementation which simply logs that a request has been received.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class LoggingRequestHandler implements Handler {
|
||||
|
||||
/**
|
||||
* Logger.
|
||||
*/
|
||||
private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class);
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org.
|
||||
* eclipse.jetty.util.component.LifeCycle.Listener)
|
||||
*/
|
||||
@Override
|
||||
public void addLifeCycleListener(Listener arg0) {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isFailed()
|
||||
*/
|
||||
@Override
|
||||
public boolean isFailed() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isRunning()
|
||||
*/
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStarted()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStarted() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStarting()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStarting() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStopped()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStopped() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#isStopping()
|
||||
*/
|
||||
@Override
|
||||
public boolean isStopping() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
|
||||
* eclipse.jetty.util.component.LifeCycle.Listener)
|
||||
*/
|
||||
@Override
|
||||
public void removeLifeCycleListener(Listener arg0) {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#start()
|
||||
*/
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.util.component.LifeCycle#stop()
|
||||
*/
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#destroy()
|
||||
*/
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#getServer()
|
||||
*/
|
||||
@Override
|
||||
public Server getServer() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
|
||||
* org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse)
|
||||
*/
|
||||
@Override
|
||||
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3)
|
||||
throws IOException, ServletException {
|
||||
LOG.info("Received a new request");
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
|
||||
* Server)
|
||||
*/
|
||||
@Override
|
||||
public void setServer(Server server) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ChannelHandlerA extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
throw new Exception("Ooops");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
logger.info("Exception Occurred in ChannelHandler A");
|
||||
ctx.fireExceptionCaught(cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
logger.info("Exception Handled in ChannelHandler B");
|
||||
logger.info(cause.getLocalizedMessage());
|
||||
//do more exception handling
|
||||
ctx.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
|
||||
public class NettyServerB {
|
||||
|
||||
private int port;
|
||||
|
||||
private NettyServerB(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
private void run() throws Exception {
|
||||
|
||||
EventLoopGroup bossGroup = new NioEventLoopGroup();
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||
|
||||
try {
|
||||
ServerBootstrap b = new ServerBootstrap();
|
||||
b.group(bossGroup, workerGroup)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
public void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB());
|
||||
}
|
||||
})
|
||||
.option(ChannelOption.SO_BACKLOG, 128)
|
||||
.childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||
ChannelFuture f = b.bind(port).sync(); // (7)
|
||||
f.channel().closeFuture().sync();
|
||||
} finally {
|
||||
workerGroup.shutdownGracefully();
|
||||
bossGroup.shutdownGracefully();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new NettyServerB(8080).run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.smooks.converter;
|
||||
|
||||
import com.baeldung.smooks.model.Order;
|
||||
import org.milyn.Smooks;
|
||||
import org.milyn.payload.JavaResult;
|
||||
import org.milyn.payload.StringResult;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.transform.stream.StreamSource;
|
||||
import java.io.IOException;
|
||||
|
||||
public class OrderConverter {
|
||||
|
||||
public Order convertOrderXMLToOrderObject(String path) throws IOException, SAXException {
|
||||
Smooks smooks = new Smooks(OrderConverter.class.getResourceAsStream("/smooks/smooks-mapping.xml"));
|
||||
try {
|
||||
JavaResult javaResult = new JavaResult();
|
||||
smooks.filterSource(new StreamSource(OrderConverter.class.getResourceAsStream(path)), javaResult);
|
||||
return (Order) javaResult.getBean("order");
|
||||
} finally {
|
||||
smooks.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException {
|
||||
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml");
|
||||
}
|
||||
|
||||
public String convertOrderXMLtoEmailMessage(String path) throws IOException, SAXException {
|
||||
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-email.xml");
|
||||
}
|
||||
|
||||
private String convertDocumentWithTempalte(String path, String config) throws IOException, SAXException {
|
||||
Smooks smooks = new Smooks(config);
|
||||
|
||||
try {
|
||||
StringResult stringResult = new StringResult();
|
||||
smooks.filterSource(new StreamSource(OrderConverter.class.getResourceAsStream(path)), stringResult);
|
||||
return stringResult.toString();
|
||||
} finally {
|
||||
smooks.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.smooks.converter;
|
||||
|
||||
import org.milyn.Smooks;
|
||||
import org.milyn.payload.JavaResult;
|
||||
import org.milyn.payload.StringResult;
|
||||
import org.milyn.validation.ValidationResult;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.transform.stream.StreamSource;
|
||||
import java.io.IOException;
|
||||
|
||||
public class OrderValidator {
|
||||
|
||||
public ValidationResult validate(String path) throws IOException, SAXException {
|
||||
Smooks smooks = new Smooks(OrderValidator.class.getResourceAsStream("/smooks/smooks-validation.xml"));
|
||||
|
||||
try {
|
||||
StringResult xmlResult = new StringResult();
|
||||
JavaResult javaResult = new JavaResult();
|
||||
ValidationResult validationResult = new ValidationResult();
|
||||
smooks.filterSource(new StreamSource(OrderValidator.class.getResourceAsStream(path)), xmlResult, javaResult, validationResult);
|
||||
return validationResult;
|
||||
} finally {
|
||||
smooks.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.smooks.model;
|
||||
|
||||
public class Item {
|
||||
|
||||
public Item() {
|
||||
}
|
||||
|
||||
public Item(String code, Double price, Integer quantity) {
|
||||
this.code = code;
|
||||
this.price = price;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
private String code;
|
||||
private Double price;
|
||||
private Integer quantity;
|
||||
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Item item = (Item) o;
|
||||
|
||||
if (code != null ? !code.equals(item.code) : item.code != null) return false;
|
||||
if (price != null ? !price.equals(item.price) : item.price != null) return false;
|
||||
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = code != null ? code.hashCode() : 0;
|
||||
result = 31 * result + (price != null ? price.hashCode() : 0);
|
||||
result = 31 * result + (quantity != null ? quantity.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Item{" +
|
||||
"code='" + code + '\'' +
|
||||
", price=" + price +
|
||||
", quantity=" + quantity +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.smooks.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
public class Order {
|
||||
private Date creationDate;
|
||||
private Long number;
|
||||
private Status status;
|
||||
private Supplier supplier;
|
||||
private List<Item> items;
|
||||
|
||||
public Date getCreationDate() {
|
||||
return creationDate;
|
||||
}
|
||||
|
||||
public void setCreationDate(Date creationDate) {
|
||||
this.creationDate = creationDate;
|
||||
}
|
||||
|
||||
public Long getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(Long number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public Status getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Status status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Supplier getSupplier() {
|
||||
return supplier;
|
||||
}
|
||||
|
||||
public void setSupplier(Supplier supplier) {
|
||||
this.supplier = supplier;
|
||||
}
|
||||
|
||||
public List<Item> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<Item> items) {
|
||||
this.items = items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.smooks.model;
|
||||
|
||||
public enum Status {
|
||||
NEW, IN_PROGRESS, FINISHED
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.smooks.model;
|
||||
|
||||
public class Supplier {
|
||||
|
||||
private String name;
|
||||
private String phoneNumber;
|
||||
|
||||
public Supplier() {
|
||||
}
|
||||
|
||||
public Supplier(String name, String phoneNumber) {
|
||||
this.name = name;
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getPhoneNumber() {
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Supplier supplier = (Supplier) o;
|
||||
|
||||
if (name != null ? !name.equals(supplier.name) : supplier.name != null) return false;
|
||||
return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = name != null ? name.hashCode() : 0;
|
||||
result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<#setting locale="en_US">
|
||||
Hi,
|
||||
Order number #${order.number} created on ${order.creationDate?string["yyyy-MM-dd"]} is currently in ${order.status} status.
|
||||
Consider contact supplier "${supplier.name}" with phone number: "${supplier.phoneNumber}".
|
||||
Order items:
|
||||
<#list items as item>
|
||||
${item.quantity} X ${item.code} (total price ${item.price * item.quantity})
|
||||
</#list>
|
||||
@@ -0,0 +1 @@
|
||||
"max_total","item.quantity * item.price < 300.00"
|
||||
|
@@ -0,0 +1,7 @@
|
||||
<#setting locale="en_US">
|
||||
UNA:+.? '
|
||||
UNH+${order.number}+${order.status}+${order.creationDate?string["yyyy-MM-dd"]}'
|
||||
CTA+${supplier.name}+${supplier.phoneNumber}'
|
||||
<#list items as item>
|
||||
LIN+${item.quantity}+${item.code}+${item.price}'
|
||||
</#list>
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"creationDate":"2018-01-14",
|
||||
"orderNumber":771,
|
||||
"orderStatus":"IN_PROGRESS",
|
||||
"supplier":{
|
||||
"name":"CompanyX",
|
||||
"phone":"1234567"
|
||||
},
|
||||
"orderItems":[
|
||||
{
|
||||
"quantity":1,
|
||||
"code":"PX1234",
|
||||
"price":9.99
|
||||
},
|
||||
{
|
||||
"quantity":2,
|
||||
"code":"RX1990",
|
||||
"price":120.32
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<order creation-date="2018-01-14">
|
||||
<order-number>771</order-number>
|
||||
<order-status>IN_PROGRESS</order-status>
|
||||
<supplier>
|
||||
<name>CompanyX</name>
|
||||
<phone>1234567</phone>
|
||||
</supplier>
|
||||
<order-items>
|
||||
<item>
|
||||
<quantity>1</quantity>
|
||||
<code>PX1234</code>
|
||||
<price>9.99</price>
|
||||
</item>
|
||||
<item>
|
||||
<quantity>2</quantity>
|
||||
<code>RX990</code>
|
||||
<price>120.32</price>
|
||||
</item>
|
||||
</order-items>
|
||||
</order>
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0"?>
|
||||
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
|
||||
xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd">
|
||||
|
||||
<jb:bean beanId="order" class="com.baeldung.smooks.model.Order" createOnElement="order">
|
||||
<jb:value property="number" data="order/order-number" />
|
||||
<jb:value property="status" data="order/order-status" />
|
||||
<jb:value property="creationDate" data="order/@creation-date" decoder="Date">
|
||||
<jb:decodeParam name="format">yyyy-MM-dd</jb:decodeParam>
|
||||
</jb:value>
|
||||
<jb:wiring property="supplier" beanIdRef="supplier" />
|
||||
<jb:wiring property="items" beanIdRef="items" />
|
||||
</jb:bean>
|
||||
|
||||
<jb:bean beanId="supplier" class="com.baeldung.smooks.model.Supplier" createOnElement="supplier">
|
||||
<jb:value property="name" data="name" />
|
||||
<jb:value property="phoneNumber" data="phone" />
|
||||
</jb:bean>
|
||||
|
||||
<jb:bean beanId="items" class="java.util.ArrayList" createOnElement="order">
|
||||
<jb:wiring beanIdRef="item" />
|
||||
</jb:bean>
|
||||
<jb:bean beanId="item" class="com.baeldung.smooks.model.Item" createOnElement="item">
|
||||
<jb:value property="code" data="item/code" />
|
||||
<jb:value property="price" decoder="Double" data="item/price" />
|
||||
<jb:value property="quantity" decoder="Integer" data="item/quantity" />
|
||||
</jb:bean>
|
||||
|
||||
</smooks-resource-list>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
|
||||
xmlns:ftl="http://www.milyn.org/xsd/smooks/freemarker-1.1.xsd">
|
||||
|
||||
<import file="smooks-validation.xml" />
|
||||
|
||||
<ftl:freemarker applyOnElement="#document">
|
||||
<ftl:template>/smooks/order.ftl</ftl:template>
|
||||
</ftl:freemarker>
|
||||
|
||||
</smooks-resource-list>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
|
||||
xmlns:ftl="http://www.milyn.org/xsd/smooks/freemarker-1.1.xsd">
|
||||
|
||||
|
||||
<import file="smooks-validation.xml" />
|
||||
|
||||
<ftl:freemarker applyOnElement="#document">
|
||||
<ftl:template>/smooks/email.ftl</ftl:template>
|
||||
</ftl:freemarker>
|
||||
|
||||
</smooks-resource-list>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0"?>
|
||||
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
|
||||
xmlns:rules="http://www.milyn.org/xsd/smooks/rules-1.0.xsd"
|
||||
xmlns:validation="http://www.milyn.org/xsd/smooks/validation-1.0.xsd">
|
||||
|
||||
<import file="/smooks/smooks-mapping.xml" />
|
||||
|
||||
<rules:ruleBases>
|
||||
<rules:ruleBase name="supplierValidation" src="/smooks/supplier.properties" provider="org.milyn.rules.regex.RegexProvider"/>
|
||||
<rules:ruleBase name="itemsValidation" src="/smooks/item-rules.csv" provider="org.milyn.rules.mvel.MVELProvider"/>
|
||||
</rules:ruleBases>
|
||||
|
||||
<validation:rule executeOn="supplier/name" name="supplierValidation.supplierName" onFail="ERROR"/>
|
||||
<validation:rule executeOn="supplier/phone" name="supplierValidation.supplierPhone" onFail="ERROR"/>
|
||||
<validation:rule executeOn="order-items/item" name="itemsValidation.max_total" onFail="ERROR"/>
|
||||
|
||||
</smooks-resource-list>
|
||||
@@ -0,0 +1,2 @@
|
||||
supplierName=[A-Za-z0-9]*
|
||||
supplierPhone=^[0-9\\-\\+]{9,15}$
|
||||
@@ -0,0 +1,209 @@
|
||||
package com.baeldung.asynchttpclient;
|
||||
|
||||
import io.netty.handler.codec.http.HttpHeaders;
|
||||
import org.asynchttpclient.AsyncCompletionHandler;
|
||||
import org.asynchttpclient.AsyncHandler;
|
||||
import org.asynchttpclient.AsyncHttpClient;
|
||||
import org.asynchttpclient.AsyncHttpClientConfig;
|
||||
import org.asynchttpclient.BoundRequestBuilder;
|
||||
import org.asynchttpclient.Dsl;
|
||||
import org.asynchttpclient.HttpResponseBodyPart;
|
||||
import org.asynchttpclient.HttpResponseStatus;
|
||||
import org.asynchttpclient.ListenableFuture;
|
||||
import org.asynchttpclient.Request;
|
||||
import org.asynchttpclient.Response;
|
||||
import org.asynchttpclient.ws.WebSocket;
|
||||
import org.asynchttpclient.ws.WebSocketListener;
|
||||
import org.asynchttpclient.ws.WebSocketUpgradeHandler;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class AsyncHttpClientTestCase {
|
||||
|
||||
private static AsyncHttpClient HTTP_CLIENT;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
AsyncHttpClientConfig clientConfig = Dsl.config().setConnectTimeout(15000).setRequestTimeout(15000).build();
|
||||
HTTP_CLIENT = Dsl.asyncHttpClient(clientConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeSyncGetRequest() {
|
||||
|
||||
BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
|
||||
|
||||
Future<Response> responseFuture = boundGetRequest.execute();
|
||||
try {
|
||||
Response response = responseFuture.get(5000, TimeUnit.MILLISECONDS);
|
||||
assertNotNull(response);
|
||||
assertEquals(200, response.getStatusCode());
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequest() {
|
||||
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncCompletionHandler<Integer>() {
|
||||
@Override
|
||||
public Integer onCompleted(Response response) {
|
||||
|
||||
int resposeStatusCode = response.getStatusCode();
|
||||
assertEquals(200, resposeStatusCode);
|
||||
return resposeStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
// execute a bound GET request
|
||||
BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
|
||||
|
||||
boundGetRequest.execute(new AsyncCompletionHandler<Integer>() {
|
||||
@Override
|
||||
public Integer onCompleted(Response response) {
|
||||
int resposeStatusCode = response.getStatusCode();
|
||||
assertEquals(200, resposeStatusCode);
|
||||
return resposeStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequestWithAsyncHandler() {
|
||||
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncHandler<Integer>() {
|
||||
|
||||
int responseStatusCode = -1;
|
||||
|
||||
@Override
|
||||
public State onStatusReceived(HttpResponseStatus responseStatus) {
|
||||
responseStatusCode = responseStatus.getStatusCode();
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onHeadersReceived(HttpHeaders headers) {
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) {
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onThrowable(Throwable t) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer onCompleted() {
|
||||
assertEquals(200, responseStatusCode);
|
||||
return responseStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequestWithListanableFuture() {
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
ListenableFuture<Response> listenableFuture = HTTP_CLIENT.executeRequest(unboundGetRequest);
|
||||
listenableFuture.addListener(() -> {
|
||||
Response response;
|
||||
try {
|
||||
response = listenableFuture.get(5000, TimeUnit.MILLISECONDS);
|
||||
assertEquals(200, response.getStatusCode());
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, Executors.newCachedThreadPool());
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWebSocketClient_tryToConnect() {
|
||||
|
||||
WebSocketUpgradeHandler.Builder upgradeHandlerBuilder = new WebSocketUpgradeHandler.Builder();
|
||||
WebSocketUpgradeHandler wsHandler = upgradeHandlerBuilder.addWebSocketListener(new WebSocketListener() {
|
||||
@Override
|
||||
public void onOpen(WebSocket websocket) {
|
||||
// WebSocket connection opened
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(WebSocket websocket, int code, String reason) {
|
||||
// WebSocket connection closed
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
// WebSocket connection error
|
||||
assertTrue(t.getMessage().contains("Request timeout"));
|
||||
}
|
||||
}).build();
|
||||
|
||||
WebSocket WEBSOCKET_CLIENT = null;
|
||||
try {
|
||||
WEBSOCKET_CLIENT = Dsl.asyncHttpClient()
|
||||
.prepareGet("ws://localhost:5590/websocket")
|
||||
.addHeader("header_name", "header_value")
|
||||
.addQueryParam("key", "value")
|
||||
.setRequestTimeout(5000)
|
||||
.execute(wsHandler).get();
|
||||
|
||||
if (WEBSOCKET_CLIENT.isOpen()) {
|
||||
WEBSOCKET_CLIENT.sendPingFrame();
|
||||
WEBSOCKET_CLIENT.sendTextFrame("test message");
|
||||
WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'});
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (WEBSOCKET_CLIENT != null && WEBSOCKET_CLIENT.isOpen()) {
|
||||
WEBSOCKET_CLIENT.sendCloseFrame(200, "OK");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.jetty;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Test for {@link JettyServerFactory}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class JettyServerFactoryUnitTest {
|
||||
|
||||
/**
|
||||
* Tests that when a base server is provided a request returns a status 404.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception {
|
||||
Server server = JettyServerFactory.createBaseServer();
|
||||
server.start();
|
||||
|
||||
int statusCode = sendGetRequest();
|
||||
|
||||
Assert.assertEquals(404, statusCode);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that when a web app server is provided a request returns a status
|
||||
* 200.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception {
|
||||
Server server = JettyServerFactory.createWebAppServer();
|
||||
server.start();
|
||||
|
||||
int statusCode = sendGetRequest();
|
||||
|
||||
Assert.assertEquals(200, statusCode);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that when a multi handler server is provided a request returns a
|
||||
* status 200.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception {
|
||||
Server server = JettyServerFactory.createMultiHandlerServer();
|
||||
server.start();
|
||||
|
||||
int statusCode = sendGetRequest();
|
||||
|
||||
Assert.assertEquals(200, statusCode);
|
||||
server.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a default HTTP GET request to the server and returns the response
|
||||
* status code.
|
||||
*
|
||||
* @return the status code of the response
|
||||
* @throws Exception
|
||||
*/
|
||||
private int sendGetRequest() throws Exception {
|
||||
HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT);
|
||||
HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH);
|
||||
HttpClient client = HttpClientBuilder.create().build();
|
||||
HttpResponse response = client.execute(target, request);
|
||||
return response.getStatusLine().getStatusCode();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -32,9 +32,9 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
headers.put("Content-Type", "application/json");
|
||||
|
||||
return builder
|
||||
.given("test GET ")
|
||||
.given("test GET")
|
||||
.uponReceiving("GET REQUEST")
|
||||
.path("/")
|
||||
.path("/pact")
|
||||
.method("GET")
|
||||
.willRespondWith()
|
||||
.status(200)
|
||||
@@ -45,11 +45,9 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
.method("POST")
|
||||
.headers(headers)
|
||||
.body("{\"name\": \"Michael\"}")
|
||||
.path("/create")
|
||||
.path("/pact")
|
||||
.willRespondWith()
|
||||
.status(201)
|
||||
.headers(headers)
|
||||
.body("")
|
||||
.toPact();
|
||||
}
|
||||
|
||||
@@ -59,7 +57,7 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
||||
//when
|
||||
ResponseEntity<String> response
|
||||
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
|
||||
= new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class);
|
||||
|
||||
//then
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(200);
|
||||
@@ -73,7 +71,7 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
//when
|
||||
ResponseEntity<String> postResponse = new RestTemplate().exchange(
|
||||
mockProvider.getUrl() + "/create",
|
||||
mockProvider.getUrl() + "/pact",
|
||||
HttpMethod.POST,
|
||||
new HttpEntity<>(jsonBody, httpHeaders),
|
||||
String.class
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.smooks.converter;
|
||||
|
||||
import com.baeldung.smooks.model.Item;
|
||||
import com.baeldung.smooks.model.Order;
|
||||
import com.baeldung.smooks.model.Status;
|
||||
import com.baeldung.smooks.model.Supplier;
|
||||
import org.junit.Test;
|
||||
import org.milyn.validation.ValidationResult;
|
||||
import java.text.SimpleDateFormat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class SmooksIntegrationTest {
|
||||
|
||||
private static final String EDIFACT_MESSAGE =
|
||||
"UNA:+.? '\r\n" +
|
||||
"UNH+771+IN_PROGRESS+2018-01-14'\r\n" +
|
||||
"CTA+CompanyX+1234567'\r\n" +
|
||||
"LIN+1+PX1234+9.99'\r\n" +
|
||||
"LIN+2+RX990+120.32'\r\n";
|
||||
private static final String EMAIL_MESSAGE =
|
||||
"Hi,\r\n" +
|
||||
"Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" +
|
||||
"Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" +
|
||||
"Order items:\r\n" +
|
||||
"1 X PX1234 (total price 9.99)\r\n" +
|
||||
"2 X RX990 (total price 240.64)\r\n";
|
||||
|
||||
@Test
|
||||
public void givenOrderXML_whenConvert_thenPOJOsConstructedCorrectly() throws Exception {
|
||||
|
||||
OrderConverter xmlToJavaOrderConverter = new OrderConverter();
|
||||
Order order = xmlToJavaOrderConverter.convertOrderXMLToOrderObject("/smooks/order.xml");
|
||||
|
||||
assertThat(order.getNumber(),is(771L));
|
||||
assertThat(order.getStatus(),is(Status.IN_PROGRESS));
|
||||
assertThat(order.getCreationDate(),is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14")));
|
||||
assertThat(order.getSupplier(),is(new Supplier("CompanyX","1234567")));
|
||||
assertThat(order.getItems(),containsInAnyOrder(
|
||||
new Item("PX1234",9.99,1),
|
||||
new Item("RX990",120.32,2))
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIncorrectOrderXML_whenValidate_thenExpectValidationErrors() throws Exception {
|
||||
OrderValidator orderValidator = new OrderValidator();
|
||||
ValidationResult validationResult = orderValidator.validate("/smooks/order.xml");
|
||||
|
||||
assertThat(validationResult.getErrors(), hasSize(1));
|
||||
// 1234567 didn't match ^[0-9\\-\\+]{9,15}$
|
||||
assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(),is("supplierPhone"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderXML_whenApplyEDITemplate_thenConvertedToEDIFACT() throws Exception {
|
||||
OrderConverter orderConverter = new OrderConverter();
|
||||
String edifact = orderConverter.convertOrderXMLtoEDIFACT("/smooks/order.xml");
|
||||
assertThat(edifact,is(EDIFACT_MESSAGE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOrderXML_whenApplyEmailTemplate_thenConvertedToEmailMessage() throws Exception {
|
||||
OrderConverter orderConverter = new OrderConverter();
|
||||
String emailMessage = orderConverter.convertOrderXMLtoEmailMessage("/smooks/order.xml");
|
||||
assertThat(emailMessage,is(EMAIL_MESSAGE));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Reference in New Issue
Block a user