Modify HttpServletRequest body - java

I'm working on legacy code and need to make a patch.
The problem: an ancient application sends bad HTTP POST requests. One of the parameters is not URL encoded. I know that this parameter always comes last and I know it's name. I'm now trying to fix it on the server side which is running inside tomcat.
This parameter is not accessible via standard getParameter method of HttpServletRequest, since it's malformed. Method simply returns null. But when I manually read the whole body of request through ServletInputStream all the other parameters disappear. Looks like underlying classes can't parse contents of ServletInputStream since it's drained out.
So far I've managed to make a wrapper that reads all parameters from body and overrides all parameter access methods. But if any filter in the chain before mine will try to access any parameter, everything will break since ServletInputStream will be empty.
Can I somehow evade this problem? May be there's different approach?
To summarize, If I'll read raw request body in the filter, parameters will disappear from the request. If I read single parameter, ServletInputStream will become empty and manual processing will be impossible. Moreover, it's impossible to read malformed parameter via getParameter method.

Solution I've found:
It's not enough to just redefine parameter accessing methods. Several things must be done.
A filter is needed where request will be wrapped.
A custom HttpRequestWrapper is needed with all parameter access methods overridden. Request body should be parsed in constructor and stored as a field.
getInputStream and getReader methods should be redefined as well. They return values depend on the stored request body.
Custom class extending ServletInputStream is required since this one is abstract.
This 4 combined will allow you to use getParameter without interference with getInputStream and getReader methods.
Mind that manual request parameter parsing may get complicated with multipart requests. But that's another topic.
To clarify, I redefined parameter accessing methods because my request was damaged as stated in the question. You may not need that.

Rather than overriding methods, why don't you install a servlet filter which rewrites the request?
Jason Hunter has a pretty good article on filters.

I did a more complete wrapper that allows you to still access the content in the case Content-Type is application/x-www-form-urlencoded and you already called one of the getParameterXXX methods:
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* This class implements the Wrapper or Decorator pattern.<br/>
* Methods default to calling through to the wrapped request object,
* except the ones that read the request's content (parameters, stream or reader).
* <p>
* This class provides a buffered content reading that allows the methods
* {#link #getReader()}, {#link #getInputStream()} and any of the getParameterXXX to be called
* safely and repeatedly with the same results.
* <p>
* This class is intended to wrap relatively small HttpServletRequest instances.
*
* #author pgurov
*/
public class HttpServletRequestWrapper implements HttpServletRequest {
private class ServletInputStreamWrapper extends ServletInputStream {
private byte[] data;
private int idx = 0;
ServletInputStreamWrapper(byte[] data) {
if(data == null)
data = new byte[0];
this.data = data;
}
#Override
public int read() throws IOException {
if(idx == data.length)
return -1;
return data[idx++];
}
}
private HttpServletRequest req;
private byte[] contentData;
private HashMap<String, String[]> parameters;
public HttpServletRequestWrapper() {
//a trick for Groovy
throw new IllegalArgumentException("Please use HttpServletRequestWrapper(HttpServletRequest request) constructor!");
}
private HttpServletRequestWrapper(HttpServletRequest request, byte[] contentData, HashMap<String, String[]> parameters) {
req = request;
this.contentData = contentData;
this.parameters = parameters;
}
public HttpServletRequestWrapper(HttpServletRequest request) {
if(request == null)
throw new IllegalArgumentException("The HttpServletRequest is null!");
req = request;
}
/**
* Returns the wrapped HttpServletRequest.
* Using the getParameterXXX(), getInputStream() or getReader() methods may interfere
* with this class operation.
*
* #return
* The wrapped HttpServletRequest.
*/
public HttpServletRequest getRequest() {
try {
parseRequest();
} catch (IOException e) {
throw new IllegalStateException("Cannot parse the request!", e);
}
return new HttpServletRequestWrapper(req, contentData, parameters);
}
/**
* This method is safe to use multiple times.
* Changing the returned array will not interfere with this class operation.
*
* #return
* The cloned content data.
*/
public byte[] getContentData() {
return contentData.clone();
}
/**
* This method is safe to use multiple times.
* Changing the returned map or the array of any of the map's values will not
* interfere with this class operation.
*
* #return
* The clonned parameters map.
*/
public HashMap<String, String[]> getParameters() {
HashMap<String, String[]> map = new HashMap<String, String[]>(parameters.size() * 2);
for(String key : parameters.keySet()) {
map.put(key, parameters.get(key).clone());
}
return map;
}
private void parseRequest() throws IOException {
if(contentData != null)
return; //already parsed
byte[] data = new byte[req.getContentLength()];
int len = 0, totalLen = 0;
InputStream is = req.getInputStream();
while(totalLen < data.length) {
totalLen += (len = is.read(data, totalLen, data.length - totalLen));
if(len < 1)
throw new IOException("Cannot read more than " + totalLen + (totalLen == 1 ? " byte!" : " bytes!"));
}
contentData = data;
String enc = req.getCharacterEncoding();
if(enc == null)
enc = "UTF-8";
String s = new String(data, enc), name, value;
StringTokenizer st = new StringTokenizer(s, "&");
int i;
HashMap<String, LinkedList<String>> mapA = new HashMap<String, LinkedList<String>>(data.length * 2);
LinkedList<String> list;
boolean decode = req.getContentType() != null && req.getContentType().equals("application/x-www-form-urlencoded");
while(st.hasMoreTokens()) {
s = st.nextToken();
i = s.indexOf("=");
if(i > 0 && s.length() > i + 1) {
name = s.substring(0, i);
value = s.substring(i+1);
if(decode) {
try {
name = URLDecoder.decode(name, "UTF-8");
} catch(Exception e) {}
try {
value = URLDecoder.decode(value, "UTF-8");
} catch(Exception e) {}
}
list = mapA.get(name);
if(list == null) {
list = new LinkedList<String>();
mapA.put(name, list);
}
list.add(value);
}
}
HashMap<String, String[]> map = new HashMap<String, String[]>(mapA.size() * 2);
for(String key : mapA.keySet()) {
list = mapA.get(key);
map.put(key, list.toArray(new String[list.size()]));
}
parameters = map;
}
/**
* This method is safe to call multiple times.
* Calling it will not interfere with getParameterXXX() or getReader().
* Every time a new ServletInputStream is returned that reads data from the begining.
*
* #return
* A new ServletInputStream.
*/
public ServletInputStream getInputStream() throws IOException {
parseRequest();
return new ServletInputStreamWrapper(contentData);
}
/**
* This method is safe to call multiple times.
* Calling it will not interfere with getParameterXXX() or getInputStream().
* Every time a new BufferedReader is returned that reads data from the begining.
*
* #return
* A new BufferedReader with the wrapped request's character encoding (or UTF-8 if null).
*/
public BufferedReader getReader() throws IOException {
parseRequest();
String enc = req.getCharacterEncoding();
if(enc == null)
enc = "UTF-8";
return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(contentData), enc));
}
/**
* This method is safe to execute multiple times.
*
* #see javax.servlet.ServletRequest#getParameter(java.lang.String)
*/
public String getParameter(String name) {
try {
parseRequest();
} catch (IOException e) {
throw new IllegalStateException("Cannot parse the request!", e);
}
String[] values = parameters.get(name);
if(values == null || values.length == 0)
return null;
return values[0];
}
/**
* This method is safe.
*
* #see {#link #getParameters()}
* #see javax.servlet.ServletRequest#getParameterMap()
*/
#SuppressWarnings("unchecked")
public Map getParameterMap() {
try {
parseRequest();
} catch (IOException e) {
throw new IllegalStateException("Cannot parse the request!", e);
}
return getParameters();
}
/**
* This method is safe to execute multiple times.
*
* #see javax.servlet.ServletRequest#getParameterNames()
*/
#SuppressWarnings("unchecked")
public Enumeration getParameterNames() {
try {
parseRequest();
} catch (IOException e) {
throw new IllegalStateException("Cannot parse the request!", e);
}
return new Enumeration<String>() {
private String[] arr = getParameters().keySet().toArray(new String[0]);
private int idx = 0;
public boolean hasMoreElements() {
return idx < arr.length;
}
public String nextElement() {
return arr[idx++];
}
};
}
/**
* This method is safe to execute multiple times.
* Changing the returned array will not interfere with this class operation.
*
* #see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
*/
public String[] getParameterValues(String name) {
try {
parseRequest();
} catch (IOException e) {
throw new IllegalStateException("Cannot parse the request!", e);
}
String[] arr = parameters.get(name);
if(arr == null)
return null;
return arr.clone();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getAuthType()
*/
public String getAuthType() {
return req.getAuthType();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getContextPath()
*/
public String getContextPath() {
return req.getContextPath();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getCookies()
*/
public Cookie[] getCookies() {
return req.getCookies();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
*/
public long getDateHeader(String name) {
return req.getDateHeader(name);
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
*/
public String getHeader(String name) {
return req.getHeader(name);
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getHeaderNames()
*/
#SuppressWarnings("unchecked")
public Enumeration getHeaderNames() {
return req.getHeaderNames();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
*/
#SuppressWarnings("unchecked")
public Enumeration getHeaders(String name) {
return req.getHeaders(name);
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
*/
public int getIntHeader(String name) {
return req.getIntHeader(name);
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getMethod()
*/
public String getMethod() {
return req.getMethod();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getPathInfo()
*/
public String getPathInfo() {
return req.getPathInfo();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getPathTranslated()
*/
public String getPathTranslated() {
return req.getPathTranslated();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getQueryString()
*/
public String getQueryString() {
return req.getQueryString();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getRemoteUser()
*/
public String getRemoteUser() {
return req.getRemoteUser();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getRequestURI()
*/
public String getRequestURI() {
return req.getRequestURI();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getRequestURL()
*/
public StringBuffer getRequestURL() {
return req.getRequestURL();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
*/
public String getRequestedSessionId() {
return req.getRequestedSessionId();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getServletPath()
*/
public String getServletPath() {
return req.getServletPath();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getSession()
*/
public HttpSession getSession() {
return req.getSession();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getSession(boolean)
*/
public HttpSession getSession(boolean create) {
return req.getSession(create);
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#getUserPrincipal()
*/
public Principal getUserPrincipal() {
return req.getUserPrincipal();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
*/
public boolean isRequestedSessionIdFromCookie() {
return req.isRequestedSessionIdFromCookie();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
*/
public boolean isRequestedSessionIdFromURL() {
return req.isRequestedSessionIdFromURL();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
*/
#SuppressWarnings("deprecation")
public boolean isRequestedSessionIdFromUrl() {
return req.isRequestedSessionIdFromUrl();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
*/
public boolean isRequestedSessionIdValid() {
return req.isRequestedSessionIdValid();
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
*/
public boolean isUserInRole(String role) {
return req.isUserInRole(role);
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getAttribute(java.lang.String)
*/
public Object getAttribute(String name) {
return req.getAttribute(name);
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getAttributeNames()
*/
#SuppressWarnings("unchecked")
public Enumeration getAttributeNames() {
return req.getAttributeNames();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getCharacterEncoding()
*/
public String getCharacterEncoding() {
return req.getCharacterEncoding();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getContentLength()
*/
public int getContentLength() {
return req.getContentLength();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getContentType()
*/
public String getContentType() {
return req.getContentType();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getLocalAddr()
*/
public String getLocalAddr() {
return req.getLocalAddr();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getLocalName()
*/
public String getLocalName() {
return req.getLocalName();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getLocalPort()
*/
public int getLocalPort() {
return req.getLocalPort();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getLocale()
*/
public Locale getLocale() {
return req.getLocale();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getLocales()
*/
#SuppressWarnings("unchecked")
public Enumeration getLocales() {
return req.getLocales();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getProtocol()
*/
public String getProtocol() {
return req.getProtocol();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getRealPath(java.lang.String)
*/
#SuppressWarnings("deprecation")
public String getRealPath(String path) {
return req.getRealPath(path);
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getRemoteAddr()
*/
public String getRemoteAddr() {
return req.getRemoteAddr();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getRemoteHost()
*/
public String getRemoteHost() {
return req.getRemoteHost();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getRemotePort()
*/
public int getRemotePort() {
return req.getRemotePort();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
*/
public RequestDispatcher getRequestDispatcher(String path) {
return req.getRequestDispatcher(path);
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getScheme()
*/
public String getScheme() {
return req.getScheme();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getServerName()
*/
public String getServerName() {
return req.getServerName();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#getServerPort()
*/
public int getServerPort() {
return req.getServerPort();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#isSecure()
*/
public boolean isSecure() {
return req.isSecure();
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
*/
public void removeAttribute(String name) {
req.removeAttribute(name);
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#setAttribute(java.lang.String, java.lang.Object)
*/
public void setAttribute(String name, Object value) {
req.setAttribute(name, value);
}
/* (non-Javadoc)
* #see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
*/
public void setCharacterEncoding(String env)
throws UnsupportedEncodingException {
req.setCharacterEncoding(env);
}
}

I wanted to post this as a comment, but I do not have enough rep. Your solution is insufficient in that ServletInputStreamWrapper will return negative integers. For instance, mock a request with input encoding UTF-16, either big or little endian. The input may start with the Byte Order Mark indicating endianess, and when testing my statement please construct the mock request content to do so. http://en.wikipedia.org/wiki/Byte_order_mark#UTF-16 Either of these BOMs contains a 0xFF byte. Since java has no unsigned byte, this 0xFF is returned as a -1. To work around this, just change the read function like so
public int read() throws IOException {
if (index == data.length) {
return -1;
}
return data[index++] & 0xff;
}
I somewhat like your solution because it works well with Spring. At first I tried to eliminate some of the delegation code you wrote by extending from HttpServletRequestWrapper. However, Spring does something interesting: when it encounters a request of type ServletRequestWrapper it unwraps it, calling getRequest(). Problem being that my getRequest() method, as copied from your code, returns a new class that extends from HttpServletRequestWrapper... rinse and repeat infinitely. So it's sad to say, chalk up a win for not using interfaces!

You could write your own Servlet Filter and hopefully ensure that it appears first in the chain. Then wrap the ServletRequest object in something that will handle the re-writing where needed. Have a look at the Programming Customized Requests and Responses section of http://java.sun.com/products/servlet/Filters.html
------ Update ------
I must be missing something. You say you can read the request body and read the parameters yourself. Couldn't you then ensure your filter is first, wrap the ServletRequest object, read, process and store the parameters, pass your request object up the chain and offer the parameters you stored instead of the original ones?

Related

Spring form input values return null after read it once in filter, despite using request wrapper

In my spring-boot project, I use freemarker templates for sample forms. I needed to add filter in order to read payload and do some stuff. I know if you read payload in filter, you need to reset request body. Because it can be read once. Since I encountered this problem before, I knew that I must have used wrapper. I expected solve my problem as before. However, in the controller, all fields in input objects are null.
What am I missing in here ?
My filter:
public class KfsInMsgFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
Map<String, String[]> extraParams = new TreeMap<String, String[]>();
WrappedRequest wrappedRequest = new WrappedRequest(request, extraParams);
String body = IOUtils.toString(new BufferedReader(new InputStreamReader(wrappedRequest.getInputStream(), Constants.UTF_8)));
// doing some stuff using body
// ....
// resetting payload
wrappedRequest.resetStream(body.getBytes(Constants.UTF_8));
...
}
}
WrappedRequest class:
#Slf4j
public class WrappedRequest extends HttpServletRequestWrapper {
private final Map<String, String[]> modifiableParameters;
private ResettableServletInputStream servletStream;
private byte[] rawData;
private HttpServletRequest request;
private String payload;
/**
* Create a new request wrapper that will merge additional parameters into
* the request object without prematurely reading parameters from the
* original request.
*
* #param request
* #param additionalParams
*/
public WrappedRequest(final HttpServletRequest request,
final Map<String, String[]> additionalParams) {
super(request);
this.request = request;
this.modifiableParameters = new TreeMap<String, String[]>();
this.modifiableParameters.putAll(additionalParams);
this.servletStream = new ResettableServletInputStream();
}
/**
* #param newRawData
*/
public void resetStream(byte[] newRawData) {
servletStream.stream = new ByteArrayInputStream(newRawData);
}
/**
* #return
* #throws IOException
*/
#Override
public ServletInputStream getInputStream() throws IOException {
if (rawData == null) {
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return servletStream;
}
/**
* #return
* #throws IOException
*/
#Override
public BufferedReader getReader() throws IOException {
if (rawData == null) {
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return new BufferedReader(new InputStreamReader(servletStream, Constants.UTF_8));
}
/**
* #return
*/
private String getBodyAsString() {
StringBuffer buff = new StringBuffer();
buff.append(" BODY_DATA START [ ");
char[] charArr = new char[getContentLength()];
try {
BufferedReader reader = new BufferedReader(getReader());
reader.read(charArr, 0, charArr.length);
reader.close();
} catch (IOException e) {
log.error("", e);
}
buff.append(charArr);
buff.append(" ] BODY_DATA END ");
return buff.toString();
}
/**
* #return
*/
public String getPayload() {
return payload;
}
/**
* #param payload
*/
public void setPayload(String payload) {
this.payload = payload;
}
private static class ResettableServletInputStream extends ServletInputStream {
private InputStream stream;
#Override
public int read() throws IOException {
return stream.read();
}
#Override
public boolean isFinished() {
return false;
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
}
}
}
Body I expected to get in controller:
What I get:
#PostMapping(value = "/edit")
public String editPlatform(EditInfo editInfo, Model model) {
Optional<Platform> p = platformService.findById(editInfo.getId());
List<SafeCustodyOffice> officeList = safeCustodyOfficeService.getAll();
if (p.isPresent()) {
model.addAttribute("platform", p.get());
model.addAttribute("offices", officeList);
return "platform-edit";
} else {
throw new KfsException(ErrorCodes.KFS19);
}
}
Important Edit:
I discovered someting I found interesting and gives me clues about the problem. This may be makes more sense for anybody but me.
I see that the content type of input changes the result like this:
Is there any workaround to make row 5 combination work like row 3?

Sorting Java case statements

I came through here a little while ago trying to find out if there was in fact a way to auto sort case statements.. Eclipse doesn't have the answer to do this automatically. So I wanted to find out a way to do this. Sadly this doesn't appear to be something addressed anywhere. Is this something everyone will need to do... probably not.
Here is my solution:
Main call:
package com.debug;
import java.io.IOException;
public class DebugMain {
public static void main(String[] args) {
fixCases();
}
public static void fixCases() {
String filePath = System.getProperty("user.home").replace("\\", "/") + "/Documents/";
String fileName = "case.txt";
System.out.println("Organizing cases: " + filePath + fileName);
CaseHandler ch = new CaseHandler(filePath + fileName, CaseType.Integer);
try {
ch.readFile();
ch.sortCases();
ch.writeCases(filePath + "casetest.txt");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Organizing complete.");
}
}
CaseHandler:
package com.debug;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* This handler allows you to read from a text file a list of case statements, sort the case statements<br />
* in natural order, and write to a file.
*
* #author Vincent
*/
public class CaseHandler {
/**
* This denotes the use of numerical or text based case statements.
*/
public enum CaseType {
String, Integer;
}
private boolean autoSort = false;
private ArrayList<Case> cases = new ArrayList<Case>();
private CaseType caseType;
private File file;
/**
* This construcs a basic <code>CaseHandler</code> in which a file must be provided
* within the {#link #readFile(String)} method.
* <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
* The formatting is not important.
*
* #param caseType The type of case this instance should use.
* #see {#link CaseType}, {#link CaseHandler}
*/
public CaseHandler(CaseType caseType) {
this.caseType = caseType;
}
/**
* This construcs a <code>CaseHandler</code> with a file provided.<br />
* <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
* The formatting is not important.
*
* #param fileName The full file path and name to be read from and/or written to.
* #param caseType The type of case this instance should use.
* #see {#link CaseType}, {#link CaseHandler}
*/
public CaseHandler(String fileName, CaseType caseType) {
this.caseType = caseType;
this.file = new File(fileName);
}
/**
* This construcs a <code>CaseHandler</code> with a file provided.<br />
* <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
* The formatting is not important.
*
* #param fileName The full file path and name to be read from and/or written to.
* #param caseType The type of case this instance should use.
* #param autoSort Enables auto sorting in the {#link #readFile()}
*/
public CaseHandler(String fileName, CaseType caseType, boolean autoSort) {
this.caseType = caseType;
this.file = new File(fileName);
this.autoSort = autoSort;
}
/**
* Reads the file where the case statements are stored line by line.<br />
* When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
* If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
* When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
* This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
* If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
*
* #throws IOException
* #see {#link ArrayList}, {#link FileReader}, {#link BufferedReader}, {#link Case}
*/
public void readFile() throws IOException {
if (this.file != null && this.file.exists()) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(this.file);
br = new BufferedReader(fr);
String line = "";
ArrayList<String> lines = null;
while ((line = br.readLine()) != null) {
if (line.contains("case")) {
if (lines != null && lines.get(lines.size() - 1).contains("break")) {
lines = new ArrayList<String>();
} else {
lines = new ArrayList<String>();
}
}
lines.add(line);
if (line.contains("break")) {
String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
Case aCase = null;
if (caseType == CaseType.Integer) {
aCase = new Case(Integer.parseInt(caseName), lines);
} else if (caseType == CaseType.String) {
aCase = new Case(caseName, lines);
}
cases.add(aCase);
}
}
if (this.autoSort) {
this.sortCases();
}
} finally {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
}
} else {
System.out.println("File " + this.file.getName() + " does not exist!");
}
}
/**
* Reads the file where the case statements are stored line by line.<br />
* When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
* If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
* When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
* This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
* If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
*
* #param fileName The full file path and name to be read from and/or written to.
* #throws IOException
* #see {#link ArrayList}, {#link FileReader}, {#link BufferedReader}, {#link Case}
*/
public void readFile(String fileName) throws IOException {
this.file = new File(fileName);
if (this.file != null && this.file.exists()) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(this.file);
br = new BufferedReader(fr);
String line = "";
ArrayList<String> lines = null;
while ((line = br.readLine()) != null) {
if (line.contains("case")) {
if (lines != null && lines.get(lines.size() - 1).contains("break")) {
lines = new ArrayList<String>();
} else {
lines = new ArrayList<String>();
}
}
lines.add(line);
if (line.contains("break")) {
String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
Case aCase = null;
if (caseType == CaseType.Integer) {
aCase = new Case(Integer.parseInt(caseName), lines);
} else if (caseType == CaseType.String) {
aCase = new Case(caseName, lines);
}
cases.add(aCase);
}
}
if (this.autoSort) {
this.sortCases();
}
} finally {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
}
} else {
System.out.println("File " + this.file.getName() + " does not exist!");
}
}
/**
* Sorts the {#link ArrayList} in alphabetical or numerical order.<br />
* <b>Note:</b> This will <b>NOT</b> sort clusters of case statements.
* #see {#link Collections#sort(java.util.List)}
*/
public void sortCases() {
if (cases.size() > 0) {
Collections.sort(cases, Comparator.naturalOrder());
}
}
/**
* Overwrites the file provided to the <code>CaseHandler</code> with the cases list.
*
* #throws IOException
* #see {#link ArrayList}, {#link FileWriter}, {#link BufferedWriter}, {#link Case}
*/
public void writeCases() throws IOException {
if (this.file.exists()) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(this.file);
bw = new BufferedWriter(fw);
for (Case aCase : cases) {
for (String line : aCase.getLines()) {
bw.write(line);
bw.newLine();
}
}
} finally {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
}
}
}
/**
* Overwrites the file provided to with the cases list.
*
* #param fileName The full file path and name to be read from and/or written to.
* #throws IOException
* #see {#link ArrayList}, {#link FileWriter}, {#link BufferedWriter}, {#link Case}
*/
public void writeCases(String fileName) throws IOException {
File outFile = new File(fileName);
if (!outFile.exists()) {
outFile.createNewFile();
}
if (outFile.exists()) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(outFile);
bw = new BufferedWriter(fw);
for (Case aCase : cases) {
for (String line : aCase.getLines()) {
bw.write(line);
bw.newLine();
}
}
} finally {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
}
}
}
/**
* Changes the case type.
*
* #param caseType The new type of case this instance should use.
* #see {#link CaseType}
*/
public void setCaseType(CaseType caseType) {
this.caseType = caseType;
}
}
Case:
package com.debug;
import java.util.ArrayList;
/**
* This is the individual case statement starting at <code>case (Integer or String):</code> <br />
* The last line stored in the instance will be the <code>break;</code> statement.
*
* #author Vincent
*
*/
public class Case implements Comparable<Case> {
private int nameInt;
private String nameStr = null;
private ArrayList<String> lines;
/**
* Constructs a new <code>Case</code> using integer values as the name.
*
* #param nameInt The integer value name
* #param lines The lines within this case statement
* #see {#link ArrayList}
*/
public Case(int nameInt, ArrayList<String> lines) {
this.nameInt = nameInt;
this.lines = lines;
}
/**
* Constructs a new <code>Case</code> using string values as the name.
*
* #param nameStr The string value name
* #param lines The lines within this case statement
* #see {#link ArrayList}
*/
public Case(String nameStr, ArrayList<String> lines) {
this.nameStr = nameStr;
this.lines = lines;
}
#Override
public int compareTo(Case aCase) {
if (this.nameStr != null) {
return this.nameStr.compareTo(aCase.getNameStr());
} else {
if (this.nameInt < aCase.getNameInt()) {
return -1;
} else if (this.nameInt > aCase.getNameInt()) {
return 1;
} else {
return 0;
}
}
}
/**
* Returns the lines stored in this <code>Case</code> instance.
*
* #return {#link ArrayList}
*/
public ArrayList<String> getLines() {
return this.lines;
}
/**
* Returns the integer name of this <code>Case</code> instance.
*
* #return {#link Integer}
*/
public int getNameInt() {
return this.nameInt;
}
/**
* Returns the string name of this <code>Case</code> instance.
*
* #return {#link String}
*/
public String getNameStr() {
return this.nameStr;
}
}
Example input:
case 338:
// Code
break;
case 852:
// Code
break;
case 2:
// Code
break;
case 696:
// Code
break;
Example output:
case 2:
// Code
break;
case 338:
// Code
break;
case 696:
// Code
break;
case 852:
// Code
break;
Hope this potentially helps someone out. I needed this cause I was looking at a long list of cases (1000 of them to be exact) that were sorted in no particular order or with any reason to be sorted that way. So I wanted to see them in natural order.

Extracting data from Json object by http GET

I am working on android app and I want to know how to get data from Json object by using http GET the (the http request url is APIary)
It's my first time to use Json and httpRequests so I don't know the syntax needed for this
That's my HttpRequest class I'm using :
public abstract class HttpRequest extends AsyncTask<String, String, String> {
private HttpClient httpClient;
private HttpRequestBase request;
private boolean hasError = false;
private String errorMessage = null;
private boolean hasBody = false;
private int statusCode;
public HttpRequest(){
httpClient = new DefaultHttpClient();
}
/**
* This method is called from the subclasses to pass the request method used to this class
* #param request , The request class passed from the subclass
*/
void setMethod(HttpRequestBase request){
this.request = request;
}
/**
* Adds a header to the current request
* #param header , header key
* #param value , header value
*/
public void addHeader(String header,String value){
this.request.addHeader(header, value);
}
/**
* #return false if the status code was anything other than 2XX after executing the request , true otherwise
*/
public boolean hasError() {
return hasError;
}
/**
* A getter for the error message
* #return String the error message returned from the request if any
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* This is the method responsible for executing the request and handling the response
* #return String , The response body , null in case of errors
*/
#Override
protected String doInBackground(String... args) {
if(hasBody){
this.request.addHeader("content-type", "application/json");
}
ResponseHandler<String> handler = new BasicResponseHandler();
HttpResponse x = null;
try{
x = httpClient.execute(this.request);
this.statusCode = x.getStatusLine().getStatusCode();
return handler.handleResponse(x);
}catch(ClientProtocolException e ){
hasError = true;
errorMessage = e.getMessage();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* A getter method for the status code
* #return int , the status code of executing the request
*/
public int getStatusCode(){
return this.statusCode;
}
/**
* A setter method to set whether the request has a body or not , used between this class and its subclasses
* #param hasBody boolean
*/
void setHasBody(boolean hasBody){
this.hasBody = hasBody;
}
}
I think this post can help you :
How to parse JSON in Android
Tell me if don't understand !

Disposable MBean

How could I implement disposable MBean, one that doesn't prevent resource it is monitoring from being garbage collected?
Let say I wrote dummy statistic MBean but the class it is monitoring is not singleton in the system. I would like MBean to be automatically unregistered once resource is no longer in use.
Any ideas how to achieve that?
Any existing solutions?
Thanks.
Usage
registerWeakMBean("com.company:type=connection,name=" +
getClass().getSimpleName(), connectionStatMBeanImpl, ConnectionStatMBean.class);
Implementatin
package util;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import sun.management.Agent;
public class JmxUtils {
private static Logger log = Logger.getLogger(JmxUtils.class);
private static Map<Object, String> weakMBeans = new ConcurrentHashMap<Object, String>();
static {
verifyJmxAgentStarted();
}
private static final int getAvailablePort() throws IOException {
ServerSocket s = new ServerSocket(0);
int result = s.getLocalPort();
s.close();
return result;
}
/**
* #param objName
* domain:type=value[,name=value]
* #param implementation
* #param mbeanInterface
* #see ObjectName
* #see StandardMBean
*/
public static final <I> ObjectInstance registerMBean(String objName, I implementation, Class<I> mbeanInterface) {
int counter = 0;
String uniqueSuffix = "";
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
while (true) {
try {
final ObjectName name = new ObjectName(objName + uniqueSuffix);
final StandardMBean mbean = new StandardMBean(implementation, mbeanInterface);
return mbs.registerMBean(mbean, name);
} catch (final InstanceAlreadyExistsException e) {
uniqueSuffix = "" + ++counter;
} catch (final Exception e) {
throw new Error(e);
}
}
}
/**
* Weak MBean will not prevent resource it is monitoring from been garbage collected. MBean will be automatically unregistered.
*
* #param objName
* domain:type=value[,name=value]
* #param implementation
* #param mbeanInterface
* #see ObjectName
* #see StandardMBean
* #see WeakReference
*/
public static final <I> ObjectInstance registerWeakMBean(String objName, I implementation, Class<I> mbeanInterface) {
I proxy = DisposableWeakReference.newWeakReferenceProxy(new DisposableWeakReference<I>(implementation) {
#Override
public void dispose(Object disposable) {
unregisterMBean(weakMBeans.remove(disposable));
}
}, mbeanInterface);
ObjectInstance instance = registerMBean(objName, proxy, mbeanInterface);
weakMBeans.put(proxy, instance.getObjectName().getCanonicalName());
return instance;
}
public static <T> T newJmxClient(Class<T> clazz, String objectName, String serviceUrl) {
return createJmxClient(clazz, objectName, serviceUrl, null, null);
}
public static <T> T newJmxClient(Class<T> clazz, String objectName, String serviceUrl, final String user, final String pass) {
try {
JMXServiceURL jmxServiceUrl = new JMXServiceURL(serviceUrl);
Map<String, ?> env = user == null ? null : new HashMap<String, Object>() {{
put(JMXConnector.CREDENTIALS, new String[] {user, pass});
}};
JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceUrl, env);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
ObjectName mbeanName = new ObjectName(objectName);
return JMX.newMBeanProxy(mbsc, mbeanName, clazz, true);
} catch (IOException | MalformedObjectNameException e) {
throw new RuntimeException("Can not create client for remote JMX " + serviceUrl, e);
}
}
/**
* #param objName
* #see ObjectName
*/
public static final void unregisterMBean(String objName) {
try {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
final ObjectName name = new ObjectName(objName);
mbs.unregisterMBean(name);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private static final void verifyJmxAgentStarted() {
try {
String port = System.getProperty("com.sun.management.jmxremote.port");
if (port == null) {
port = String.valueOf(getAvailablePort());
System.setProperty("com.sun.management.jmxremote.port", port);
System.setProperty("com.sun.management.jmxremote.ssl", "false");
System.setProperty("com.sun.management.jmxremote.authenticate", "false");
Agent.startAgent();
}
log.info(InetAddress.getLocalHost().getCanonicalHostName() + ":" + port);
} catch (Exception e) {
throw new Error(e);
}
}
}
package util;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.WeakHashMap;
/**
* Disposable weak reference calls you back when referent has been disposed. You can also create proxy to the referent to emulate direct access.
*
* <pre>
* public class Example {
* public interface I {
* // interface referent is implementing to create a proxy
* }
*
* public static final class T implements I {
* public String toString() {
* return "blah";
* }
* }
*
* private WeakReference&ltT&gt wr;
* private I wrp;
* private List&ltObject&gt list = new LinkedList&ltObject&gt();
*
* private void testWeakRef() {
* T o = new T();
* wr = new DisposableWeakReference&ltT&gt(o) {
* public void dispose(Object disposable) {
* list.remove(disposable);
* }
* };
* list.add(wr);
* wrp = DisposableWeakReference.newWeakReferenceProxy(new DisposableWeakReference&ltI&gt(o) {
* public void dispose(Object disposable) {
* list.remove(disposable);
* Example.this.wrp = null;
* }
* }, I.class);
* list.add(wrp);
* }
*
* public static void main(final String[] args) throws Exception {
* Example exmple = new Example();
* exmple.testWeakRef(); // try to replace with exact implementation
*
* System.out.println("exmple.wr.get() " + exmple.wr.get()); // blah
* System.out.println("exmple.wrp " + exmple.wrp); // blah
* System.out.println("exmple.list.contains(exmple.wr) " + exmple.list.contains(exmple.wr)); // true
* System.out.println("exmple.list.contains(exmple.wrp) " + exmple.list.contains(exmple.wrp)); // true
* System.gc();
* Thread.sleep(10);
* System.out.println("exmple.wr.get() " + exmple.wr.get()); // null
* System.out.println("exmple.wrp " + exmple.wrp); // null or exception
* System.out.println("exmple.list.contains(exmple.wr) " + exmple.list.contains(exmple.wr)); // false
* System.out.println("exmple.list.contains(exmple.wrp) " + exmple.list.contains(exmple.wrp)); // false
* }
* }
*
* <pre>
*
* #param <T> weak reference referent type
* #author Mykhaylo Adamovych
*/
#SuppressWarnings({ "rawtypes" })
public abstract class DisposableWeakReference<T> extends WeakReference<T> {
public static class DisposedException extends RuntimeException {
private static final long serialVersionUID = -1176608195614694732L;
public DisposedException() {
super();
}
public DisposedException(String message) {
super(message);
}
public DisposedException(String message, Throwable cause) {
super(message, cause);
}
public DisposedException(Throwable cause) {
super(cause);
}
}
private static class ReferenceProxy<T> implements InvocationHandler {
private final DisposableWeakReference<T> reference;
public ReferenceProxy(DisposableWeakReference<T> reference) {
this.reference = reference;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("equals".equals(method.getName()))
return proxy == args[0];
else if ("hashCode".equals(method.getName()))
return hashCode();
T referent = reference.get();
if (referent == null)
throw new DisposedException("Referent has been disposed.");
return method.invoke(referent, args);
}
}
private static class WeakReferenceDisposerThread extends Thread {
WeakReferenceDisposerThread() {
super("Weak Reference Disposer");
}
#Override
public void run() {
while (true)
try {
DisposableWeakReference<?> reference = (DisposableWeakReference<?>) queue.remove();
Object disposable = reference.proxy;
if (disposable == null)
disposable = reference;
reference.dispose(disposable);
} catch (Throwable e) {
// ignore any exception while disposing
}
}
}
private static final ReferenceQueue queue = new ReferenceQueue();
static {
Thread disposer = new WeakReferenceDisposerThread();
disposer.setPriority(Thread.MAX_PRIORITY - 2);
disposer.setDaemon(true);
disposer.start();
}
/**
* You can use referent directly without {#link #get()}. Runtime exception will rise in case referent has been disposed by GC. You can use
* {#link #dispose(Object)} to deal with proxy also.
*
* #param reference
* disposable weak reference
* #param clazz
* referent interface class
* #param <T>
* referent type
* #param <I>
* referent interface to create a proxy
* #return referent proxy using weak reference
*/
public static <I> I newWeakReferenceProxy(DisposableWeakReference<I> reference, Class<I> clazz) {
I proxy = ReflectUtils.<I>newProxyInstance(new ReferenceProxy<I>(reference), clazz);
reference.proxy = proxy;
return proxy;
}
private Object proxy;
public DisposableWeakReference(T referent) {
super(referent, queue);
}
/**
* Remove this weak reference wrapper from whatever when referent has been garbage collected.
*
* #param disposable
* either this reference instance or proxy instance created by {#link #newWeakReferenceProxy(DisposableWeakReference, Class)}
* #see WeakHashMap
*/
public abstract void dispose(Object disposable);
}

problem in connecting to https url

I am able to connect to http url's but when
the server moved to https, my code is not working.
Can anyone help me in geeting it right with minimal changes.
I am using the following manager file (open source code)
for doing all kind of http request (uploading file,
downloading file or simple authentications).
I tried using the httpsUrlConnection as well but i guess,
i am missing something there. Please suggest something...
public class ClientHttpRequest
{
HttpURLConnection connection;
OutputStream os = null;
public static int responseCode;
public static String responseContentLength;
protected void connect() throws IOException
{
if (os == null) os = connection.getOutputStream();
}
protected void write(char c) throws IOException
{
connect();
os.write(c);
}
protected void write(String s) throws IOException
{
connect();
os.write(s.getBytes());
}
protected void newline() throws IOException
{
connect();
write("\r\n");
}
protected void writeln(String s) throws IOException
{
connect();
write(s);
newline();
}
private static Random random = new Random();
protected static String randomString() {
return Long.toString(random.nextLong(), 36);
}
String boundary = "---------------------------" + randomString() + randomString() + randomString();
private void boundary() throws IOException
{
write("--");
write(boundary);
}
/**
* Creates a new multipart POST HTTP request on a freshly opened URLConnection
* #param connection an already open URL connection
* #throws IOException
*/
public ClientHttpRequest(HttpURLConnection connection) throws IOException
{
this.connection = connection;
connection.setDoOutput(true);
connection.setConnectTimeout(20000);
connection.setReadTimeout(0);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
}
/**
* Creates a new multipart POST HTTP request for a specified URL
* #param url the URL to send request to
* #throws IOException
*/
public ClientHttpRequest(URL url) throws IOException
{
this((HttpURLConnection)url.openConnection());
}
/**
* Creates a new multipart POST HTTP request for a specified URL string
* #param urlString the string representation of the URL to send request to
* #throws IOException
*/
public ClientHttpRequest(String urlString) throws IOException
{
this(new URL(urlString));
}
private void writeName(String name) throws IOException
{
newline();
write("Content-Disposition: form-data; name=\"");
write(name);
write('"');
}
/**
* adds a string parameter to the request
* #param name parameter name
* #param value parameter value
* #throws IOException
*/
public void setParameter(String name, String value) throws IOException
{
boundary();
writeName(name);
newline(); newline();
writeln(value);
}
private static void pipe(InputStream in, OutputStream out) throws IOException
{
byte[] buf = new byte[500000];
int nread;
int total = 0;
synchronized (in)
{
while((nread = in.read(buf, 0, buf.length)) >= 0)
{
out.write(buf, 0, nread);
total += nread;
}
}
out.flush();
buf = null;
}
/**
* adds a file parameter to the request
* #param name parameter name
* #param filename the name of the file
* #param is input stream to read the contents of the file from
* #throws IOException
*/
public void setParameter(String name, String filename, InputStream is) throws IOException
{
boundary();
writeName(name);
write("; filename=\"");
write(filename);
write('"');
newline();
write("Content-Type: ");
String type = URLConnection.guessContentTypeFromName(filename);
if (type == null)
{
type = "application/octet-stream";
}
writeln(type);
newline();
pipe(is, os);
newline();
}
/**
* adds a file parameter to the request
* #param name parameter name
* #param file the file to upload
* #throws IOException
*/
public void setParameter(String name, File file) throws IOException
{
setParameter(name, file.getPath(), new FileInputStream(file));
}
/**
* adds a parameter to the request; if the parameter is a File, the file is uploaded, otherwise the string value of the parameter is passed in the request
* #param name parameter name
* #param object parameter value, a File or anything else that can be stringified
* #throws IOException
*/
public void setParameter(String name, Object object) throws IOException
{
if (object instanceof File)
{
setParameter(name, (File)object);
}
else
{
setParameter(name, object.toString());
}
}
/**
* adds parameters to the request
* #param parameters array of parameter names and values (parameters[2*i] is a name, parameters[2*i + 1] is a value); if a value is a file, the file is uploaded, otherwise it is stringified and sent in the request
* #throws IOException
*/
public void setParameters(Object[] parameters) throws IOException
{
if (parameters == null) return;
for (int i = 0; i < parameters.length - 1; i+=2)
{
setParameter(parameters[i].toString(), parameters[i+1]);
}
}
/**
* posts the requests to the server, with all the cookies and parameters that were added
* #return input stream with the server response
* #throws IOException
*/
public InputStream post() throws IOException
{
boundary();
writeln("--");
os.close();
InputStream inputStream = null;
try
{
responseCode = connection.getResponseCode();
responseContentLength = connection.getHeaderField("Content-Length");
inputStream = connection.getInputStream();
}
catch(Exception exception)
{
exception.printStackTrace();
responseCode = connection.getResponseCode();
inputStream = connection.getErrorStream();
}
return inputStream;
}
/**
* posts the requests to the server, with all the cookies and parameters that were added before (if any), and with parameters that are passed in the argument
* #param parameters request parameters
* #return input stream with the server response
* #throws IOException
* #see setParameters
*/
public InputStream post(Object[] parameters) throws IOException
{
setParameters(parameters);
return post();
}
/**
* post the POST request to the server, with the specified parameter
* #param name parameter name
* #param value parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public InputStream post(String name, Object value) throws IOException
{
setParameter(name, value);
return post();
}
/**
* post the POST request to the server, with the specified parameters
* #param name1 first parameter name
* #param value1 first parameter value
* #param name2 second parameter name
* #param value2 second parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public InputStream post(String name1, Object value1, String name2, Object value2) throws IOException
{
setParameter(name1, value1);
return post(name2, value2);
}
/**
* post the POST request to the server, with the specified parameters
* #param name1 first parameter name
* #param value1 first parameter value
* #param name2 second parameter name
* #param value2 second parameter value
* #param name3 third parameter name
* #param value3 third parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException
{
setParameter(name1, value1);
return post(name2, value2, name3, value3);
}
/**
* post the POST request to the server, with the specified parameters
* #param name1 first parameter name
* #param value1 first parameter value
* #param name2 second parameter name
* #param value2 second parameter value
* #param name3 third parameter name
* #param value3 third parameter value
* #param name4 fourth parameter name
* #param value4 fourth parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException
{
setParameter(name1, value1);
return post(name2, value2, name3, value3, name4, value4);
}
/**
* posts a new request to specified URL, with parameters that are passed in the argument
* #param parameters request parameters
* #return input stream with the server response
* #throws IOException
* #see setParameters
*/
public static InputStream post(URL url, Object[] parameters) throws IOException
{
return new ClientHttpRequest(url).post(parameters);
}
/**
* post the POST request specified URL, with the specified parameter
* #param name parameter name
* #param value parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public static InputStream post(URL url, String name1, Object value1) throws IOException
{
return new ClientHttpRequest(url).post(name1, value1);
}
/**
* post the POST request to specified URL, with the specified parameters
* #param name1 first parameter name
* #param value1 first parameter value
* #param name2 second parameter name
* #param value2 second parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2) throws IOException
{
return new ClientHttpRequest(url).post(name1, value1, name2, value2);
}
/**
* post the POST request to specified URL, with the specified parameters
* #param name1 first parameter name
* #param value1 first parameter value
* #param name2 second parameter name
* #param value2 second parameter value
* #param name3 third parameter name
* #param value3 third parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException
{
return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3);
}
/**
* post the POST request to specified URL, with the specified parameters
* #param name1 first parameter name
* #param value1 first parameter value
* #param name2 second parameter name
* #param value2 second parameter value
* #param name3 third parameter name
* #param value3 third parameter value
* #param name4 fourth parameter name
* #param value4 fourth parameter value
* #return input stream with the server response
* #throws IOException
* #see setParameter
*/
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException
{
return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3, name4, value4);
}
}
sample code for Disabling Certificate Validation in an HTTPS Connection
http://exampledepot.com/egs/javax.net.ssl/TrustAll.html
use this code in yr java prog
try {
logger.info("Importing the Https certificate..");
/* ----------- Importing the Https certificate -----------*/
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
System.out.println("Exception" + e);
}
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
});
and see this link u have to make change in server.xml

Categories

Resources