littleproxy empty reply from server - java

I am using littleproxy-mitm to proxy requests in java to remote servers, yet I am getting an empty response from curl when trying to make a request through the proxy, regardless if it is http or https:
curl: (52) Empty reply from server
curl: (56) Proxy CONNECT aborted
My code:
HttpProxyServer server =
DefaultHttpProxyServer.bootstrap()
.withPort(PORT)
.withManInTheMiddle(new CertificateSniffingMitmManager())
.withFiltersSource(new HttpFiltersSourceAdapter() {
public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext context) {
System.out.println("-----------------------------------------------------");
HttpMethod method = originalRequest.getMethod();
String originalUri = originalRequest.getUri();
System.out.println("CLIENT " + method + " -> " + originalUri);
originalRequest.headers().forEach(entry -> {
System.out.println("-- " + entry.getKey() + ":" + entry.getValue());
});
if (HttpMethod.CONNECT.equals(method) && Objects.nonNull(context) && originalUri.endsWith(":443")) {
String url = "https://" + originalUri.replaceFirst(":443$", "");
context.channel().attr(CONNECTED_URL).set(url);
System.out.println("URL: " + context.channel().attr(CONNECTED_URL).get());
System.out.println("(Manipulating connection request for successful HTTPS: " + originalUri + " -> " + url + ")");
return new HttpFiltersAdapter(originalRequest, context);
}
return new HttpFiltersAdapter(originalRequest) {
#Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
if (httpObject instanceof LastHttpContent) {
LastHttpContent copy = ((LastHttpContent) httpObject).copy();
String body = copy.content().toString(StandardCharsets.UTF_8);
System.out.println("-- Content:" + body);
}
return null;
}
#Override
public HttpObject serverToProxyResponse(HttpObject httpObject) {
System.out.println("Server Response");
if (httpObject instanceof HttpResponse) {
HttpResponse response = (HttpResponse) httpObject;
System.out.println("SERVER RESPONSE");
response.headers().forEach(entry -> {
System.out.println("-- " + entry.getKey() + ":" + entry.getValue());
});
}
return httpObject;
}
};
}
})
.start();

Related

What's wrong inside try block as I'm getting response as Null

public static Response getRequest(String urlParameters, Map headers) {
RequestSpecification spec =setCertification();
Response response = null;
try {
LOGGER.info("URL : ()", EnvironmentPath
.GET LIMITS TRANSACTION_PATH_URI + urlParameters);
response = RestAssured.given().spec(spec).when().contentType(ContentType
.JSON).headers(headers).get(EnvironmentPath
.GET_LIMITS TRANSACTION_PATH URI + urlParameters)
.then().extract().response();
}
catch (Exception e) {
LOGGER.error("GET_REQUEST_NOT_PROCESSED- there was an exception raised "
+ "while processing the request");
throw new DPMSException("GET_REQUEST_NOT_PROCESSED - there was an exception "
+ "raised while processing the request,e);
}
return response;

HttpServletRequestWrapper not working in Spring MVC

I am developing a custom log with Spring MVC to get information from all incoming request. I would like to grab both the request body and response body. The issue is, even if I create a HttpServletRequestWrapper, I cannot forward the request after I process and wrap the request.
Here is my code:
Interceptor
#Component
public class LoggerInterceptor implements HandlerInterceptor{
final static org.apache.log4j.Logger log = Logger.getLogger(LoggerInterceptor.class.getName());
/**
* Executed before actual handler is executed
**/
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long start = System.currentTimeMillis();
MyRequestWrapper requestWrapper = new MyRequestWrapper(request);
SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
String date = f.format(new Date());
UUID uuid = UUID.randomUUID();
String method = requestWrapper.getMethod();
String uri = requestWrapper.getRequestURI();
String step = "Default Step";
String url = String.valueOf(requestWrapper.getRequestURL());
String serverName = requestWrapper.getServerName();
String reqBody = IOUtils.toString(requestWrapper.getInputStream(), Charset.forName("UTF-8").toString());
CustomHttpResponseWrapper responseWrapper = new CustomHttpResponseWrapper(response);
long end = System.currentTimeMillis() - start;
String status = String.valueOf(responseWrapper.getStatus());
String resBody = new String(responseWrapper.getBaos().toByteArray());
if(step!=null && !step.isEmpty()) {
log.info("INFO " + date + " " + uuid + "\n" +
"ID : " + getCurrentlyDateTime() + "\n" +
"STEP : " + step + "\n" +
"Request URL: " + url + "\n" +
"Host : " + serverName + "\n" +
"Request Body : " + reqBody + "\n" +
"Response Status : " + status + "\n" +
"Response Body : " + resBody + "\n" +
"Response Time : " + end);
}
return true;
}
}
Request Wrapper
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
#Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
// TODO Auto-generated method stub
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
Output
INFO 2022/04/12 10:35:18:578 d00ec778-2a6e-4a72-a0e0-9649c13776eb
ID : 20220412103518
STEP : Default Step
Request URL: http://localhost:8080/com.ihcs.api.mobile/loginNew
Host : localhost
Request Body : {
"username":"P0****",
"sessionid":"*************************",
"password":"********",
"companyCode":"***",
"UniqueId":"**********",
"Manufacturer":"google",
"Brand":"google",
"Model":"*******",
"DeviceId":"*******",
"FcmTokens":"*******",
"UniqueLogin":false
}
Response Status : 200
Response Body :
Response Time : 18
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
I've tried some suggestions from stack overflow but still can't help. Thank you.

Trying to access hosted SharePoint 2013 from Java app gives me 401 although I use correct OAuth token

I'm trying to access our company SharePoint 2013 instance, which is hosted at ourinstance.sharepoint.com, with small Java web application.
I registered application through _layouts/15/AppRegNew.aspx this way:
I let SP generate Client ID, Client Secret,
to App Domain I set: ourdomain:8443
to Redirect URL I set: https://ourdomain:8443/our-redirect-processing
I edited application permissions with _layouts/15/appinv.aspx, where I looked it up by client ID and edited its Permission Request XML to contain:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://insideidc.sharepoint.com/oursite/web" Right="FullControl"/>
</AppPermissionRequests>
Handler behind https://ourdomain:8443/our-redirect-processing is doing this:
JsonWebSignature jws = JsonWebSignature.parse(new JacksonFactory(), request.getParameter("SPAppToken"));
JsonParser jsonParser = new JacksonFactory().createJsonParser(jws.getPayload().get("appctx").toString());
AppCtx appCtx = jsonParser.parse(AppCtx.class, new CustomizeJsonParser());
String appctxsender=jws.getPayload().get("appctxsender").toString();
String[] splitApptxSender = appctxsender.split("#");
String sharepointServerHostName = new URL(request.getParameter("SPSiteUrl")).getHost();
String resource = splitApptxSender[0] + "/" + sharepointServerHostName + "#" + splitApptxSender[1];
AuthorizationCodeTokenRequest tokenRequest = new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
new GenericUrl(appCtx.getSecurityTokenServiceUri()), jws.getPayload().get("refreshtoken").toString());
tokenRequest.setRedirectUri(request.getRequestURL().toString());
String aud = (String) jws.getPayload().getAudience();
tokenRequest.setClientAuthentication(new ClientParametersAuthentication(aud, secrets.get(aud)));
tokenRequest.setGrantType("refresh_token");
tokenRequest.set("resource", resource);
tokenRequest.set("refresh_token", jws.getPayload().get("refreshtoken").toString());
TokenResponse response = tokenRequest.execute();
token = response.getAccessToken();
It uses com.google.api.client. auth, http and json classes.
The token I get I use in REST call to this URL:
https://ourinstance.sharepoint.com/oursite/_api/web/getFolderByServerRelativeUrl('/thefolderIwant')/Files
with these Headers:
Accept: application/json;odata=verbose
Authorization: Bearer theToken
The response asks me for logging in, while response header has WWW-Authenticate: NTLM set.
First question: should such complex process of obtaining OAuth token end up with another credentials request?
Second and main question: how can I construct domain\username for NTLM Authenticator, which I can build, when SharePoint is hosted for us?
I had a similar experience when trying to access Microsoft's Project Online.
I found some helpful information from AllThatJS which pointed me in the right direction. He suggested sniffing the packets using Fiddler. Once I did that, I saw what was actually going on.
Here is some Java code I used to solve this problem, using Apache's HttpClient, Apache's common-io, and log4j to solve this :
/**
This is for using Java to connect with Microsoft's Project Online
If you go into your Project Online, go to 'Server Settings' -> 'Manage Users', and look under the column 'User Logon Account'
If it looks like :
i:0#.w|domain\\username
then you can just scroll down to where I call
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
new NTCredentials(
USERNAME,
PASSWORD,
url.getHost(),
DOMAIN));
However, if it looks more like :
i:0#.f|membership|username#yourcompany.com
then you'll need to use OAuth, which is what this file demonstrates.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.IOUtils;// from commons-io-2.4.jar
import org.apache.http.Header;// from httpcore-4.2.4.jar
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;// from log4j.jar
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class ProjectOnline {
private static final Logger logger = Logger.getLogger(ProjectOnline.class);
private static final String USERNAME = "your user's email address";
private static final String PASSWORD = "password";
private static final String DOMAIN = "YOURDOMAIN";
private static final String PROJECT_SERVER = "https://your.project.online.sharepoint.com";
private static final String EMAIL_DOMAIN = "#your.company.com";
public static void main(String[] args) {
ProjectOnline dao = new ProjectOnline();
System.out.println(dao.getOAuthCookie());
}
private boolean needToUseOAuth(String username) {
if (username == null) return false;
return username.toLowerCase().endsWith(EMAIL_DOMAIN.toLowerCase());
}
public String getOAuthCookie() {
if (needToUseOAuth(USERNAME)) {
String samlSecurityToken = postLoginCredentialsToOurOAuthService();
if (samlSecurityToken != null && samlSecurityToken.isEmpty() == false) {
String binarySecurityToken = postSamlSecurityTokenToSecondSite(samlSecurityToken);
if (binarySecurityToken != null && binarySecurityToken.isEmpty() == false) {
String spoidcrlCookie = getSpoidcrlCookie(binarySecurityToken);
return spoidcrlCookie;
} else {
//System.out.println("getXMLDocument - OAuth authentication / authorization failed : Binary Security Token was not found");
logger.error("getOAuthCookie - OAuth authentication / authorization failed : Binary Security Token was not found");
}
} else {
//System.out.println("getXMLDocument - OAuth authentication / authorization failed : SAML Security Token was not found");
logger.error("getOAuthCookie - OAuth authentication / authorization failed : SAML Security Token was not found");
}
}
return "";
}
// Step 1 - Find the URL to your company's OAuth site
private String getOurOAuthServerURL(String emailAddress) {
DefaultHttpClient httpclient = new DefaultHttpClient();
// Go to this site, passing in email address. Should tell the URL for your company's OAuth site
HttpPost httppost = new HttpPost("https://login.microsoftonline.com/GetUserRealm.srf?xml=1&login=" + emailAddress);
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String status = response.getStatusLine().toString();
//System.out.println("getOurOAuthServerURL - status = " + status);
logger.info("getOurOAuthServerURL - status = " + status);
// If response status doesn't equal 'OK' then it didn't work.
if (entity != null && "HTTP/1.1 200 OK".equals(status)) {
StringWriter writer = new StringWriter();
IOUtils.copy(entity.getContent(), writer, "utf-8");
String xml = writer.toString();
//System.out.println(xml);
//logger.debug(xml);
String ourAuthURL = getSTSAuthURL(xml);
//System.out.println("ourAuthURL = " + ourAuthURL);
return ourAuthURL;
}
} catch (UnsupportedEncodingException e) {
logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (ClientProtocolException e) {
logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IllegalStateException e) {
logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IOException e) {
logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
return "";
}
private String getBinarySecurityToken(String xml) {
return getValuesBetweenTags(xml, "<wsse:BinarySecurityToken Id=\"Compact0\">", "</wsse:BinarySecurityToken>");
}
private String getSTSAuthURL(String xml) {
return getValuesBetweenTags(xml, "<STSAuthURL>", "</STSAuthURL>");
}
private String getSamlSecurityToken(String xml) {
return getValuesBetweenTags(xml, "<t:RequestedSecurityToken>", "</t:RequestedSecurityToken>");
}
private String getValuesBetweenTags(String xml, String tagToLeft, String tagToRight) {
if (xml == null || xml.isEmpty()) return "";
int startToken = xml.indexOf(tagToLeft);
if (startToken > -1) {
return xml.substring(startToken + tagToLeft.length(), xml.indexOf(tagToRight, startToken));
} else {
return "";
}
}
private String getTimeString(int minutesInFuture) {
Calendar rightNow = Calendar.getInstance();
rightNow.add(Calendar.SECOND, (((rightNow.get(Calendar.ZONE_OFFSET) + (rightNow.get(Calendar.DST_OFFSET)))/-1000)));
rightNow.add(Calendar.MINUTE, minutesInFuture);
String timeString = String.format("%d-%02d-%02dT%02d:%02d:%02d.0000000Z",
rightNow.get(Calendar.YEAR),
(rightNow.get(Calendar.MONTH) + 1),
rightNow.get(Calendar.DATE),
rightNow.get(Calendar.HOUR_OF_DAY),
rightNow.get(Calendar.MINUTE),
rightNow.get(Calendar.SECOND));
return timeString;
}
// Step 2 - POST an XML message, with a few key fields filled in (rest can be left as-is)
// This should be sent to your company's OAuth site
private String postLoginCredentialsToOurOAuthService() {
String ourOAuthService = getOurOAuthServerURL(USERNAME);
DefaultHttpClient httpclient = new DefaultHttpClient();
StringBuilder xmlString = new StringBuilder();
xmlString.append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" ");
xmlString.append("xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" ");
xmlString.append("xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" ");
xmlString.append("xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" ");
xmlString.append("xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" ");
xmlString.append("xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" ");
xmlString.append("xmlns:wssc=\"http://schemas.xmlsoap.org/ws/2005/02/sc\" ");
xmlString.append("xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\"> ");
xmlString.append("<s:Header> ");
xmlString.append("<wsa:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action> ");
xmlString.append("<wsa:To s:mustUnderstand=\"1\">" + ourOAuthService + "</wsa:To> ");
xmlString.append("<wsa:MessageID>").append(UUID.randomUUID().toString()).append("</wsa:MessageID> ");
xmlString.append("<ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"PPAuthInfo\"> ");
xmlString.append("<ps:HostingApp>Managed IDCRL</ps:HostingApp> ");
xmlString.append("<ps:BinaryVersion>6</ps:BinaryVersion> ");
xmlString.append("<ps:UIVersion>1</ps:UIVersion> ");
xmlString.append("<ps:Cookies></ps:Cookies> ");
xmlString.append("<ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams> ");
xmlString.append("</ps:AuthInfo> ");
xmlString.append("<wsse:Security> ");
xmlString.append("<wsse:UsernameToken wsu:Id=\"user\"> ");
xmlString.append("<wsse:Username>").append(USERNAME).append("</wsse:Username> ");
xmlString.append("<wsse:Password>").append(PASSWORD).append("</wsse:Password> ");
xmlString.append("</wsse:UsernameToken> ");
xmlString.append("<wsu:Timestamp Id=\"Timestamp\"> ");
xmlString.append("<wsu:Created>" + getTimeString(0) + "</wsu:Created> ");
xmlString.append("<wsu:Expires>" + getTimeString(10) + "</wsu:Expires> ");
xmlString.append("</wsu:Timestamp> ");
xmlString.append("</wsse:Security> ");
xmlString.append("</s:Header> ");
xmlString.append("<s:Body> ");
xmlString.append("<wst:RequestSecurityToken Id=\"RST0\"> ");
xmlString.append("<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType> ");
xmlString.append("<wsp:AppliesTo> ");
xmlString.append("<wsa:EndpointReference> ");
xmlString.append("<wsa:Address>urn:federation:MicrosoftOnline</wsa:Address> ");
xmlString.append("</wsa:EndpointReference> ");
xmlString.append("</wsp:AppliesTo> ");
xmlString.append("<wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType> ");
xmlString.append("</wst:RequestSecurityToken> ");
xmlString.append("</s:Body> ");
xmlString.append("</s:Envelope> ");
HttpPost httppost = new HttpPost(ourOAuthService);
try {
httppost.addHeader("Content-Type", "application/soap+xml; charset=utf-8");
httppost.setEntity(new StringEntity(xmlString.toString()));// Set this in the body
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String status = response.getStatusLine().toString();
//System.out.println("postLoginCredentialsToOurOAuthService - status = " + status);
logger.info("postLoginCredentialsToOurOAuthService - status = " + status);
// If response status doesn't equal 'OK' then it didn't work.
if (entity != null && "HTTP/1.1 200 OK".equals(status)) {
StringWriter writer = new StringWriter();
IOUtils.copy(entity.getContent(), writer, "utf-8");
String xml = writer.toString();
//System.out.println(xml);
//logger.debug(xml);
// Now, extract out the SAML Security Token. It is several lines (~49, if you parse it out).
String samlSecurityToken = getSamlSecurityToken(xml);
//System.out.println("samlSecurityToken = " + samlSecurityToken);
return samlSecurityToken;
}
} catch (UnsupportedEncodingException e) {
logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (ClientProtocolException e) {
logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IllegalStateException e) {
logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IOException e) {
logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
return "";
}
// Step 3 - Now that you have the SAML Security Token, you embed it within some other generic XML, and send back to Microsoft server
private String postSamlSecurityTokenToSecondSite(String samlSecurityToken) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("https://login.microsoftonline.com/rst2.srf");
httppost.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
StringBuilder xmlString = new StringBuilder();
xmlString.append("<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\" ");
xmlString.append("xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" ");
xmlString.append("xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" ");
xmlString.append("xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" ");
xmlString.append("xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" ");
xmlString.append("xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">");
xmlString.append("<S:Header>");
xmlString.append("<wsa:Action S:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>");
xmlString.append("<wsa:To S:mustUnderstand=\"1\">https://login.microsoftonline.com/rst2.srf</wsa:To>");
xmlString.append("<ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/LiveID/SoapServices/v1\" Id=\"PPAuthInfo\">");
xmlString.append("<ps:BinaryVersion>5</ps:BinaryVersion>");
xmlString.append("<ps:HostingApp>Managed IDCRL</ps:HostingApp>");
xmlString.append("</ps:AuthInfo>");
xmlString.append("<wsse:Security>");
xmlString.append(samlSecurityToken);
xmlString.append("</wsse:Security>");
xmlString.append("</S:Header>");
xmlString.append("<S:Body>");
xmlString.append("<wst:RequestSecurityToken xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\" Id=\"RST0\">");
xmlString.append("<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>");
xmlString.append("<wsp:AppliesTo>");
xmlString.append("<wsa:EndpointReference>");
xmlString.append("<wsa:Address>sharepoint.com</wsa:Address>");
xmlString.append("</wsa:EndpointReference>");
xmlString.append("</wsp:AppliesTo>");
xmlString.append("<wsp:PolicyReference URI=\"MBI\"></wsp:PolicyReference>");
xmlString.append("</wst:RequestSecurityToken>");
xmlString.append("</S:Body>");
xmlString.append("</S:Envelope>");
httppost.addHeader("Content-Type", "application/soap+xml; charset=utf-8");
httppost.setEntity(new StringEntity(xmlString.toString()));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String status = response.getStatusLine().toString();
//System.out.println("postSamlSecurityTokenToSecondSite - status = " + status);
logger.info("postSamlSecurityTokenToSecondSite - status = " + status);
// If response status doesn't equal 'OK' then it didn't work.
if (entity != null && "HTTP/1.1 200 OK".equals(status)) {
StringWriter writer = new StringWriter();
IOUtils.copy(entity.getContent(), writer, "utf-8");
String xml = writer.toString();
//System.out.println(xml);
//logger.debug(xml);
// Extract out the value from just one, single line of this returned XML file
String binarySecurityToken = getBinarySecurityToken(xml);
//System.out.println("binarySecurityToken = " + binarySecurityToken);
return binarySecurityToken;
}
} catch (UnsupportedEncodingException e) {
logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (ClientProtocolException e) {
logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IllegalStateException e) {
logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IOException e) {
logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
return "";
}
// Step 4 - Using the extracted value, the Binary Security Token, build a header, and add it to the next request
// This will go to your own Project Online server, which should return back a reply message, containing a 'Set-Cookie' cookie with 'SPOIDCRL' in the value
private String getSpoidcrlCookie(String binarySecurityToken) {
try {
HttpGet httpget = new HttpGet(PROJECT_SERVER + "/_vti_bin/idcrl.svc/");
httpget.addHeader("Authorization", "BPOSIDCRL " + binarySecurityToken);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpget);
String status = response.getStatusLine().toString();
//System.out.println("getSpoidcrlCookie - status = " + status);
logger.info("getSpoidcrlCookie - status = " + status);
// If response status doesn't equal 'OK' then it didn't work.
if ("HTTP/1.1 200 OK".equals(status)) {
Header[] headers = response.getHeaders("Set-Cookie");
for (Header header : headers) {
if (header.getValue().contains("SPOIDCRL")) {
String spoidcrlCookie = header.getValue();
//System.out.println("Found SPOIDCRL cookie : " + spoidcrlCookie);
return spoidcrlCookie;
}
}
}
} catch (ClientProtocolException e) {
logger.error("getSpoidcrlCookie ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IOException e) {
logger.error("getSpoidcrlCookie ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (Exception e) {
logger.error("getSpoidcrlCookie ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
}
return null;
}
public Document getXMLDocument(String strURL) {
String spoidcrlCookie = getOAuthCookie();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(strURL);
try {
URL url = new URL(strURL);
if (needToUseOAuth(USERNAME)) {
httpget.addHeader("Cookie", spoidcrlCookie);
} else {
// Otherwise, can just use this simple way of logging in, using the Domain
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
new NTCredentials(
USERNAME,
PASSWORD,
url.getHost(),
DOMAIN));
}
//System.out.println("getXMLDocument - strURL " + strURL);
//logger.info("getXMLDocument - strURL " + strURL);
//logger.info("getXMLDocument - executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);//httppost
HttpEntity entity = response.getEntity();
//logger.info("getXMLDocument - ----------------------------------------");
//for (Header header : response.getAllHeaders()) {
// System.out.println("getXMLDocument - header = " + header.toString());
//}
String status = response.getStatusLine().toString();
//System.out.println("getXMLDocument - status = " + status);
//logger.info("getXMLDocument - status = " + status);
// If response status doesn't equal 'OK' then it didn't work.
if (entity != null && "HTTP/1.1 200 OK".equals(status)) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
StringWriter writer = new StringWriter();
IOUtils.copy(entity.getContent(), writer, "utf-8");
String xml = writer.toString();
//System.out.println(xml);
//logger.debug(xml);
if (xml.endsWith("</feed>") == false) {
//logger.warn("The XML did not end with </feed>");
xml = xml + "</feed>";
}
InputStream inputStream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
Document doc = docBuilder.parse(inputStream);
return doc;
} else {
logger.error("getXMLDocument - status = " + status);
}
} catch (ClientProtocolException e) {
logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IOException e) {
logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (ParserConfigurationException e) {
logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (IllegalStateException e) {
logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (SAXException e) {
logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} catch (Exception e) {
logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
logger.warn("Exiting from getXMLDocument but returning null");
return null;
}
}

Socket TimeOutException-Connection timed out

I am trying to connect with Tomcat Server(IP address-192.168.1.120 which is stored in Config.java(static variable APP_SERVER_URL)) but it is giving me socket timeout exception .
How to resolve it.Please help.
But when I
public class ShareExternalServer {
public String shareRegIdWithAppServer(Map<String, String> paramsMap) {
String result = "";
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry<String, String>> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
Log.d("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&",body);
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httpCon.setConnectTimeout(20000);
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
Log.d("$$$$$$$$$$$$$$$$$$",String.valueOf(status));
/* if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post Failure." + " Status: " + status+regId;
}*/
} finally {
if (httpCon != null) {
((HttpURLConnection) httpCon).disconnect();
}
}
} catch (IOException e) {
result = "Post Failure. Error in sharing with App Server.";
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}

Java application with httpServer hangs for 45 seconds before exiting

I have been playing around with Java httpServer class a little bit. When I run my test application it will get to the last line (a println) in main about right a way, but then it sits there for about 45 secs before closing the application. Why does it do that and is there a way to make it so it ends faster? Thanks
public class TestTester
{
public static void main(String[] args) throws IOException {
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8780);
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
URL url = new URL("http://localhost:8780/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStreamReader(connection.getInputStream()));
// print out the response headers
System.out.println("\nHttp Response Headers");
for (int i=0; ; i++)
{
String headerName = connection.getHeaderFieldKey(i);
String headerValue = connection.getHeaderField(i);
if (headerName == null && headerValue == null) {
// No more headers
break;
}
else if (headerName == null) {
System.out.println( " " + headerValue);
}
else
System.out.println( " " + headerName + ": " + headerValue );
}
connection.disconnect();
server.stop(0);
System.out.println("Stopped Server.");
} // end main()
}
class MyHandler implements HttpHandler {
#Override
public void handle(HttpExchange exchange) throws IOException
{
System.out.println("===Enter MyHandler===");
System.out.println("Http Request Header:");
// print out the request methode and url
System.out.println( " " + exchange.getRequestMethod() + " "
+ exchange.getRequestURI() + " " + exchange.getProtocol());
// print out the request headers
Headers requestHeaders = exchange.getRequestHeaders();
for (String name : requestHeaders.keySet() )
{
List<String> values = requestHeaders.get(name);
for ( String value : values )
{
System.out.println( " " + name + ": " + value);
}
}
// print out the request body if any
BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
String sCurrentLine;
System.out.println( "\nHttp Request Body:");
if ( ! in.ready() )
System.out.println( " No Request Body");
else
{
while ((sCurrentLine = in.readLine()) != null) {
System.out.println(" " + sCurrentLine);
}
}
// set up and send response
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET"))
{
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write("<!DOCTYPE html><html><body><h1>My Response Header</h1><p>And some sample data.</p></body></html>".getBytes());
responseBody.close();
}
exchange.close();
} // end public void handle()
} // end class
I did find something that seems to work although I am not sure if it is the correct way to be handling this. This is not extensively tested, but it does make it shutdown faster.
I replaced:
server.setExecutor(Executors.newCachedThreadPool());
With:
ExecutorService excu = Executors.newCachedThreadPool();
server.setExecutor(excu);
Then just before the server.stop(0); I added excu.shutdown();

Categories

Resources