Consuming Rabbit MQ messages using Eclipse on Tomcat - eclipse

I am using Eclipse, Tomcat and Rabbit MQ.
I want to be able to consume messages of a queue as soon as they hit the queue. I have managed to do this using a Java class in Eclipse (see below), but have not been able to get this working when deploying the WAR file on the Tomcat server.
package org.com.hello;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
public class HelloRecv {
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("172.24.3.53");
factory.setPort(6672);
factory.setUsername("user");
factory.setPassword("password");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("q1", true, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume("q1", true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
Is there something I need to add like a web.xml file and if so, what should I add to this file?

Create a war application using eclipse:
you can see this video:
https://www.youtube.com/watch?v=fk22hQz9L_M
or googling then copy you code inside a servlet. You should use the init method.
an pseudo code:
public class YourServlet extends HttpServlet {
int count;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("172.24.3.53");
factory.setPort(6672);
factory.setUsername("user");
factory.setPassword("password");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("q1", true, false, false, null);
/// you shoud put the consumer inside a thread.
channel.basicConsume("q1", true, new DefaultConsumer(){
/// here you should use Default consumer and not QueueingConsumer because is blocking
});
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
.....
}
}
See also DefaultConsumer
Hope it helps

Related

I am not getting results from ksql StreamQuery integrated with java. when I am printing log for client is showing not completed

I am using confluent kafka version 6.o
downloaded from https://www.confluent.io/download/
I am referring
https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-clients/java-client/ acritical .
https://www.youtube.com/watch?v=85udigshlNI
with java producer code I am able to send value to ksql. But not able to retrieve this value.
when I am printing log for streamQuery result, I am getting Not Completed message.
used Maven dependency as:
<dependencies>
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-api-client</artifactId>
<version>${ksqldb.version}</version>
</dependency>
</dependencies>
java code :
public class ExampleApp {
public static String KSQLDB_SERVER_HOST = "localhost";
public static int KSQLDB_SERVER_HOST_PORT = 8088;
public static void main(String[] args) {
ClientOptions options = ClientOptions.create()
.setHost(KSQLDB_SERVER_HOST)
.setPort(KSQLDB_SERVER_HOST_PORT);
Client client = Client.create(options);
// Send requests with the client by following the other examples
// Terminate any open connections and close the client
client.close();
}
}public class ExampleApp {
public static String KSQLDB_SERVER_HOST = "localhost";
public static int KSQLDB_SERVER_HOST_PORT = 8088;
public static void main(String[] args) {
ClientOptions options = ClientOptions.create()
.setHost(KSQLDB_SERVER_HOST)
.setPort(KSQLDB_SERVER_HOST_PORT);
Client client = Client.create(options);
StreamedQueryResult streamedQueryResult = client.streamQuery("SELECT * FROM MY_STREAM EMIT CHANGES;").get();
for (int i = 0; i < 10; i++) {
// Block until a new row is available
Row row = streamedQueryResult.poll();
if (row != null) {
System.out.println("Received a row!");
System.out.println("Row: " + row.values());
} else {
System.out.println("Query has ended.");
}
}
client.close();
}
}
output :
get() is waiting for long time even after adding values into topic waiting and finally gives timeout exception.

Netty connection pool not sending messages to server

I have a simple netty connection pool and a simple HTTP endpoint to use that pool to send TCP messages to ServerSocket. The relevant code looks like this, the client (NettyConnectionPoolClientApplication) is:
#SpringBootApplication
#RestController
public class NettyConnectionPoolClientApplication {
private SimpleChannelPool simpleChannelPool;
public static void main(String[] args) {
SpringApplication.run(NettyConnectionPoolClientApplication.class, args);
}
#PostConstruct
public void setup() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.remoteAddress(new InetSocketAddress("localhost", 9000));
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new DummyClientHandler());
}
});
simpleChannelPool = new SimpleChannelPool(bootstrap, new DummyChannelPoolHandler());
}
#RequestMapping("/test/{msg}")
public void test(#PathVariable String msg) throws Exception {
Future<Channel> future = simpleChannelPool.acquire();
future.addListener((FutureListener<Channel>) f -> {
if (f.isSuccess()) {
System.out.println("Connected");
Channel ch = f.getNow();
ch.writeAndFlush(msg + System.lineSeparator());
// Release back to pool
simpleChannelPool.release(ch);
} else {
System.out.println("not successful");
}
});
}
}
and the Server (ServerSocketRunner)
public class ServerSocketRunner {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
System.out.println("New client connected");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));) {
String inputLine, outputLine;
out.println("Hello client!");
do {
inputLine = in.readLine();
System.out.println("Received: " + inputLine);
} while (!"bye".equals(inputLine));
System.out.println("Closing connection...");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
DummyChannelPoolHandler and DummyClientHandler just print out events that happen, so they are not relevant. When the server and the client are started and I send a test message to test endpoint, I can see the server prints "New client connected" but the message sent by client is not printed. None of the consecutive messages sent by client are printed by the server.
If I try telnet, everything works fine, the server prints out messages. Also it works fine with regular netty client with same bootstrap config and without connection pool (SimpleNettyClientApplication).
Can anyone see what is wrong with my connection pool, I'm out of ideas
Netty versioin: 4.1.39.Final
All the code is available here.
UPDATE
Following Norman Maurer advice. I added
ChannelFuture channelFuture = ch
.writeAndFlush(msg + System.lineSeparator());
channelFuture.addListener(writeFuture -> {
System.out
.println("isSuccess(): " + channelFuture.isSuccess() + " : " + channelFuture.cause());
});
This prints out
isSuccess: false : java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion)
To fix it, I just converted String into ByteBuf
ch.writeAndFlush(Unpooled.wrappedBuffer((msg + System.lineSeparator()).getBytes()));
You should check what the status of the ChannelFuture is that is returned by writeAndFlush(...). I suspect it is failed.

Spring Cloud - Getting Retry Working In RestTemplate?

I have been migrating an existing application over to Spring Cloud's service discovery, Ribbon load balancing, and circuit breakers. The application already makes extensive use of the RestTemplate and I have been able to successfully use the load balanced version of the template. However, I have been testing the situation where there are two instances of a service and I drop one of those instances out of operation. I would like the RestTemplate to failover to the next server. From the research I have done, it appears that the fail-over logic exists in the Feign client and when using Zuul. It appears that the LoadBalancedRest template does not have logic for fail-over. In diving into the code, it looks like the RibbonClientHttpRequestFactory is using the netflix RestClient (which appears to have logic for doing retries).
So where do I go from here to get this working?
I would prefer to not use the Feign client because I would have to sweep A LOT of code.
I had found this link that suggested using the #Retryable annotation along with #HystrixCommand but this seems like something that should be a part of the load balanced rest template.
I did some digging into the code for RibbonClientHttpRequestFactory.RibbonHttpRequest:
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
try {
addHeaders(headers);
if (outputStream != null) {
outputStream.close();
builder.entity(outputStream.toByteArray());
}
HttpRequest request = builder.build();
HttpResponse response = client.execute(request, config);
return new RibbonHttpResponse(response);
}
catch (Exception e) {
throw new IOException(e);
}
}
It appears that if I override this method and change it to use "client.executeWithLoadBalancer()" that I might be able to leverage the retry logic that is built into the RestClient? I guess I could create my own version of the RibbonClientHttpRequestFactory to do this?
Just looking for guidance on the best approach.
Thanks
To answer my own question:
Before I get into the details, a cautionary tale:
Eureka's self preservation mode sent me down a rabbit hole while testing the fail-over on my local machine. I recommend turning self preservation mode off while doing your testing. Because I was dropping nodes at a regular rate and then restarting (with a different instance ID using a random value), I tripped Eureka's self preservation mode. I ended up with many instances in Eureka that pointed to the same machine, same port. The fail-over was actually working but the next node that was chosen happened to be another dead instance. Very confusing at first!
I was able to get fail-over working with a modified version of RibbonClientHttpRequestFactory. Because RibbonAutoConfiguration creates a load balanced RestTemplate with this factory, rather then injecting this rest template, I create a new one with my modified version of the request factory:
protected RestTemplate restTemplate;
#Autowired
public void customizeRestTemplate(SpringClientFactory springClientFactory, LoadBalancerClient loadBalancerClient) {
restTemplate = new RestTemplate();
// Use a modified version of the http request factory that leverages the load balacing in netflix's RestClient.
RibbonRetryHttpRequestFactory lFactory = new RibbonRetryHttpRequestFactory(springClientFactory, loadBalancerClient);
restTemplate.setRequestFactory(lFactory);
}
The modified Request Factory is just a copy of RibbonClientHttpRequestFactory with two minor changes:
1) In createRequest, I removed the code that was selecting a server from the load balancer because the RestClient will do that for us.
2) In the inner class, RibbonHttpRequest, I changed executeInternal to call "executeWithLoadBalancer".
The full class:
#SuppressWarnings("deprecation")
public class RibbonRetryHttpRequestFactory implements ClientHttpRequestFactory {
private final SpringClientFactory clientFactory;
private LoadBalancerClient loadBalancer;
public RibbonRetryHttpRequestFactory(SpringClientFactory clientFactory, LoadBalancerClient loadBalancer) {
this.clientFactory = clientFactory;
this.loadBalancer = loadBalancer;
}
#Override
public ClientHttpRequest createRequest(URI originalUri, HttpMethod httpMethod) throws IOException {
String serviceId = originalUri.getHost();
IClientConfig clientConfig = clientFactory.getClientConfig(serviceId);
RestClient client = clientFactory.getClient(serviceId, RestClient.class);
HttpRequest.Verb verb = HttpRequest.Verb.valueOf(httpMethod.name());
return new RibbonHttpRequest(originalUri, verb, client, clientConfig);
}
public class RibbonHttpRequest extends AbstractClientHttpRequest {
private HttpRequest.Builder builder;
private URI uri;
private HttpRequest.Verb verb;
private RestClient client;
private IClientConfig config;
private ByteArrayOutputStream outputStream = null;
public RibbonHttpRequest(URI uri, HttpRequest.Verb verb, RestClient client, IClientConfig config) {
this.uri = uri;
this.verb = verb;
this.client = client;
this.config = config;
this.builder = HttpRequest.newBuilder().uri(uri).verb(verb);
}
#Override
public HttpMethod getMethod() {
return HttpMethod.valueOf(verb.name());
}
#Override
public URI getURI() {
return uri;
}
#Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
if (outputStream == null) {
outputStream = new ByteArrayOutputStream();
}
return outputStream;
}
#Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
try {
addHeaders(headers);
if (outputStream != null) {
outputStream.close();
builder.entity(outputStream.toByteArray());
}
HttpRequest request = builder.build();
HttpResponse response = client.executeWithLoadBalancer(request, config);
return new RibbonHttpResponse(response);
}
catch (Exception e) {
throw new IOException(e);
}
//TODO: fix stats, now that execute is not called
// use execute here so stats are collected
/*
return loadBalancer.execute(this.config.getClientName(), new LoadBalancerRequest<ClientHttpResponse>() {
#Override
public ClientHttpResponse apply(ServiceInstance instance) throws Exception {}
});
*/
}
private void addHeaders(HttpHeaders headers) {
for (String name : headers.keySet()) {
// apache http RequestContent pukes if there is a body and
// the dynamic headers are already present
if (!isDynamic(name) || outputStream == null) {
List<String> values = headers.get(name);
for (String value : values) {
builder.header(name, value);
}
}
}
}
private boolean isDynamic(String name) {
return name.equals("Content-Length") || name.equals("Transfer-Encoding");
}
}
public class RibbonHttpResponse extends AbstractClientHttpResponse {
private HttpResponse response;
private HttpHeaders httpHeaders;
public RibbonHttpResponse(HttpResponse response) {
this.response = response;
this.httpHeaders = new HttpHeaders();
List<Map.Entry<String, String>> headers = response.getHttpHeaders().getAllHeaders();
for (Map.Entry<String, String> header : headers) {
this.httpHeaders.add(header.getKey(), header.getValue());
}
}
#Override
public InputStream getBody() throws IOException {
return response.getInputStream();
}
#Override
public HttpHeaders getHeaders() {
return this.httpHeaders;
}
#Override
public int getRawStatusCode() throws IOException {
return response.getStatus();
}
#Override
public String getStatusText() throws IOException {
return HttpStatus.valueOf(response.getStatus()).name();
}
#Override
public void close() {
response.close();
}
}
}
I had the same problem but then, out of the box, everything was working (using a #LoadBalanced RestTemplate). I am using Finchley version of Spring Cloud, and I think my problem was that I was not explicity adding spring-retry in my pom configuration. I'll leave here my spring-retry related yml configuration (remember this only works with #LoadBalanced RestTemplate, Zuul of Feign):
spring:
# Ribbon retries on
cloud:
loadbalancer:
retry:
enabled: true
# Ribbon service config
my-service:
ribbon:
MaxAutoRetries: 3
MaxAutoRetriesNextServer: 1
OkToRetryOnAllOperations: true
retryableStatusCodes: 500, 502

Camel Restlet and CXF SOA Integration Issue

I am new to Camel and am facing an issue with a route I need to setup. It will be great if someone can either guide me to the correct forum or better still rectify the issue I am facing.
Here is what I need to do - expose a restlet endpoint to accept data; use this data as input to an external SOAP web service and send back the response in JSON format back to the caller...
Here is what I have done...however, I am getting the following error while Camel tries to call the Web Service...can anyone guide me here? Thanks.
I am using camel 2.11.1 and cxf-codegen-plugin version 2.7.11
I am getting the following exception: org.restlet.data.Parameter cannot be cast to java.lang.String.
public class IntegrationTest extends CamelTestSupport {
String restletURL = <url>;
#org.junit.Test
public void integTest() throws Exception {
//trying to simulate the rest service call...
template.sendBodyAndHeader(restletURL, "Body does not matter here", "data", "{\"FromCurrency\":\"AUD\",\"ToCurrency\":\"USD\"}");
}
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
System.out.println("In Counfigure");
String cxfEndpoint = "cxf://http://www.webservicex.net/CurrencyConvertor.asmx?"
+ "wsdlURL=http://www.webservicex.net/CurrencyConvertor.asmx?wsdl&"
+ "serviceName={http://www.webserviceX.NET/}CurrencyConvertor&"
+ "portName={http://www.webserviceX.NET/}CurrencyConvertorSoap&"
+ "dataFormat=MESSAGE";
XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
SoapJaxbDataFormat soap = new SoapJaxbDataFormat("net.webservicex", new ServiceInterfaceStrategy(CurrencyConvertorSoap.class, true));
GsonDataFormat gson = new GsonDataFormat(ConversionRate.class);
gson.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
from(restletURL).routeId("Restlet")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
String data = (String) URLDecoder.decode((String) exchange.getIn().getHeader("data"), "UTF-8");
System.out.println(data);
// get the mail body as a String
exchange.getIn().setBody(data);
Response.getCurrent().setStatus(Status.SUCCESS_OK);
}
})
.unmarshal(gson)
.marshal(soap)
.log("${body}")
.to(cxfEndpoint)
.unmarshal(soap)
.marshal(xmlJsonFormat);
.log("${body}");
}
};
}
}
However, the sample works when I try out the individual pieces - restlet alone and CXF alone...
Thanks,
Ritwick.
Sure Willem, here is the entire configure implementation:
#Override
public void configure() throws Exception {
String restletURL = "restlet:http://localhost:8080/convert/{data}?restletMethods=get";
String cxfEndpoint = "cxf://http://www.webservicex.net/CurrencyConvertor.asmx?"
+ "portName={http://www.webserviceX.NET/}CurrencyConvertorSoap&"
+ "dataFormat=MESSAGE&loggingFeatureEnabled=true&defaultOperationName=ConversionRate&defaultOperationNamespace={http://www.webserviceX.NET/}&synchronous=true";
SoapJaxbDataFormat soap = new SoapJaxbDataFormat("net.webservicex", new ServiceInterfaceStrategy(CurrencyConvertorSoap.class, true));
soap.setVersion("1.2");
GsonDataFormat gson = new GsonDataFormat(ConversionRate.class);
gson.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
from(restletURL).routeId("Restlet")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
String data = (String) URLDecoder.decode((String) exchange.getIn().getHeader("data"), "UTF-8");
exchange.getIn().setHeader("org.restlet.http.headers", "");
exchange.getIn().setHeader("data", "");
exchange.getIn().setBody(data);
Response.getCurrent().setStatus(Status.SUCCESS_OK);
}
})
.unmarshal(gson)
.marshal(soap)
.to(cxfEndpoint)
.unmarshal(soap)
.marshal(gson)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
String output = exchange.getIn().getBody(String.class);
exchange.getOut().setBody(output);
}
});
}
The issue I was facing has been resolved. In addition to "exchange.getIn().setBody(data);", I added the following line of code "exchange.getIn().setHeader("org.restlet.http.headers", "");" in order to get rid of the class cast exception I was getting. The restlet headers were causing this issue and once these headers were removed (I didn't need the headers in the first place), everything worked as expected.
Thanks,
Ritwick.

smartgwt spring servlet and uploading files

I've seen this question here before, but none of the solutions work for me.
I have a SmartGWT app with Spring MVC. This all works great, and I have working RESTful web-services.
I have a form to upload not only the file, but also some meta data as well.
There is an associated DataSource with this form:
private final String DEFAULT_FILE_UPLOAD_SERVICE_PATH = "upload";
private final String TARGET = "uploadTarget";
public FileUploadForm()
{
setEncoding(Encoding.MULTIPART);
setMethod(FormMethod.POST);
setAutoFetchData(false);
setDataSource(fileUploadDS);
setTitleOrientation(TitleOrientation.TOP);
setNumCols(1);
setColWidths("*");
uploadFileIdItem.setRequired(true);
uploadFileIdItem.setDefaultValue(0);
uploadFileIdItem.setVisible(false);
uploadFileIdItem.setShowTitle(false);
// ==========================================================================
fileUploadTypeSelectItem.setShowTitle(false);
fileUploadTypeSelectItem.setName(Constants.FILE_UPLOAD_UPLOADTYPE);
fileUploadTypeSelectItem.setPickListWidth(TEXT_SIZE);
fileUploadTypeSelectItem.setTitle(Constants.TITLE_FILE_UPLOAD_UPLOADTYPE);
fileUploadTypeSelectItem.setOptionDataSource(fileUploadTypeDS);
fileUploadTypeSelectItem.setRequired(true);
fileUploadTypeSelectItem.setDisplayField(Constants.FILE_UPLOAD_UPLOADTYPE_NAME);
fileUploadTypeSelectItem.setValueField(Constants.FILE_UPLOAD_UPLOADTYPE_ID);
fileUploadTypeSelectItem.setDataPath("fileUploadType/fileUploadTypeId");
// ==========================================================================
setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
ButtonItem uploadButton = new ButtonItem("Upload");
uploadButton.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler()
{
#Override
public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event)
{
submitForm();
}
});
FileItem uploadItem = new FileItem(Constants.FILENAME);
uploadItem.setTitle(Constants.FILENAME);
setFields(uploadFileIdItem, fileUploadTypeSelectItem, uploadItem, uploadButton);
}
So, I don't know if I need to use:
setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
or
setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
or
setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
None of these seem to work, I submit my data to upload the filename, and I constantly get the HTTP 404 error.
I did not define anything extra special in the web.xml file for servlets.
Instead, the springmvc-servlet contains:
<context:component-scan base-package="com.myself.products.app.server.controller" />
And the servlet is actually defined like:
#SuppressWarnings("serial")
#Controller
#RequestMapping("/upload")
public class FileUploadServlet extends HttpServlet
{
private final Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.process(request, response);
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// check that we have a file upload request
if (ServletFileUpload.isMultipartContent(request))
{
processFiles(request, response);
}
}
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/files/upload";
private File destinationDir;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
tmpDir = new File(((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).toString());
if (!tmpDir.isDirectory())
{
throw new ServletException(tmpDir.toString() + " is not a directory");
}
logger.debug("tmpDir: " + tmpDir.toString());
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory())
{
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}
private void processFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
// create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// set the size threshold, above which content will be stored on disk
factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
// set the temporary directory (this is where files that exceed the threshold will be stored)
factory.setRepository(tmpDir);
// create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// parse the request
List<?> items = upload.parseRequest(request);
// process the uploaded items
Iterator<?> itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
// write the uploaded file to the application's file staging area
File file = new File(destinationDir, item.getName());
item.write(file);
}
}
catch (FileUploadException e)
{
logger.error("Error encountered while parsing the request", e);
}
catch (Exception e)
{
logger.error("Error encountered while uploading file", e);
}
}
You've seen this code before along this web-site, and several others.
I'd like to submit the file, AND data if possible, but if not, then how can I submit the form, and then metadata for it?
Any help would be much appreciated.
Simple File Upload GWT Example:
Available here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FileUpload.html
For sending Metadata along with request, need to set the hidden field to panel:
import com.google.gwt.user.client.ui.Hidden;
Hidden hidden = new Hidden();
hidden.setName("json");
hidden.setVisible(false);
hidden.setValue("simpleMetadata:testData");
panel.add(hidden);
I will suggest you to seperate saving metadata from uploding a file and have 2 forms. This is what I'm doing and it is working for me:
uploadForm.setAction(GWT.getHostPageBaseURL() + "importServiceName");
uploadForm.setEncoding(Encoding.MULTIPART);
uploadForm.setTarget(TARGET);
uploadForm.setMethod(FormMethod.POST);
fileItem = new UploadItem("file");
fileItem.setTitle("File");
fileItem.setWidth(300);
NamedFrame frame = new NamedFrame(TARGET);
frame.setWidth("1");
frame.setHeight("1");
frame.setVisible(false);
uploadForm.setItems(fileItem);
I'm using NamedFrame to be able to fetch servlet response in gwt code, but this is different story. I'm defining servler manually in web.xml