Handle http post request - http

I have the following scenario to implement:
I have an ASP.NET Web site. On a click of a button in my site the user is redirected to a 3rd party site. When the user does some actions in this 3rd party site, the site starts sending http post requests to my site with a special message every 1 minute.
Now, the problem is that I should handle and process these requests, but I do not know how to do it. Please note that the requests that are sent from the 3rd party site DO NOT open my site by the http post requests. These requests are some kind of background requests, i.e. they do not open a page directly, so they should be handled using another approach.
I have the solution in Java. It is called Servlet. By the help of the servlet I can do the thing that I want in Java. However, I need the same functionality in ASP.NET? Does anybody have a solution for this?
Thanks a lot!
P.S. Just for your reference, here is the Java code for the servlet:
package payment;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.action.PaymentBean;
public class EPayRequestCatcher extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet{
static final long serialVersionUID = 1L;
public EPayRequestCatcher() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
String encoded = request.getParameter("encoded");
PaymentUtil util = new PaymentUtil();
if (encoded != null) {
String decoded = util.getDecodedB64Data(encoded);
int invStart = decoded.indexOf("=") + 1;
int invEnd = decoded.indexOf(":", invStart);
String invoice = decoded.substring(invStart, invEnd);
System.out.println("" + invoice);
String checksum = request.getParameter("checksum");
PaymentBean bean = new PaymentBean();
String responseStatus = bean.getEpayRequest(encoded, checksum);
if (!responseStatus.equals("")) {
String responseData = "INVOICE=" + invoice + ":STATUS=" + responseStatus + "\n";
System.out.println(responseData);
response.getWriter().append(responseData);
}
}
else {
return;
}
}
}

TheVisitor,
if I understood well, an external website will POST some data to your ASP.NET website; you'll (probably) define a page to receive that post and don't know how to handle it, right?
Well, you can try something like:
protected void Page_Load(object sender, EventArgs e)
{
string encoded = Request["encoded"];
string checksum = Request["checksum"];
// do stuff
Response.Write("some response");
}
This could be enough, depending on you requirements.
HTH

Related

Servlet Response wrapper to add getHeaderNames and getHeaders methods to Servet 2.4 spec container not working

Since Servlet 3.0, HttpServletResponse#getHeaderNames() and HttpServletResponse#getHeaders() has been available. However, I'm using an older spec, specifically Servlet 2.4.
Having looked at the resource, How can I get the HTTP status code out of a ServletResponse in a ServletFilter?, I got an idea of how to write a wrapper. If I understand it right, I have to use setHeader() to facilitate the creation of getHeaderNames() and getHeaders(). I think I have a solid footing on how to store the headers to simulate the usage of these missing methods.
The problem is the filter which leverages this wrapper does not seem to be calling setHeader() automatically. I don't get it. I presume sincegetStatus() is working properly, I'm expecting setHeader() to behave in the same fashion. Specifically, I'm looking to print out all the response headers, after calling chain.doFilter(). I'm not sure what I'm doing wrong here. Maybe there is something wrong with how I'm storing header name-value pairs.
I would appreciate any help. Thank you.
public class ServletResponseWrapper extends HttpServletResponseWrapper {
private int httpStatus = SC_OK;
private HashMap<String, String> hashMapHeaders = new HashMap<String, String>();
public ServletResponseWrapper(HttpServletResponse response) {
super(response);
}
#Override
public void sendError(int sc) throws IOException {
httpStatus = sc;
super.sendError(sc);
}
#Override
public void sendError(int sc, String msg) throws IOException {
httpStatus = sc;
super.sendError(sc, msg);
}
#Override
public void setStatus(int sc) {
httpStatus = sc;
super.setStatus(sc);
}
public int getStatus() {
return httpStatus;
}
#Override
public void sendRedirect(String location) throws IOException {
httpStatus = SC_MOVED_TEMPORARILY;
super.sendRedirect(location);
}
#Override
public void setHeader(String name, String value) {
hashMapHeaders.put(name, value);
super.setHeader(name, value);
}
public String getHeader(String name) {
return hashMapHeaders.get(name);
}
public Enumeration<String> getHeaderNames() {
Enumeration<String> enumerationHeaderNames = Collections.enumeration(hashMapHeaders.keySet());
return enumerationHeaderNames;
}
}
public class ServletResponseWrapperFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletResponseWrapper servletResponseWrapper = new ServletResponseWrapper( (HttpServletResponse) response );
chain.doFilter( request, servletResponseWrapper );
// Process response
// This works, even though I never explicitly call the setStatus() method
int status = response.getStatus();
// This returns NULL because no header values get set; I presume setHeader() gets called implicitly
Enumeration<String> headerNames = servletResponseWrapper.getHeaderNames();
}
public void init(FilterConfig config) throws ServletException {
//empty
}
public void destroy() {
// empty
}
}
web.xml file
<display-name>Tomcat App</display-name>
<filter>
<filter-name>ResponseHeadersFilter</filter-name>
<filter-class>com.company.filters.ResponseHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ResponseHeadersFilter</filter-name>
<url-pattern>/testfilter.jsp</url-pattern>
</filter-mapping>
I took the vendor's servlet out of the equation. The filter now fires on an empty JSP file. Tomcat is also hooked to a front-end web server, IIS. I disabled IIS. Now, I'm accessing the website directly over Tomcat, via port 8080. Despite all this, I dot see any response headers.
Using Fiddler, the response headers I see are few but existing, namely:
(Cache) Date
(Entity) Content- Length, Content-Type
(Miscellaneous) Server
And status response, i.e. HTTP/1.1 200 OK
I can get by without getting response headers in the filter. But the big question I have is this is a bug with Servlet version 2.4 or is there some kind of OS Server and/or Tomcat configuration change I need to enable? Unless there's some Tomcat configuration, I'm led to believe this is likely a bug. Perhaps a clean install using the default configuration of the Tomcat version I'm using, 5.5.28, would resolve the problem, but I cannot attempt that at this time.

Servlet shows blank page when using println in method other than doGet or doPost

My dynamic web app is showing a blank page when using println in a method other than doGet or doPost. The default page loads fine. On it is a form that has an input that's passed to the startup servlet's doPost, and then it's request, response gets passed to a second servlet's doPost. Then the same request, response gets passed to an output method than uses println to display the output. But I'm getting a blank page instead of the output. I know that the output method gets called because I was getting an error with it when I initially tried using a BufferedWriter to write to an output file, but that wasn't working. This is my first attempt at a Java EE dynamic web app and using println, although I have intermediate experience with PHP, ASP.Net and several languages in desktop apps.
The second servlet's doPost method calls the methods of readnums, sort, and outputSort. The readnums method reads a text file for the program to use. I'm having problems with relative paths (that's why I couldn't get the BufferedWriter to work in outputSort, I suppose). The path I'm using for the input text file is "/WebContent/WEB-INFO/myfile.txt". Will I have a problem with this once the web app is deployed with a hosting site? At the risk of asking 2 questions in one, how do you correctly specify relative paths to the app? I've Googled and Googled but can't seem to find a working solution. When I try to use getServletContext().getRealPath() I get an error in the outputSort method at that line. I didn't try to use it in the readnums method yet. I've got a website that I can hotlink to for the input files if that is a viable alternative. How would you do that?
Any help with this would be greatly appreciated. Thanks in advance.
Initial servlet called from the default jsp:
package com.LAEWeb;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Startup extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF/Startup.jsp").forward(req,resp);
}
#Override
public void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
String sorts = req.getParameter("sorts");
String action = req.getParameter("action");
if ("Powerball".equals(action)) {
Powerball p = new Powerball();
p.sortInputText = sorts;
p.doPost (req, resp);
}
else if ("Mega Millions".equals(action)) {
// Invoke SecondServlet's job here.
}
}
}
The second servlet's methods (I didn't list readnums and sort for brevity):
#Override
public void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
if (PB_operation == "sorts") {
readnums();
if (!errorMessage.isEmpty()) {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
try {
out.println("<html>");
out.println("<body>");
out.println("<h2>Input file not found</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
return;
}
else {
sort();
outputSort(req, resp);
}
}
}
void outputSort (HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
String Temp;
int i;
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println ("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>LAEWeb</title>");
out.println("</head>");
out.println("<body>");
out.println("Return to previous page ");
out.println("<h2>The Powerball sorted totals for the range selected</h2>");
out.println("<pre>");
out.println("Rank Numbers Totals Power ball Totals");
out.println ("");
out.println ("");
for (i = 1; i <= NUMLIMIT; i++) {
Temp = "<p>" + Integer.toString(i) + " ";
if (i < 10)
Temp += " ";
Temp += Integer.toString(sortnums[i][1]) + " ";
Temp += Integer.toString(sortnums[i][2]) + " ";
if (i <= XLIMIT) {
Temp += Integer.toString(sortxball[i][1]) + " ";
Temp += Integer.toString(sortxball[i][2]) + " ";
}
out.println (Temp);
}
out.println("</pre>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
If you want to get real path of a relative path you can use getRealPath() method, for example:
String realPath = getServletContext().getRealPath("/WEB-INFO/myfile.txt");
If you're using this code in init() method of your servlet, use:
config.getServletContext().getRealPath("/WEB-INFO/myfile.txt");
To answer first part of your question, I need more information about it. I'll edit this answer after getting information.
I used getServletContext().getRealPath() in the first servlet and passed the path to the second servlet through a class variable in the second servlet. That worked. Thanks for your help Ali for pointing me in the right direction. I guess since the second servlet is not actually initializing normally (I'm just calling it's doPost from the first servlet) the context for it is null. Thanks again for the help!

Async Servlet - preferred implementation

Lately, during my research about asynchronous processing in Servlets, I came across at at least three ways to implement
some functionality using this approach.
The questions are:
Which one is the best?
Maybe some of these approaches are not recommended?
Maybe there is another one approach better than all of mentioned below?
Found approaches:
Using AsyncContext.start(Runnable).
This approach is quite simple and straightforward. But many serwers executes such a job in thread pool created for HTTP requests
(more about it here http://www.nurkiewicz.com/2012/05/javaxservletservletrequeststartasync.html)
Using custom threads pool created during Servlet context initialization
(sample here: http://www.journaldev.com/2008/async-servlet-feature-of-servlet-3).
But can I create my own threads in Servlet container? It was not recommended (or even prohibited) in EJB (before JavaEE7).
Can I use JavaSE Executors or should I use ManagedExecutors from JavaEE7 (assuming that I use JavaEE7)?
Using EJB and #Asynchronious annotation
(example here: https://github.com/wildfly/quickstart/tree/master/servlet-async/src/main/java/org/jboss/as/quickstarts/servlet/async).
But here I have no control over threads executing my task (i.e. how many thread should by created etc.)
I would by glad to hear your thoughts on this issue and your experience with AsyncContext.
All will have the same performance, at the backend all threads are replacing the request processing thread to another thread, so that more requests can be served.
Below you'll find a simple implementation:
#WebServlet(urlPatterns = "/AsyncLongRunningServlet", asyncSupported = true)
public class AsyncLongRunningServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Request Processing Thread "+Thread.currentThread().getName());
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
response.setContentType("text/html");
PrintWriter printWriter=response.getWriter();
printWriter.println("<html><head><title>Asynchronous servlet</title></head><body>");
printWriter.println("Request Processing Thread "+Thread.currentThread().getName());
printWriter.println("<br>");
printWriter.println("<progress id='progress' max='100')></progress>");
printWriter.println("<br>");
AsyncContext asyncCtx = request.startAsync();
asyncCtx.addListener(new AppAsyncListener());
asyncCtx.setTimeout(12000);
//release of request processing thread
asyncCtx.start(() ->{
printWriter.println("<br>");
printWriter.println("Async thread Name "+Thread.currentThread().getName());
printWriter.println("<br>");
int i=0;
while(i<100)
{
printWriter.println("<script>document.getElementById('progress').value=\""+i+"\";</script>");
printWriter.flush();
try {
Thread.sleep(100);
} catch (Exception e) {
}
i++;
}
printWriter.println("</body></html>");
asyncCtx.complete();
}
);
printWriter.println("<br>");
printWriter.println("End of response");
}
}
package com.journaldev.servlet.async;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebListener;
#WebListener
public class AppAsyncListener implements AsyncListener {
#Override
public void onComplete(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onComplete");
// we can do resource cleanup activity here
}
#Override
public void onError(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onError");
//we can return error response to client
}
#Override
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onStartAsync");
//we can log the event here
}
#Override
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
System.out.println("AppAsyncListener onTimeout");
//we can send appropriate response to client
ServletResponse response = asyncEvent.getAsyncContext().getResponse();
PrintWriter out = response.getWriter();
out.write("TimeOut Error in Processing");
}
}

PlayN.Net returning empty String in HTML

I can't understand the problem im having with PlayN.net. Maybe it's trivial, but since im new to web based stuff, I'm kinda stuck, so I hope someone here can enlighten me :)
My problem: I would like to acess a servlet from my game, it works, but only in java. Html gives me back an empty string.
Simple Servlet:
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter writer = response.getWriter();
writer.println("test");
writer.close();
}
}
and simple call:
PlayN.net().get("http://localhost:8080/Test", new Callback<String>() {
#Override
public void onSuccess(String result) {
System.out.println("YAY "+result);
}
#Override
public void onFailure(Throwable cause) {
System.out.println("BUH");
}
});
So like I said, java prints "YAY test", HTML prints "YAY" and I cannot figure out why.
I tried running the servlet on an other server (not localhost) but the same reaction.
Anyone an idea what I'm doing wrong?
In the browser (HTML) you have to work with the 'Same origin policy': See http://en.wikipedia.org/wiki/Same_origin_policy
Suggested solutions and work-arounds:
Collaboration from PlayN client with server
Why net().get on success return empty string

Why Java servlet can't get Paypal IPN messages everytime?

I have a Java servlet running on my notebook with Windows Vista, I set up a static IP, did port forwarding and registered for a free DDNS service, now my servlet is running, I gave the url to Paypal to send me IPN messages, I went on to it's sandbox site got to the test tools page, tried to send test messages by clicking the "Send IPN" button, most of the time it would fail, the error is : "IPN delivery failed. Unable to connect to the specified URL. Please verify the URL and try again."
But maybe 1 in 10 times, it might be successful and my servlet would get the message, and I looked at the messages I got, they are in correct format. So I called Paypal asking why, he said I shouldn't run the servlet on my notebook, in stead I should run it on the web server, but I told him my ISP doesn't support Java on their server, and since I did all the above steps, shouldn't it be the same to run the servlet on my notebook ? He said his test showed he couldn't get to my servlet, but I asked why maybe 1 in 10 times it could get through ? If there is something wrong with running it on my notebook, then 100% times it should fail, am I correct on this point ? But anyway he said that's all he could do, and I should troubleshoot it myself. The servlet looks like this :
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class PayPal_Servlet extends HttpServlet
{
static boolean Debug=true;
static String PayPal_Url="https://www.paypal.com/cgi-bin/webscr",Sandbox_Url="https://www.sandbox.paypal.com/cgi-bin/webscr",
Dir_License_Messages="C:/Dir_License_Messages/";
static TransparencyExample Transparency_Example;
static PayPal_Message_To_License_File_Worker PayPal_message_to_license_file_worker;
// Initializes the servlet.
public void init(ServletConfig config) throws ServletException
{
super.init(config);
if (!new File(Dir_License_Messages).exists()) new File(Dir_License_Messages).mkdirs();
System.gc();
}
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
// Read post from PayPal system and add 'cmd'
Enumeration en=request.getParameterNames();
String str="cmd=_notify-validate";
while (en.hasMoreElements())
{
String paramName=(String)en.nextElement();
String paramValue=request.getParameter(paramName);
str=str+"&"+paramName+"="+URLEncoder.encode(paramValue);
}
// Post back to PayPal system to validate
// NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
// using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE) and configured for older versions.
URL u=new URL(Debug?Sandbox_Url:PayPal_Url);
URLConnection uc=u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw=new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in=new BufferedReader(new InputStreamReader(uc.getInputStream()));
String res=in.readLine();
in.close();
// Assign posted variables to local variables
String itemName=request.getParameter("item_name");
String itemNumber=request.getParameter("item_number");
String paymentStatus=request.getParameter("payment_status");
String paymentAmount=request.getParameter("mc_gross");
String paymentCurrency=request.getParameter("mc_currency");
String txnId=request.getParameter("txn_id");
String receiverEmail=request.getParameter("receiver_email");
String payerEmail=request.getParameter("payer_email");
if (res.equals("VERIFIED")) // Check notification validation
{
// check that paymentStatus=Completed
// check that txnId has not been previously processed
// check that receiverEmail is your Primary PayPal email
// check that paymentAmount/paymentCurrency are correct
// process payment
}
else if (res.equals("INVALID")) // Log for investigation
{
}
else // Log for error
{
}
// ===========================================================================
if (txnId!=null)
{
Write_File_Safe_Fast(Dir_License_Messages+txnId+".txt",new StringBuffer(str.replace("&","\n")),false);
}
// ===========================================================================
String Message_File_List[]=Tool_Lib.Get_File_List_From_Dir(Dir_License_Messages);
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String title="Reading All Request Parameters",Name="",Value;
out.println("<Html><Head><Title>"+title+"</Title></Head>\n<Body Bgcolor=\"#FDF5E6\">\n<H1 Align=Center>"+title+"</H1>\n"+
"<Table Border=1 Align=Center>\n"+"<Tr Bgcolor=\"#FFAD00\"><Th>Parameter Name</Th><Th>Parameter Value(s) Messages = "+Message_File_List.length+"</Th></Tr>");
Enumeration paramNames=request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName=(String)paramNames.nextElement();
out.print("<Tr><Td>"+paramName+"</Td><Td>");
String[] paramValues=request.getParameterValues(paramName);
if (paramValues.length == 1)
{
String paramValue=paramValues[0];
if (paramValue.length() == 0) out.print("<I>No Value</I>");
else
{
out.println(paramValue+"</Td></Tr>");
// Out("paramName = "+paramName+" paramValue = "+paramValue);
// if (paramName.startsWith("Name")) Name=paramValue;
// else if (paramName.startsWith("Value")) Write_File_Safe_Fast("C:/Dir_Data/"+Name,new StringBuffer(paramValue),false);
}
}
else
{
out.println("<Ul>");
for (int i=0;i<paramValues.length;i++) out.println("<Li>"+paramValues[i]);
out.println("</Ul></Td</Tr>");
}
}
out.println("</Table>\n</Body></Html>");
}
/** Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { processRequest(request,response); }
/** Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { processRequest(request,response); }
// Returns a short description of the servlet.
public String getServletInfo() { return "Short description"; }
// Destroys the servlet.
public void destroy() { System.gc(); }
public static void Write_File_Safe_Fast(String File_Path,StringBuffer Str_Buf,boolean Append)
{
FileOutputStream fos=null;
BufferedOutputStream bos=null;
try
{
fos=new FileOutputStream(File_Path,Append);
bos=new BufferedOutputStream(fos);
for (int j=0;j<Str_Buf.length();j++) bos.write(Str_Buf.charAt(j));
}
catch (Exception e) { e.printStackTrace(); }
finally
{
try
{
if (bos!=null)
{
bos.close();
bos=null;
}
if (fos!=null)
{
fos.close();
fos=null;
}
}
catch (Exception ex) { ex.printStackTrace(); }
}
System.gc();
}
}
I use Netbean6.7 to develop the servlet, and the code was from Paypal's JSP sample code, what can I do to debug the problem ?
HI, try to use my library:
http://paypal-nvp.sourceforge.net/index.htm
I hope it will help you. If you have any questions, improvements you can contact me. You find my email in the comments of the source.

Resources