Read HTTP POST from mobile in java - java

I have iOS Swift code, which sends a POST request to server. If i send this code directly to apple server i get response back with proper data. But when i send this to my server, server could not get the body of the HTTP POST.
I have no idea whether this issue is related to client side or server side.
Here is the Swift code.
func validateReceipt(completion : (status : Bool) -> ()) {
let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL!
if NSFileManager.defaultManager().fileExistsAtPath(receiptUrl.path!)
{
if let receipt : NSData = NSData(contentsOfURL: receiptUrl)
{
let receiptdata: NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
let dict = ["receipt-data" : receiptdata]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
let request = NSMutableURLRequest(URL: NSURL(string: ReceiptURL.MAIN_SERVER.rawValue)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = jsonData
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let dataR = data
{
self.handleData(dataR, completion: { status in
completion(status: status)
})
}
})
task.resume()
}
else
{
completion(status: false)
}
}
else
{
completion(status: false)
}
}
and here is my Java code in server side, there are two Java classes which take care of this
MyRequestWrapper.Java
package webservice;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
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[100000];
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();
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
And here is the another class.
GetResult.Java
package webservice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
#Path("/service")
public class GetResult {
static Logger logger = Logger.getLogger(GetResult.class);
// #Produces("application/json; charset=UTF-8")
//#Produces("text/plain")
#POST
#Produces (MediaType.APPLICATION_JSON)
public Response inapp(#Context HttpServletRequest request,
#Context HttpServletResponse response) throws Exception {
System.out.println("response===" + response);
System.out.println("Request-Header===" + request.getHeader("receipt-data"));
System.out.println("Request===" + request.getParameter("receipt-data"));
// System.out.println("Request==="+request.getReader());
// reader(request,response);
// getBody(request);
doFilter(request,response);
String result = "";
result = " " /* jsonObject */;
return Response.status(200).entity(result).build();
}
We could get the client IP and client Port from this request but unable to get the body. In production also we could not get the body. Some Java developers told me that you cant directly get the raw bytes in Java, i don't know about this.
Somebody please take a look at this, and tell me what i am doing wrong.

You may have to explicitly set the content type of the input post body you send to the server. This can be achieved as follows:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Set the content type after setting the http method and son data to the request object( NSMutableURLRequest object)
This may help you!
Edited:
Actually the header field name is "Content-Type".

Related

Mock an instance method call of another class that takes a URL and File object and writes a file to a HTTP connection

I'm trying to write UTs for a file called DocumentStoreAccessor.java. Here is the class below:
package com.company.main.accessor;
import com.company.main.dagger.component.AccessorComponent;
import com.company.main.dagger.component.DaggerAccessorComponent;
import com.company.main.util.aws.s3.AWSS3Util;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
#Slf4j
#RequiredArgsConstructor
public class DocumentStoreAccessor {
private final DocumentStore documentStoreClient; //Comes from Dagger
public DocumentStoreAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.documentStoreClient = accessorComponent.provideDocumentStoreClient();
}
private int putContentsIntoS3(CreateUploadS3UrlResult createUploadS3UrlResponse,
#NonNull File file) {
int uploadStatusCode = 0;
try {
URL url = new URL(createUploadS3UrlResponse.getS3Url());
uploadStatusCode = new AWSS3Util().upload(url, file); //Instance comes from a util class
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uploadStatusCode;
}
public String uploadFile(File file, DocumentFileExtension fileExtension) throws Exception {
String documentId = null;
CreateUploadS3UrlResult createUploadS3Urlresult = documentStoreClient.createUploadS3Url(new CreateUploadS3UrlRequest());
int putContentsStatusCode = putContentsIntoS3(createUploadS3Urlresult, file);
if (putContentsStatusCode == 200) {
CreateDocumentRequest createDocumentRequest = new CreateDocumentRequest()
CreateDocumentResult document = documentStoreClient.createDocument(createDocumentRequest);
documentId = document.getDocumentId();
} else {
throw new Exception("Status code is: " + putContentsStatusCode);
}
return documentId;
}
}
Inside this file I do new AWSS3Util().upload(url, file).
And here is the AWSS3Util.java
package com.company.main.util.aws.s3;
import com.company.main.exception.DataAccessException;
import com.company.main.exception.RetriableDataAccessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
#Slf4j
#AllArgsConstructor
#Builder
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
final InputStream inputStream = new FileInputStream(file);
final Reader fileReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
final BufferedReader br = new BufferedReader(fileReader);
HttpURLConnection connection = null;
int responseCode = 0;
try {
// Create the connection and use it to upload the new object using the pre-signed URL.
connection = create(url);
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
final OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
String st;
while ((st = br.readLine()) != null) {
out.write(st);
}
out.close();
responseCode = connection.getResponseCode();
} catch (IOException e) {
throw new RetriableDataAccessException(String.format("S3 upload request failed with request: %s", url.toString()), e);
} finally {
inputStream.close();
fileReader.close();
br.close();
}
return responseCode;
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
I want to make new AWSS3Util().upload(url, file) return a 200..
I'm unable to do so.. I keep getting a NullPointerException. Here is what I have for the past day:
package com.company.main.accessor;
import com.company.main.util.aws.s3.AWSS3Util;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#ExtendWith(MockitoExtension.class)
public class DocumentStoreAccessorTest {
#Mock
private DocumentStore mockDocumentStoreClient;
#Mock
private HttpURLConnection httpURLConnection;
#Mock
private OutputStream outputStream;
#InjectMocks
private DocumentStoreAccessor classUnderTest;
private URL url;
private AWSS3Util awss3Util;
private CreateUploadS3UrlRequest dummyCreateUploadS3UrlRequest;
private CreateUploadS3UrlResult dummyCreateUploadS3UrlResult;
private CreateDocumentRequest dummyCreateDocumentRequest;
private CreateDocumentResult dummyCreateDocumentResult;
#BeforeEach
void setUp() throws IOException {
awss3Util = new AWSS3Util();
url = getMockUrl(httpURLConnection);
dummyCreateUploadS3UrlRequest = new CreateUploadS3UrlRequest();
dummyCreateUploadS3UrlResult = new CreateUploadS3UrlResult().withS3Url("http://foo.io://:99");
dummyCreateDocumentRequest = new CreateDocumentRequest();
dummyCreateDocumentResult = new CreateDocumentResult().withDocumentId("foo");
}
#Test
void uploadSuccess() throws IOException {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
AWSS3Util aSpy = Mockito.spy(awss3Util);
Mockito.when(aSpy.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
private File getDataToUpload() {
return new File("TestFileName.xlsx");
}
/**
* We cannot directly use Mockito to mock URL. This helper method, helps us to create the mock url.
* <p>
* https://stackoverflow.com/questions/565535/mocking-a-url-in-java
*/
private URL getMockUrl(HttpURLConnection httpURLConnection) throws IOException {
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return httpURLConnection;
}
};
final URL url = new URL("http://foo.io", "foo.io", 80, "", handler);
return url;
}
}
I'm unable to mock the URL class, so I followed a another Stackoverflow post..
The AWSS3Util cannot come through Dagger, it is a util class that we're all using so this must not change.
I'm not sure if I'm going in the right direction.. I've tried "spying" on that AWSS3Util class. I want this method to return a 200 or any status code of my choice to cover them in UTs by asserting a String return as seen in the example below
I can change the the upload method inside AWSS3Util to static if it helps UTs
Cannot use PowerMockito (this is a last resort)
Try incorporating Yan's comments:
#Test
void verifyCreateUploadS3UrlInvocation() throws Exception {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
when(httpURLConnection.getOutputStream()).thenReturn(outputStream);
when(httpURLConnection.getResponseCode()).thenReturn(200);
when(awss3Util.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
I get a 405 thrown when I specifically want it to send a 200, and therefore java.lang.Exception: Status code is: 405 thrown from my function.
Firstly I would change a little bit AWSS3Util, because reading binary files as string can lead to very interesting results.
import lombok.NonNull;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
HttpURLConnection connection = create(url);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
try (BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream())) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
return connection.getResponseCode();
}
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
Test for upload method could be like this:
import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.nio.file.Files;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MyTest {
#Test
public void test() throws IOException {
final HttpURLConnection mockUrlCon = mock(HttpURLConnection .class);
URLStreamHandler stubUrlHandler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return mockUrlCon;
}
};
URL url = new URL("http://foo.io", "foo.io", 80, "", stubUrlHandler);
when(mockUrlCon.getResponseCode()).thenReturn(200);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
when(mockUrlCon.getOutputStream()).thenReturn(outputStream);
File file = new File("c:\\anyFile.png");
int responseCode = new AWSS3Util().upload(url, file);
assertEquals(200, responseCode);
byte[] expectedBytes = Files.readAllBytes(file.toPath());
byte[] actualBytes = outputStream.toByteArray();
assertArrayEquals(expectedBytes, actualBytes);
}
}
I had to violate the second rule - I had to DependencyInject it via Dagger
package com.company.main.dagger.module;
import com.company.main.util.aws.s3.AWSS3Util;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
#Module
public class AWSS3UtilModule {
#Provides
#Singleton
public static AWSS3Util provideAwss3Util() {
return new AWSS3Util();
}
}
and then in my component
import javax.inject.Singleton;
#Singleton
#Component(modules = {
ShipDocsDMSAccessorModule.class,
AWSS3UtilModule.class
})
public interface AccessorComponent {
ShipDocsDMS provideShipDocsDMSClient();
AWSS3Util provideAwss3Util();
}
and then in my main class
#Slf4j
#RequiredArgsConstructor
public class ShipDocsDMSAccessor {
private final ShipDocsDMS shipDocsDMSClient;
private final AWSS3Util awss3Util;
public ShipDocsDMSAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.shipDocsDMSClient = accessorComponent.provideShipDocsDMSClient();
this.awss3Util = accessorComponent.provideAwss3Util();
}
.
.
.
.
and then in my test, I can freely mock AWSS3Util dependency and carry ahead and force out the required response.

Sending XML message to JMS queue

am working with a project in which I am trying to call a Servlet that will push XML message to a JMS queue running in my local machine, using java code. You can find the actual Servlet code below, which actually sends the message to the queue.
import java.io.IOException;
import java.io.PrintWriter;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MessageSender
extends HttpServlet
{
private static final long serialVersionUID = 1L;
static PrintWriter out;
public static final String CNN_FACTORY = "jms/alert/connectionFactory";
public static final String QUEUE_NAME = "jms/alert/amlScreenQueue";
public static String currentQueueName;
public static String JMSConnectionFactory;
private QueueConnection qcon;
private QueueSession qsession;
private static QueueSender qsender;
private Queue queue;
private static ObjectMessage om;
private static MessageProducer messageProducer;
public MessageSender() {}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
String JMSQueueName = request.getParameter("JMSQueueName");
currentQueueName = JMSQueueName;
JMSConnectionFactory = request.getParameter("JMSConnectionFactory");
out = response.getWriter();
InitialContext ic = getInitialContext();
init(ic, JMSQueueName);
doPost(request, response);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void init(Context ctx, String queueName)
throws NamingException, JMSException
{
QueueConnectionFactory qconFactory = (QueueConnectionFactory)ctx.lookup(JMSConnectionFactory);
this.qcon = qconFactory.createQueueConnection();
this.qsession = this.qcon.createQueueSession(false, 1);
queue = ((Queue)ctx.lookup(queueName));
QueueConnection qcon = qconFactory.createQueueConnection();
qcon.start();
QueueSession qsession = qcon.createQueueSession(false, 1);
qsender = qsession.createSender(queue);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String textMessage = request.getParameter("textMessage");
try
{
TextMessage msg = qsession.createTextMessage(textMessage);
msg.setStringProperty("JMSXGroupID", "1");
msg.setIntProperty("JMSXGroupSeq", 1);
msg.setBooleanProperty("JMS_IBM_Last_Msg_In_Group", false);
qsender.send(msg);
out.println("Message sent to queue " + currentQueueName);
out.println("");
out.println(msg.getText());
}
catch (JMSException e)
{
e.printStackTrace();
out.println(e.getErrorCode());
try
{
qsender.close();
qcon.close();
}
catch (JMSException e) {
e.printStackTrace();
}
}
finally
{
try
{
qsender.close();
qcon.close();
}
catch (JMSException e) {
e.printStackTrace();
}
}
}
private static InitialContext getInitialContext() throws NamingException
{
return new InitialContext();
}
}
This is the java code that I am using to call the servlet,
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map.Entry;
public class SendMessage {
public static void main(String[] args) throws URISyntaxException{
String line;
StringBuffer buffer = new StringBuffer();
String data = null;
try
{
String filePath = "data/payload.xml";
File dataFile = new File(filePath);
if(dataFile.exists()){
data = new String(Files.readAllBytes(Paths.get(filePath)));
}else{
System.out.println("Not Available");
}
String localUrl = "http://localhost:8080/SimulationTool/MessageSender";
String params = "JMSQueueName=jms/alert/amlScreenQueue&"
+ "JMSConnectionFactory=jms/alert/connectionFactory&"
+ "textMessage=" + data;
System.out.println("PARAMS:::" + params);
URL url = new URL(localUrl);
System.out.println("URL FOUND:::" + url.toURI());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.connect();
System.out.println("Response Code:::" + ((HttpURLConnection)conn).getResponseCode());
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ));
out.write(params);
out.flush();
out.close();
// Response code
System.out.println("Response Code:::" + ((HttpURLConnection)conn).getResponseCode());
// Response values
for (Entry<String, List<String>> header : ((HttpURLConnection)conn).getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
String response;
while ( (response = in.readLine()) != null ) {
System.out.println( response );
}
in.close();
}
catch ( MalformedURLException ex ) {
ex.printStackTrace();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
The problem is its failing with below exception,
Response Code:::200
java.net.ProtocolException: Cannot write output after reading input.
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1312)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1291)
at servlettests.SendMessage.main(SendMessage.java:63)
Its shows response code as 200, so the connection was successful but it fails while getting the outputstream, which is being created to send message to the queue. Pls help me on resolving this issue.

Deploy a .bpmn file via REST

i want to deploy a BPMN-file with the REST-API of Activiti. But i always get a Bad Request (400) error...
Has anybody an idea what i'm doing wrong??? I use restlet to upload my code. My code is below.
Thank your very much :)
import java.io.File;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Disposition;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.FileRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
public class REST {
private static String REST_URI = "http://localhost:8080/activiti-rest/service";
private static ClientResource getClientResource(String uri) {
ClientResource resource = new ClientResource(uri);
resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "kermit", "kermit");
return resource;
}
public static JSONArray postDeployments() throws JSONException, IOException {
String deploymentURI = REST_URI + "/repository/deployments";
File file = new File("C:\\Users\\Test\\Desktop\\process.bpmn");
FileRepresentation fr = new FileRepresentation(file, MediaType.TEXT_PLAIN);
System.out.println("Size sent: " + fr.getSize());
try{
Representation response = getClientResource(deploymentURI).post(file, MediaType.MULTIPART_FORM_DATA);
JSONObject object = new JSONObject(response.getText());
if (object != null) {
JSONArray dataArray = (JSONArray) object.get("data");
return dataArray;
}
}
catch(Exception e){
System.out.println("Error:");
e.printStackTrace();
}
return null;
}
}
You are not generating the multipart-form-data request properly with Restlet.
You could have done the following to deploy a business process to activiti REST API:
String deploymentURI = REST_URI + "/repository/deployments";
File file = new File("/home/toto/fake-process.bpmn20.xml");
FileRepresentation entity = new FileRepresentation(file, MediaType.MULTIPART_FORM_DATA);
FormDataSet fds = new FormDataSet();
FormData fd = new FormData("upload_file", entity);
fds.getEntries().add(fd);
fds.setMultipart(true);
try {
Representation response = getClientResource(deploymentURI).post(fds);
} catch (Exception e) {
System.out.println("Error:");
e.printStackTrace();
}
See also this post

get XML from server by URL in AsyncTask and return response to UI

I try to get xml from server in async task, but my doInBackground method returns me NULL. Where is my mistake? And how I can send result to UI?
Here is all classes
I have this code for getting xml from server:
package classes;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created by Mikhail on 28.03.2015.
*/
public class GetXMLFromServer {
InputStreamReader reader;
public GetXMLFromServer(){
//reader = null;
}
public InputStreamReader getReaderWithXML(String url){
GetXMlTask task = new GetXMlTask();
task.execute(url);
return reader;
}
public void setReader(InputStreamReader newReader){
this.reader = newReader;
}
class GetXMlTask extends AsyncTask<String, Integer, InputStreamReader>{
#Override
protected InputStreamReader doInBackground(String... params) {
InputStreamReader iStream = null;
try {
iStream = new InputStreamReader(getUrlData(params[0]));
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return iStream;
}
#Override
protected void onPostExecute(InputStreamReader inputStreamReader) {
super.onPostExecute(inputStreamReader);
setReader(inputStreamReader);
}
public InputStream getUrlData(String urlString) throws URISyntaxException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(String.valueOf(new URL(urlString)));
HttpResponse res = client.execute(method);
StatusLine status = res.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d("APP", "HTTP error.Invalid server status code: " + res.getStatusLine());
}
return res.getEntity().getContent();
}
}
}
You have a good example how to use async task here.
Please check it!
The returning is in onPostExecute method.
To send the result to UI use OnPostExecute do call a static method of your UI class.
protected void onPostExecute(Long result) {
YourUIFragmentORActivity.showResult(result);
showDialog("Downloaded " + result + " bytes");
}

Execution stops automatically at getOutputStream() function Push notification using servlets

I have a problem while getting a push notification on the server side. I am using C2DM sever connection to achieve the push notification. Its working fine on android but not in the Java Servecr. I'm able to get the registration ID and authentication code but the handling stops when it comes to the line:
OutputStream out = conn.getOutputStream();
It does not throw anything, just stops.
If anyone has a solution for this then please guide me. I am adding the whole code so you can go through and tell me where I'm wrong in getting the result.
import org.apache.http.client.methods.HttpPost;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.print.DocFlavor.INPUT_STREAM;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Server {
private static String key=null;
// private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
private static String Authcode = null;
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "reg id";
public void getAuthentification() {
System.out.println("check");
//HttpPost post = new HttpPost("http://www.google.com/accounts/ClientLogin");
try {
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
System.out.println("getAuthentication method called****************************");
URL url=new URL("https://www.google.com/accounts/ClientLogin");
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
HttpURLConnection conn=(HttpURLConnection)connection;
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
StringBuilder content = new StringBuilder();
content.append("Email=").append("xyz#gmail.com");
content.append("&Passwd=").append("asdfgt");
content.append("&service=").append("ac2dm");
content.append("&source=").append("MY_APP-V0.1");
content.append("&accountType=").append("HOSTED_OR_GOOGLE");
OutputStream out = conn.getOutputStream();
out.write(content.toString().getBytes("UTF-8"));
out.close();
int res = conn.getResponseCode();
System.out.println(res + "Success");
StringBuffer resp = new StringBuffer();
if(res == HttpsURLConnection.HTTP_OK){
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
System.out.println("inside");
if (line.startsWith("Auth=")) {
Authcode = line.substring(5);
resp.append(line.substring(5));
System.out.println(line.substring(5));
System.out.println("something to be done here..");
}
}
rd.close();
}
}
}
public void sendMessage() {
try {
System.out.println(YOUR_REGISTRATION_STRING);
System.out.println("Authcode = " + Authcode);
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
URL url1 = new URL("https://android.apis.google.com/c2dm/send");
System.out.println("here2.5");
HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
System.out.println("here2.6");
conn1.setDoInput(true);
conn1.setDoOutput(true);
conn1.setUseCaches(false);
conn1.setRequestMethod("POST");
conn1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn1.setRequestProperty("Authorization", "GoogleLoginauth="+ Authcode);
System.out.println("here2.7");
OutputStream out = conn1.getOutputStream();
System.out.println("send Message method.");
String auth_key="n/a";
if(key!=null) {
auth_key=Authcode;
}
System.out.println("here");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID)
.append("=").append(YOUR_REGISTRATION_STRING);
System.out.println("here1");
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY)
.append("=").append("0");
System.out.println("here2");
postDataBuilder.append("&").append("data.payload")
.append("=").append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
conn1.setRequestProperty("Content-Length",
Integer.toString(postData.length));
// Hit the dm URL.
System.out.println("out created");
out.write(postData);
System.out.println("data written");
out.close();
System.out.println("here3");
int responseCode = conn1.getResponseCode();
System.out.println(String.valueOf(responseCode));
// Validate the response code
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
System.out.println("C2DM, Unauthorized - need token");
}
} catch (Exception ignore) {
// the editor that corrected the indentation of the code could not find any code here so he closed all methods to have a syntactically correct class.
}
}
}
Make sure that you are posting message to url from background thread not from the UI thread.
I hope after this change it will work. Good Luck!!!

Categories