Access to http request body raw data - java

I am trying to implement a web application using play framework as a replacement for old http server implementation that is interfacing the old non-browser legacy http client.
That client is written in Delphi and it is posting data directly in the body of a request with some header information about it.
I thought I would get something in
request.body /* In the play controller */
but nothing is there.
See the code below:
public static void uploadPicture() {
InputStream data = request.body;
String fx = Play.getFile("").getAbsolutePath()+File.separator+"uploads"+File.separator+"test.jpg";
File f = new File(fx);
FileOutputStream moveTo = new FileOutputStream(fx);
try {
byte[] b = new byte[4096];
for (int x = 0; (data.read(b)) != -1;){
moveTo.write(b, 0, x);
}
} finally{
moveTo.close();
}
}
EDIT:
To clarify my point : I went and I created a simple Dynamic Web Project in eclipse HttpServlet and in doPost() method when I get the request.getInputStream() it contains the file that is sent from the legacy client.
Play is doing something to the body of the request!?
What are my options?
Thanks.
Irfan

Ok, it was a bug in Play 1.2.4. I installed latest version 1.2.5 and everything works out of the box.
You can access raw body of a request in request.body in the controller.

Related

Code position of keystore and truststore in java servlet

I'm working with an organization's payment API. The API automatically posts a soap request to our server when a customer makes payment and I response with an acknowledgement message in xml. (Check out the screenshots show a simple demonstration in SOAP UI)
SOAP UI Test Response
SOAP UI Test Raw XML
I made this code in Java to receive the soap request and send a response.
`public class testsoap extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/xml;charset=UTF-8");
ServletInputStream out = request.getInputStream();
String xmlrpc = "";
int c = 0;
while((c = out.read()) != -1 ){ xmlrpc += (char)c; }
int startTag = xmlrpc.indexOf("<TransID>");
int endTag = xmlrpc.indexOf("</TransID>");
String parameter = xmlrpc.substring(startTag,endTag).replaceAll("<TransID>","");
String result="";
//result +="<?xml version=\"1.0\"?>\n";
result +="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:c2b=\"http://cps.huawei.com/cpsinterface/c2bpayment\">\n";
result +="<soapenv:Header/>\n";
result +="<soapenv:Body>\n";
result +="<c2b:C2BPaymentConfirmationResult>C2B Payment Transaction "+parameter+" result received.</c2b:C2BPaymentConfirmationResult>\n";
result +="</soapenv:Body>\n";
result +="</soapenv:Envelope>\n";
response.getWriter().println(result);
}
}`
Now I need to add the location of my keystore and truststore.
Should I add this code just before I start preparing a response?
` System.setProperty("javax.net.ssl.keyStore",path_to_keystore);
System.setProperty("javax.net.ssl.keyStorePassword",akeystorepassword);
System.setProperty("javax.net.ssl.trustStore",path_to_your_cacerts_file);
System.setProperty("javax.net.ssl.trustStorePassword",atrustsorepassword)`
Or do I need to make a snippet that makes secure connection using the keystore and truststore rather than just setting a system property?
Create a Java class and write all the functionalities that you need to publish as a methods. Then you need to publish those functionalities as a WSDL to be consumed by your clients. See the following tutorial that will take you in step by step to publish a web services:
Step by Step JAX-WS Web Services with Eclipse, TomEE, and Apache CXF
Building a Simple Web Service ? A Tutorial
Implementing a simple web service
Further based on your requirements you can have complex object as an input parameter like C2BPaumentConfirmationRequest and KYCInfo in your case

How to stream url from .pls file with java?

I want to stream a radio with Java, my approach is to download the playlist file (.pls), then extract one of the urls given in that same file and finally, stream it with java. However, it seems I cannot find a way to do it.. I tried with JMF, but I get java.io.IOException: Invalid Http response everytime I run the code.
Here is what I tried:
Player player = Manager.createPlayer(new URL("http://50.7.98.106:8398"));
player.start();
The .pls file:
[playlist]
NumberOfEntries=1
File1=http://50.7.98.106:8398/
In the piece of code above I'm setting the URL by hand, just for testing, but I've sucessfuly done the .pls downloading code and it's working, and from this I make another question, is it a better approach to just simply play the .pls file locally? Can it be done?
You are connecting to an Icecast server, not a web server. That address/port is not sending back HTTP responses, it's sending back Icecast responses.
The HTTP specification states that the response line must start with the HTTP version of the response. Icecast responses don't do that, so they are not valid HTTP responses.
I don't know anything about implementing an Icecast client, but I suspect such clients interpret an http: URL in a .pls file as being just a host and port specification, rather than a true HTTP URL.
You can't use the URL class to download your stream, because it (rightly) rejects invalid HTTP responses, so you'll need to read the data yourself. Fortunately, that part is fairly easy:
Socket connection = new Socket("50.7.98.106", 8398);
String request = "GET / HTTP/1.1\n\n";
OutputStream out = connection.getOutputStream();
out.write(request.getBytes(StandardCharsets.US_ASCII));
out.flush();
InputStream response = connection.getInputStream();
// Skip headers until we read a blank line.
int lineLength;
do {
lineLength = 0;
for (int b = response.read();
b >= 0 && b != '\n';
b = response.read()) {
lineLength++;
}
} while (lineLength > 0);
// rest of stream is audio data.
// ...
You still will need to find something to play the audio. Java Sound can't play MP3s (without a plugin). JMF and JavaFX require a URL, not just an InputStream.
I see a lot of recommendations on Stack Overflow for JLayer, whose Player class accepts an InputStream. Using that, the rest of the code is:
Player player = new Player(response);
player.play();

open website code in java as illusion of web browser

I want to open a website in web browser. I know it is easy but i want to do it in different way ...
It is like proxy server .I have made a java code that will get content(source code) of webpage and when browser request localhost on particular port number this code writes source code in browser. But instead of getting web page I am getting source code of webpage in browser and also i want to make a request from java code as a illusion of browser means server should feel that that request is made from a browser and not from java console.
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String args[]) throws Exception{
URL ul = null;
HttpURLConnection ulc = null;
ServerSocket server = null;
Socket client = null;
DataInputStream in = null;
DataOutputStream out = null;
String c = null;
server = new ServerSocket(9898);
System.out.println("Server is waiting for clients on port no 9898....");
while(client == null){
client = server.accept();
}
System.out.println("Connected.....");
out = new DataOutputStream(client.getOutputStream());
ul = new URL("http://www.google.com");
ulc = (HttpURLConnection)ul.openConnection();
in = new DataInputStream(ulc.getInputStream());
while((c = in.readLine())!=null){
out.writeBytes(c);
}
in.close();
out.close();
client.close();
}
}
Loading web pages is not quite as simple as you probably think. Both the browser and the server use a protocol called HTTP. In simple terms, the browser sends a request consisting of a request line, headers and sometimes data, and the server responds with a response line, headers and data. Most web pages also have related resources that need to be loaded for displaying the page (such as images, stylesheets and scripts), and each resource is loaded through a separate request.
Your program only accepts one request, completely ignores the details of the request, and then loads a fixed web page and sends it as the response. The way you are loading the web page (with a URL), you are only getting the data part of the response (the page source); the response line and the headers are missing. The headers are very important as one of them (named "Content-Type") specifies what kind of resource it is - web page, image or something else. Without it, browsers usually assume the data is plain text and display it accordingly.
So if you want your experiment to work better, you need to make sure you send a complete and valid HTTP response to the browser. You can probably reconstruct the response line and headers from the HttpURLConnection object. Or you can use sockets directly to load the web page.
A better solution would be to use a java web server (such as Jetty) in which you'd run a servlet that loads the remote page using an HTTP client library (such as Apache HttpComponents) and does the necessary processing of addresses and headers. But.. small steps :)

Getting raw XML response from Java web service client

I am trying to get the raw XML response from a web service, instead of the usual set of POJOs.
I am using a webservice client that I generated (so I have access to the client's code) from a WSDL and some schemas. The client is generated in RAD 7.5, I think using JAX-WS. I've been looking at the client code itself, but I'm not even sure if the client code ever handles raw XML or if it passes it off to other libraries.
You can do it using
javax.xml.ws.handler.soap.SOAPHandler<javax.xml.ws.handler.soap.SOAPMessageContext>
you can simply get message using SOAPMessageContext#getMessage() and convert message to String using method
public static String getXmlMessage(SOAPMessage message) throws Exception
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
message.writeTo(os);
final String encoding = (String) message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
if (encoding == null)
{
return new String(os.toByteArray());
}
else
{
return new String(os.toByteArray(), encoding);
}
}
Also you can read here about SOAP handler on client side
Article
It's not widely documented, but you can use the Dispatch interface to implement JAXWS clients which work directly w/ the XML. Here and here are some articles for getting started.

how to write a file object on server response and without saving file on server?

I am using Spring with DWR . I want to return a file object as response , however I save the file (to be sent) at server temporary location and then send its location as href for anchor tag on client side , however I wonder if there could be a way to throw the file directly to browser on response object without saving it temporarily on server.
I expected if there could be a way to send file as a response via DWR.
public ModelAndView writeFileContentInResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
FileInputStream inputStream = new FileInputStream("FileInputStreamDemo.java"); //read the file
response.setHeader("Content-Disposition","attachment; filename=test.txt");
try {
int c;
while ((c = inputStream.read()) != -1) {
response.getWriter().write(c);
}
} finally {
if (inputStream != null)
inputStream.close();
response.getWriter().close();
}
}
It has been years since I've used Spring, and I'm unfamiliar with DWR, but the essence of your question is basic to the web.
The answer is yes, you can. In effect, you need to set the HTTP header Content-Disposition: attachment, then stream down the contents. All of this will be in the response to the original request (as opposed to sending back a link).
The actual code to achieve this will depend on your circumstances, but this should get you started.
you call the method from Java Script, right? I didn't really understand how Spring is related in this flow, but as far as I know DWR allows you to produce Java Script Stubs and call the Java methods of the exposed bean directly on server right from your java script client code.
You can read the file byte-by-byte and return it from your java method as long as it really returns a byte array.
However what would you do with this byte array on client?
I just think in this specific flow you shouldn't use the DWR but rather issue an ordinar AJAX request (if DWR can wrap it somehow for convenience - great). This request shouldn't come to DWRServlet, but rather be proceeded by a regular servlet/some web-based framework, like Spring MVC :)
Once the request comes to the servlet, use
response.setHeader("Content-Disposition","attachment; filename=test.txt");
as was already stated.
Hope this helps,
Good luck!
Mark
An example which return a excel to download from client:
//Java side:
public FileTransfer getExcel(Parametros param){
byte[] result = <here get data>;
InputStream myInputStream = new ByteArrayInputStream(result);
String excelFormat = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
FileTransfer dwrExcelFile = new FileTransfer("excel.xlsx", excelFormat, myInputStream);
return dwrExcelFile;
}
//Javascript side:
function downloadExcelFile() {
dwr.engine.setTimeout(59000);
var params = <params_to_send>;
<Java_class>.getExcel(params, {callback:function(dataFromServer) {
downloadExcelCallback(dataFromServer);
}});
}
function downloadExcelCallback(data) {
dwr.engine.openInDownload(data);
}

Categories

Resources