Hide server version from header in jetty - eclipse

I know config.setSendServerVersion(false); should hide the server version from Header.
But it's not happening even I debug the code get into
public void setSendServerVersion(boolean sendServerVersion) {
this._sendServerVersion = sendServerVersion;
}
And found sendServerVersion always true even we are passing false.
Here is how I'm calling
HttpConfiguration http_config = new HttpConfiguration();
http_config.setOutputBufferSize(32768);
http_config.setSendServerVersion(false);
Can somebody help me out with how to remove the header server?
Content-Type: text/html;charset=utf-8
Date: Thu, 28 Oct 2021 10:57:29 GMT
Server: Jetty(9.4.42.v20210604)
Strict-Transport-Security: max-age=31556926; includeSubDomains
Transfer-Encoding: chunked
.
.
.

Configuring the common Response headers is definitely done with the HttpConfiguration, but it has to be tied to a specific ServerConnector for that configuration to have any impact.
Take this example.
Available on jetty-project/embedded-jetty-cookbook as HttpConfigExample
Pay attention to the branch on embedded-jetty-cookbook, as there are examples for jetty-9.4.x, jetty-10.0.x, and also jetty-11.0.x
package org.eclipse.jetty.cookbook;
import java.io.IOException;
import java.net.URI;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.component.LifeCycle;
public class HttpConfigExample
{
public static void main(String[] args) throws Exception
{
Server server = new Server();
HttpConfiguration httpConfigOff = new HttpConfiguration();
httpConfigOff.setSendDateHeader(false);
httpConfigOff.setSendServerVersion(false);
httpConfigOff.setSendXPoweredBy(false);
ServerConnector connectorOff = new ServerConnector(server, new HttpConnectionFactory(httpConfigOff));
connectorOff.setPort(9090);
server.addConnector(connectorOff);
HttpConfiguration httpConfigDefault = new HttpConfiguration();
ServerConnector connectorDefault = new ServerConnector(server, new HttpConnectionFactory(httpConfigDefault));
connectorDefault.setPort(9191);
server.addConnector(connectorDefault);
server.setHandler(new AbstractHandler()
{
#Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.getWriter().println("Greetings.");
baseRequest.setHandled(true);
}
});
HttpClient client = new HttpClient();
try
{
client.start();
server.start();
// Let's show what the default Response headers look like.
dumpResponse("Default Response", client.GET(URI.create("http://localhost:9191/")));
// Let's show what the default Response headers look like.
dumpResponse("Configured Response", client.GET(URI.create("http://localhost:9090/")));
}
finally
{
LifeCycle.stop(server);
LifeCycle.stop(client);
}
}
private static void dumpResponse(String heading, ContentResponse response)
{
System.out.printf("--- %s ---%n", heading);
System.out.printf("Request to %s%n", response.getRequest().getURI());
System.out.printf("Response: %s %d %s%n", response.getVersion(), response.getStatus(), response.getReason());
System.out.println(response.getHeaders());
System.out.println(response.getContentAsString());
}
}
This sets up 2 ServerConnector objects ...
On port 9191 is the default HttpConfiguration
On port 9090 is the configured (some common response headers turned off) HttpConfiguration
If we make a simple request to both ports we can see the results ...
--- Default Response ---
Request to http://localhost:9191/
Response: HTTP/1.1 200 OK
Date: Thu, 28 Oct 2021 13:22:41 GMT
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Server: Jetty(9.4.44.v20210927)
Greetings.
--- Configured Response ---
Request to http://localhost:9090/
Response: HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Greetings.

Related

http client failing to call service with jearsey multipart as an argument

Trying to hit Jersey multipart service with httpclient, and seeing some issues. Could you please share your insights to resolve this issue. Below I posted client code, service, stack trace.
Thanks for your support.
It works good when I use below client and register classes. Not finding any facility to register these classes for http client.
javax.ws.rs.client.Client
client.register(JacksonJsonProvider.class);
client.register(MultiPartFeature.class);
CLIENT CODE:
final String CONTENT_TYPE_MULTIPART = "multipart/related";
final String CONTENT_TYPE = "application/octet-stream";
final String BOUNDARY = "--upload_boundary--";
String responseStr = "";
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addBinaryBody("file_upload", inputStream, ContentType.create(CONTENT_TYPE), "filename");
HttpPost httpPost = new HttpPost(finalURL);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_MULTIPART);//+";type="+CONTENT_TYPE+";boundary="+BOUNDARY);
httpPost.setEntity(multipartEntityBuilder.build());
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
responseStr = entity.toString();
RestHelper.verifyResponse(response, responseStr);
} catch (ClientProtocolException e) {
LOGGER.error("ClientProtocolException during upload",e);
} catch (IOException e) {
LOGGER.error("IOException during upload",e);
} finally {
response.close();
httpclient.close();
}
REST SERVICE:
#Consumes(MULTIPART_RELATED)
public String addDocument(MultiPart multipart)
STACKTRACE:
httpResponse :::::::::::::::::::: HttpResponseProxy{HTTP/1.1 400 Bad Request [Content-Type: text/html;charset=ISO-8859-1, $WSEP: , Content-Language: en-US, Transfer-Encoding: chunked, X-Cnection: Close, Date: Mon, 10 May 2021 11:50:32 GMT, Set-Cookie: dev-issapps.us=2036276652.6195.0000; path=/; Httponly] ResponseEntityProxy{[Content-Type: text/html;charset=ISO-8859-1,Chunked: true]}}
17:20:32.220 [main] ERROR us.dc.httpproxy.RestHelper - Response Error: RestException{us.dc.httpproxy.RestException
: HTTP/1.1 400 Bad Request', statusCode=400, detail='ResponseEntityProxy{[Content-Type: text/html;charset=ISO-8859-1,Chunked: true]}'}
17:20:32.221 [main] ERROR us.dc.httpproxy.RestClient - Exception in executeMultiPartRequest http://XXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXX/api/applications/GWEW/documents
RestException{ us.dc.httpproxy.RestException: HTTP/1.1 400 Bad Request', statusCode=400, detail='ResponseEntityProxy{[Content-Type: text/html;charset=ISO-8859-1,Chunked: true]}'}
Here is the solution, hope it helps somebody:
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.13'
compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.3'
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
File file = new File("src/main/resources/48-1.jpg");
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entitybuilder.addBinaryBody("image", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName());
entitybuilder.setContentType(ContentType.create("multipart/related"));
HttpEntity mutiPartHttpEntity = entitybuilder.build();
RequestBuilder reqbuilder = RequestBuilder.post(url);
reqbuilder.setEntity(mutiPartHttpEntity);
HttpUriRequest multipartRequest = reqbuilder.build();
HttpResponse httpresponse = httpclient.execute(multipartRequest);
System.out.println("response status = " + httpresponse.getStatusLine().getStatusCode());
System.out.println("filenet id = " + EntityUtils.toString(httpresponse.getEntity()));
}catch(Exception e) {
e.printStackTrace();
}

parsing email with mime4j

I encountered a problem when parsing email with mime4j.
The email has an attachment, and I use MimeStreamParser to parse it.
The parser does not call startMultipart method at all. Instead, it only calls body method once, and the BodyDescriptor is "text/plain".
I do not know the root of this problem, the email format or my program?
Here is my test program:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.james.mime4j.*;
import org.apache.james.mime4j.dom.BinaryBody;
import org.apache.james.mime4j.dom.Body;
import org.apache.james.mime4j.dom.Entity;
import org.apache.james.mime4j.dom.Header;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.dom.MessageBuilder;
import org.apache.james.mime4j.dom.Multipart;
import org.apache.james.mime4j.dom.TextBody;
import org.apache.james.mime4j.dom.address.Mailbox;
import org.apache.james.mime4j.dom.address.MailboxList;
import org.apache.james.mime4j.dom.field.AddressListField;
import org.apache.james.mime4j.dom.field.ContentTypeField;
import org.apache.james.mime4j.dom.field.DateTimeField;
import org.apache.james.mime4j.dom.field.UnstructuredField;
import org.apache.james.mime4j.field.address.AddressFormatter;
import org.apache.james.mime4j.message.BodyPart;
import org.apache.james.mime4j.message.MessageImpl;
import org.apache.james.mime4j.message.DefaultMessageBuilder;
import org.apache.james.mime4j.message.SimpleContentHandler;
import org.apache.james.mime4j.parser.ContentHandler;
import org.apache.james.mime4j.parser.MimeStreamParser;
import org.apache.james.mime4j.stream.BodyDescriptor;
import org.apache.james.mime4j.stream.Field;
import org.apache.james.mime4j.stream.MimeConfig;
public class TestClass extends SimpleContentHandler{
public static void main(String[] args) throws MimeException, IOException {
ContentHandler handler = new TestClass();
MimeConfig config = new MimeConfig();
MimeStreamParser parser = new MimeStreamParser(config);
parser.setContentHandler(handler);
InputStream instream = new FileInputStream("mail/testuser1");
try {
parser.parse(instream);
} finally {
instream.close();
}
}
#Override
public void headers(Header arg0) {
// TODO Auto-generated method stub
System.out.println("headers args: "+arg0);
}
#Override
public void body(BodyDescriptor bd, InputStream is) {
// TODO Auto-generated method stub
System.out.println("body descriptor: "+bd);
}
public void startMessage(){
System.out.println("startMessage");
}
public void endMessage(){
System.out.println("endMessage");
}
public void startBodyPart(){
System.out.println("startBodyPart");
}
public void endBodyPart() {
System.out.println("endBodyPart");
}
public void preamble(InputStream is){
System.out.println("preamble");
}
public void epilogue(InputStream is) {
System.out.println("epilogue");
}
public void startMultipart(BodyDescriptor bd){
System.out.println("startMultipart");
}
public void endMultipart() {
System.out.println("endMultipart");
}
public void raw(InputStream is) {
System.out.println("raw");
}
}
Here is a part of my email file:
From MAILER_DAEMON Wed Aug 21 19:24:53 2013
Date: Wed, 21 Aug 2013 19:24:53 +0800
From: Mail System Internal Data <MAILER-DAEMON#mail.abc.com>
Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
Message-ID: <1377084293#mail.abc.com>
X-IMAP: 1377072167 0000000003
Status: RO
This text is part of the internal format of your mail folder, and is not
a real message. It is created automatically by the mail system software.
If deleted, important folder data will be lost, and it will be re-created
with the data reset to initial values.
From testuser2#abc.com Sat Aug 24 10:53:42 2013
Return-Path: <testuser2#abc.com>
X-Original-To: testuser1#abc.com
Delivered-To: testuser1#abc.com
Received: from shupc (unknown [192.168.75.130])
by mail.abc.com (Postfix) with SMTP id C0F5B1EFBC3
for <testuser1#abc.com>; Sat, 24 Aug 2013 10:53:42 +0800 (CST)
Message-ID: <7F1C30C9CB284CA594D01CBE210257D3#shupc>
From: "john" <testuser2#abc.com>
To: "smith" <testuser1#abc.com>
Subject: aaa
Date: Sat, 24 Aug 2013 10:53:42 +0800
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
X-Priority: 3
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 6.00.2900.5512
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5512
X-UID: 3
Status: O
Content-Length: 386430
This is a multi-part message in MIME format.
------=_NextPart_000_000B_01CEA0B8.32903020
Content-Type: multipart/alternative;
boundary="----=_NextPart_001_000C_01CEA0B8.32903020"
------=_NextPart_001_000C_01CEA0B8.32903020
Content-Type: text/plain;
charset="gb2312"
Content-Transfer-Encoding: base64
dGVzdCBhYSBiYiBjYw==
------=_NextPart_001_000C_01CEA0B8.32903020
Content-Type: text/html;
charset="gb2312"
Content-Transfer-Encoding: base64
PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv
L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu
dD0idGV4dC9odG1sOyBjaGFyc2V0PWdiMjMxMiI+DQo8TUVUQSBjb250ZW50PSJNU0hUTUwgNi4w
MC4yOTAwLjU1MTIiIG5hbWU9R0VORVJBVE9SPg0KPFNUWUxFPjwvU1RZTEU+DQo8L0hFQUQ+DQo8
Qk9EWSBiZ0NvbG9yPSNmZmZmZmY+DQo8RElWPjxGT05UIHNpemU9Mj50ZXN0IGFhIGJiIGNjPC9G
T05UPjwvRElWPjwvQk9EWT48L0hUTUw+DQo=
------=_NextPart_001_000C_01CEA0B8.32903020--
------=_NextPart_000_000B_01CEA0B8.32903020
Content-Type: application/octet-stream;
name="10112716229607.doc"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="10112716229607.doc"
0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAAFAAAAKAIAAAAAAAAA
EAAAKgIAAAEAAAD+////AAAAACMCAAAkAgAAJQIAACYCAAAnAgAA////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////s
pcEAcWAJBAAA8FK/AAAAAAAAEAAAAAAABgAArJ0CAA4AYmpianFQcVAAAAAAAAAAAAAAAAAAAAAA
AAAECBYAOBIDABM6AQATOgEA1gwBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA
AAAAAAD//w8AAAAAAAAAAAD//w
The problem is with the sample email which not multipart. It contains, as inline text, a multipart email.
Remove the first headers ("FROM MAILER") and then make sure all lines following after Content-Type are indented (eg charset and boundary) by at least one whitespace character as required by the spec (RFC822 or later) or remove the linefeed. See example:
Change from :
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
to either:
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
or:
Content-Type: multipart/mixed; boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
Alternatively, try a different message.
Use the following library based on mime4j:
email-mime-parser
The provided sample code takes care of email parsing and the resulting 'email' object provides convenience method for the solution of your problem :
ContentHandler contentHandler = new CustomContentHandler();
MimeConfig mime4jParserConfig = new MimeConfig();
BodyDescriptorBuilder bodyDescriptorBuilder = new DefaultBodyDescriptorBuilder();
MimeStreamParser mime4jParser = new MimeStreamParser(mime4jParserConfig,DecodeMonitor.SILENT,bodyDescriptorBuilder);
mime4jParser.setContentDecoding(true);
mime4jParser.setContentHandler(contentHandler);
InputStream mailIn = 'Provide email mime stream here';
mime4jParser.parse(mailIn);
Email email = ((CustomContentHandler) contentHandler).getEmail();

Issue in sending a SOAP request in ApacheHttpClient with SSL

I want to send a SOAP request through SSL to SOAP server (Microsoft IIS server). When I test the SOAP request through the soapUI tool with SSL - Keystore configurations it returns response correctly. But Using following code it returns "HTTP/1.1 400 Bad Request"
I used httpclient-4.2.3 and httpcore-4.2.2.
import java.security.KeyStore;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream instream1 = new FileInputStream(new File("C:\\CCDKeyStore\\mykeystore.jks"));
try {
keyStore.load(instream1, "1214524".toCharArray());
} finally {
try { instream1.close(); } catch (Exception ignore) {}
}
SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,"1214524");
Scheme sch = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
schemeRegistry.register(sch);
final HttpParams httpParams = new BasicHttpParams();
DefaultHttpClient lHttpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams);
String lUrl = "https://api.demo.server.com/XDS/Service.svc?wsdl";
StringBuffer lXmlBuffer = new StringBuffer();
lXmlBuffer.append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">\n");
lXmlBuffer.append("<s:Header>\n");
lXmlBuffer.append("<a:Action s:mustUnderstand=\"1\">urn:74347:4757:StoredQuery</a:Action>\n");
lXmlBuffer.append("<a:MessageID>urn:uuid:c6430690-412e-4744-afe1-233e2138f2d2</a:MessageID>\n");
.
.
.
.
.
.
lXmlBuffer.append("</Slot>\n");
lXmlBuffer.append("</AdhocQuery>\n");
lXmlBuffer.append("</query:AdhocQueryRequest>\n");
lXmlBuffer.append("</s:Body>\n");
lXmlBuffer.append("</s:Envelope>\n");
String lXml = lXmlBuffer.toString();
HttpPost lMethod = new HttpPost(lUrl);
HttpEntity lEntity = new StringEntity(lXml, "multipart/related", "utf-8");
lMethod.setHeader("SOAPAction", "urn:74347:4757:StoredQuery");
System.out.println(EntityUtils.toString(lEntity));
lMethod.setEntity(lEntity);
HttpResponse lHttpResponse = lHttpClient.execute(lMethod);
} finally {
httpclient.getConnectionManager().shutdown();
}
Any help on this highly appreciate
Thanks,
Mohan
Finally I found the answer...
Here the following line in above code contains content type as "multipart/related". But web service is expected the content type "application/soap+xml" since this is SOAP request. Please refer w3schools tutorial for further information
HttpEntity lEntity = new StringEntity(lXml, "multipart/related", "utf-8");

Why is Jetty serving css with text/html content type

I'm using an embedded Jetty server in a Scalatra app. The issue is that it serves css files with text/html content type:
Here is the main method:
package yard.web
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener
object JettyMain {
def main(args: Array[String]) {
val server = new Server(9080)
val context: WebAppContext = new WebAppContext("src/main/webapp", "/")
context.setServer(server)
context.setInitParameter(ScalatraListener.LifeCycleKey, "yard.web.ScalatraBootstrap")
context.addEventListener(new ScalatraListener())
server.setHandler(context)
server.start()
println("Press ENTER to stop server")
Console.readLine()
server.stop()
server.join()
}
}
The file is located at src/main/webapp/libs/bootstrap/css/bootstrap.css, and served with:
$ curl --head http://localhost:9080/libs/bootstrap/css/bootstrap.css
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Last-Modified: Sat, 06 Apr 2013 14:30:35 GMT
Content-Length: 127247
Accept-Ranges: bytes
Server: Jetty(8.1.10.v20130312)
Why is Jetty thinking it's an html file?
Here is the ScalatraBootstrap class for completeness:
package yard.web
import org.scalatra.LifeCycle
import javax.servlet.ServletContext
import yard.Settings
import yard.db.Store
class ScalatraBootstrap extends LifeCycle {
override def init(context: ServletContext) {
val settings = Settings.default
val db = Store(settings).db
context mount (new MainServlet, "/")
}
}
Update: Using a ResourceHandler causes the css to be served with correct content type. However, the app doesn't work :(
The CSS file is typically served from the org.eclipse.jetty.servlet.DefaultServlet.
Which is declared in the etc/webdefault.xml file in the distribution.
Since you are using embedded mode, you'll want to provide this manually by calling WebAppContext.setDefaultsDescriptor(String) with the path to your etc/webdefault.xml file.
And finally, the mime types themselves are loaded by the DefaultServlet via the mime.properties file, which is loaded by Jetty via a call to Classloader.getResource("/org/eclipse/jetty/http/mime.properties").
Note: the mime.properties file is found in the jetty-http-8.1.10.v20130312.jar file.

Neo4j cannot accept big http rest requests

I'm trying to send one very big http post request to stand alone neo4j server (neo4j-community-1.9.M01).
Bellow is the sample code that I'm using.
The input file: ideas/src/test/test-rest.txt contains one very big json string (more than (250k).
The problem is that I cannot control a lot of settings of the web server launched by the standalone version of neo4j. Probably there is some limit on the web server that prevent me to send big post requests. Could someone help me to find out this setting.
Alternative : could some one tell me how to replace the default webserver used by neo4j for example with tomcat.
The error that I receive on the client is:
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
at org.apache.commons.httpclient.WireLogOutputStream.write(WireLogOutputStream.java:86)
at com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor$3.writeRequest(DefaultApacheHttpMethodExecutor.java:186)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.executeMethod(DefaultApacheHttpMethodExecutor.java:210)
Here are some logs from the web client:
11-11#08:28:01 INFO (HttpMethodDirector.java:445) - Retrying request
11-11#08:28:01 DEBUG (HttpConnection.java:692) - Open connection to localhost:7474
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "POST /db/data/batch HTTP/1.1[\r][\n]"
11-11#08:28:01 DEBUG (HttpMethodBase.java:1352) - Adding Host request header
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "Accept: application/json; stream=true[\r][\n]"
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "X-Stream: true[\r][\n]"
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "Content-Type: application/json[\r][\n]"
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "User-Agent: Jakarta Commons-HttpClient/3.1[\r][\n]"
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "Content-Length: 246292[\r][\n]"
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "Host: localhost:7474[\r][\n]"
11-11#08:28:01 DEBUG ( Wire.java:70) - >> "[\r][\n]"
11-11#08:31:22 DEBUG (HttpMethodDirector.java:404) - Closing the connection.
11-11#08:31:22 DEBUG (HttpMethodDirector.java:434) - Method retry handler returned false. Automatic recovery will not be attempted
11-11#08:31:22 DEBUG (HttpConnection.java:1178) - Releasing connection back to connection manager.
Here is the client code:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.client.apache.ApacheHttpClient;
import org.apache.commons.io.FileUtils;
import org.neo4j.rest.graphdb.RequestResult;
import org.neo4j.rest.graphdb.UserAgent;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
public class Main {
private static final UserAgent userAgent = new UserAgent();
public static final MediaType STREAMING_JSON_TYPE = new MediaType(APPLICATION_JSON_TYPE.getType(),APPLICATION_JSON_TYPE.getSubtype(), stringMap("stream","true"));
public static void main(String[] args) throws URISyntaxException, IOException {
String data = FileUtils.readFileToString(new File("ideas/src/test/test-rest.txt"));
Client client = createClient();
WebResource resource = client.resource(new URI("http://localhost:7474/db/data/batch"));
WebResource.Builder builder = resource.accept(STREAMING_JSON_TYPE).header("X-Stream", "true");
builder.entity( toInputStream(data), APPLICATION_JSON_TYPE );
System.out.println(RequestResult.extractFrom(builder.post(ClientResponse.class)));
}
private static InputStream toInputStream(String data) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(4024 * 1024);
outputStream.write(data.getBytes());
byte[] buf = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(buf);
return inputStream;
}
protected static Client createClient1() {
Client client = Client.create();
client.setConnectTimeout(800);
client.setReadTimeout(800);
client.setChunkedEncodingSize(80 * 1024);
userAgent.install(client);
return client;
}
protected static Client createClient() {
Client client = ApacheHttpClient.create();
return client;
}
private static Map<String, String> stringMap(String stream, String aTrue) {
HashMap<String, String> result = new HashMap<String, String>();
result.put(stream, aTrue);
return result;
}
}
Thanks in advance.
I found the reason of the problem.
I was running under Virtual BOX 4.2.0 with Windows XP guest machine and windows 7 host machine machine.
After putting the server on another machine, the problem disappeared.
I investigated with wireshark, before the failure I saw a lot of tcp packages that were not acknowledged and therefore retransmitted.
My question is still opened:how to replace the default webserver used by neo4j for example with tomcat?