Search Results

Search found 194 results on 8 pages for 'httpservletresponse'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • HttpServletResponse XML to Java

    - by Mike
    I am maintaining this servlet that has a HttpServletResponse response that replies back to the client an XML message. I want to take the XML message and convert it to JSON, then send the JSON back. I want to avoid writing my own JSON converter if possible. Does anyone have a good method of doing this? I googled for this: http://pvoss.wordpress.com/2009/02/26/servlet-filter-to-convert-xml-to-json/ , which is exactly what I want but they are using a hacked dom4j jar which doesn't help me.

    Read the article

  • HttpServletResponse encoding problem @ WebSphere 6.1

    - by user295509
    My application is working fine with JBOSS 4.2.2 application server. However when I deploy same application at WebSphere 6.1. I get HttpServletResponse encoding problem. I am getting response on web browser as shown below:- ??][s?8?~N??0?uRY?d;?H?e??e??d6?%??A"yH????????M??x?? ??&A??h??ntCT???????UM??BW???H?T?4???????t??G?f =l?&5[?j?B{???6???V???6???7???????(???5?4????.?!????j??i?V????? X?Q??^<??????????sK????h?{y1?] [??T??- ?Dm?_?7????P??<*??VvQ?:6?KCc? 6?]????V_?zPC?c???Ÿ???zsW????_y?*???2? ??)?r?~?L%^?M???kzduY??BW4? ?.?????V????{??O????/?l?ii8?S?Q?cJ?56GAogp?w???7'??9vf???E?,??? 9?q?x???z?H????????;????4?? ?5?????iWF??l????o^??Fy?|?d???????zMa,????y??e \<?J???M?:miz????z?Z5???????^/???e?:?j7??'??~?@?V?V???nN?&??Q%}(??????*u???#???S?BO??Lð????+??x?8?/?E??????6_k?1)?@q. ?S%??5?=?$?CSBt?c ????+hX??2?>t?s?+?M????????nv$??13m??? I would like to mentioned that this encoding problem is not arise when I have less data (or HTML element). Means even at WebSphere, It is working fine when there are up to approximately 300 HTML element are render. When HTML elements over than certain number then web page is shown with encoded form. Moreover at Jboss 4.2.2 application is working fine up to long -long html element. I set content type as: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> This issue is reproducible at FF 3.6 and IE 7 and 8 browser. Can anyone help me out? Am I missing some setting?

    Read the article

  • Mimic an HTTPRequest and HTTPResponse object in Java

    - by Ankur
    How do I mimic an HTTPServletRequest and HTTPServletResponse object. The reason is I want to test the behaviour of some servlets. I know JUnit probably provides this functionality but I don't know how to use it (I will learn soon) and need to do this reasonably quickly. HTTPServletRequest and HTTPServletResponse are both interfaces so they can't be instantiated. There is a HttpServletRequestWrapper which implements HttpServletRequest but it doesn't seem to have any setParameter() type methods and HttpServletResponse doesn't seem to have any implementing classes at all. How can I test my code by passing a suitable HttpServletRequest object and then checking that the received HttpServletResponse object matches what I expect?

    Read the article

  • communication between remote servlets

    - by Venkatesh
    I have two web applications say App1 and App2. I want to call a servlet which is in App2 from a servlet in App1. I'm using URLConnection for this. I'm able to pass parameters to the servlet in App2 also and I'm also able to receive response from the servlet as string. But I want to send java objects from the servlet in App2 and receive them in servlet of App1. How to achieve this?

    Read the article

  • How to Upload a file from client to server using OFBIZ?

    - by SIVAKUMAR.J
    I'm new to ofbiz so try to keep your answer as simple as possibly. If you can give examples that would be kind. My problem is I created a project inside the ofbiz/hot-deploy folder namely productionmgntSystem. Inside the folder ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem I created a file app_details_1.ftl. The following are the code of this file <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT"> function uploadFile() { //alert("Before calling upload.jsp"); window.location='<@ofbizUrl>testing_service1</@ofbizUrl>' } </script> </head> <!-- <form action="<@ofbizUrl>testing_service1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> --> <form action="<@ofbizUrl>logout1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> <center style="height: 299px; "> <table border="0" style="height: 177px; width: 788px"> <tr style="height: 115px; "> <td style="width: 103px; "> <td style="width: 413px; "><h1>APPLICATION DETAILS</h1> <td style="width: 55px; "> </tr> <tr> <td style="width: 125px; ">Application name : </td> <td> <input name="app_name_txt" id="txt_1" value=" " /> </td> </tr> <tr> <td style="width: 125px; ">Excell sheet &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </td> <td> <input type="file" name="filename"/> </td> </tr> <tr> <td> <!-- <input type="button" name="logout1_cmd" value="Logout" onclick="logout1()"/> --> <input type="submit" name="logout_cmd" value="logout"/> </td> <td> <!-- <input type="submit" name="upload_cmd" value="Submit" /> --> <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/> </td> </tr> </table> </center> </form> </html> the following coding is present in the file ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem\WEB-INF\controller.xml ...... ....... ........ <request-map uri="testing_service1"> <security https="true" auth="true"/> <event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.WebServices1" invoke="testingService"/> <response name="ok" type="view" value="ok_view"/> <response name="exception" type="view" value="exception_view"/> </request-map> .......... ............ .......... <view-map name="ok_view" type="ftl" page="ok_view.ftl"/> <view-map name="exception_view" type="ftl" page="exception_view.ftl"/> ................ ............. ............. The following are the coding present in the file ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req\WebServices1.java package org.ofbiz.productionmgntSystem.web_app_req; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; public class WebServices1 { public static String testingService(HttpServletRequest request, HttpServletResponse response) { //int i=0; String result="ok"; System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- Start"); String contentType=request.getContentType(); System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- contentType : "+contentType); String str=new String(); // response.setContentType("text/html"); //PrintWriter writer; if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) after if (contentType != null)"); try { // writer=response.getWriter(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try Start"); DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //this loop converting the uploaded file into byte code while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); //for saving the file name String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; //extracting the index of file pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; //creating a new file with the same name and writing the content in new file FileOutputStream fileOut = new FileOutputStream("/"+saveFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try End"); } catch(IOException ioe) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch IOException"); //ioe.printStackTrace(); return("exception"); } catch(Exception ex) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch Exception"); return("exception"); } } else { System.out.println("\n\n\t********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) else part"); result="exception"; } System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- End"); return(result); } } I want to upload a file to the server. The file is get from user " tag in the "app_details_1.ftl" file & it is updated into the server by using the method "testingService(HttpServletRequest request, HttpServletResponse response)" in the class "WebServices1". But the file is not uploaded. Give me a good solution for uploading a file to the server.

    Read the article

  • How to Upload a file from client to server using OFBIZ?

    - by SIVAKUMAR.J
    Hi all, Im new to ofbiz.So is my question is have any mistake forgive me for my mistakes.Im new to ofbiz so i did not know some terminologies in ofbiz.Sometimes my question is not clear because of lack of knowledge in ofbiz.So try to understand my question and give me a good solution with respect to my level.Because some solutions are in very high level cannot able to understand for me.So please give the solution with good examples. My problem is i created a project inside the ofbiz/hot-deploy folder namely "productionmgntSystem".Inside the folder "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem" i created a .ftl file namely "app_details_1.ftl" .The following are the coding of this file <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT"> function uploadFile() { //alert("Before calling upload.jsp"); window.location='<@ofbizUrl>testing_service1</@ofbizUrl>' } </script> </head> <!-- <form action="<@ofbizUrl>testing_service1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> --> <form action="<@ofbizUrl>logout1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> <center style="height: 299px; "> <table border="0" style="height: 177px; width: 788px"> <tr style="height: 115px; "> <td style="width: 103px; "> <td style="width: 413px; "><h1>APPLICATION DETAILS</h1> <td style="width: 55px; "> </tr> <tr> <td style="width: 125px; ">Application name : </td> <td> <input name="app_name_txt" id="txt_1" value=" " /> </td> </tr> <tr> <td style="width: 125px; ">Excell sheet &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </td> <td> <input type="file" name="filename"/> </td> </tr> <tr> <td> <!-- <input type="button" name="logout1_cmd" value="Logout" onclick="logout1()"/> --> <input type="submit" name="logout_cmd" value="logout"/> </td> <td> <!-- <input type="submit" name="upload_cmd" value="Submit" /> --> <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/> </td> </tr> </table> </center> </form> </html> the following coding is present in the file "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem\WEB-INF\controller.xml" ...... ....... ........ <request-map uri="testing_service1"> <security https="true" auth="true"/> <event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.WebServices1" invoke="testingService"/> <response name="ok" type="view" value="ok_view"/> <response name="exception" type="view" value="exception_view"/> </request-map> .......... ............ .......... <view-map name="ok_view" type="ftl" page="ok_view.ftl"/> <view-map name="exception_view" type="ftl" page="exception_view.ftl"/> ................ ............. ............. The following are the coding present in the file "ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req\WebServices1.java" package org.ofbiz.productionmgntSystem.web_app_req; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; public class WebServices1 { public static String testingService(HttpServletRequest request, HttpServletResponse response) { //int i=0; String result="ok"; System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- Start"); String contentType=request.getContentType(); System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- contentType : "+contentType); String str=new String(); // response.setContentType("text/html"); //PrintWriter writer; if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) after if (contentType != null)"); try { // writer=response.getWriter(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try Start"); DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //this loop converting the uploaded file into byte code while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); //for saving the file name String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; //extracting the index of file pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; //creating a new file with the same name and writing the content in new file FileOutputStream fileOut = new FileOutputStream("/"+saveFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try End"); } catch(IOException ioe) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch IOException"); //ioe.printStackTrace(); return("exception"); } catch(Exception ex) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch Exception"); return("exception"); } } else { System.out.println("\n\n\t********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) else part"); result="exception"; } System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- End"); return(result); } } I want to upload a file to the server.The file is get from user "<input type="file"..> tag in the "app_details_1.ftl" file & it is updated into the server by using the method "testingService(HttpServletRequest request, HttpServletResponse response)" in the class "WebServices1".But the file is not uploaded. Give me a good solution for uploading a file to the server. Thanks & Regards, Sivakumar.J

    Read the article

  • red5 and servlets: can i get HttpServerRequest and HttpServerResponse?

    - by ufk
    Hiya I'm trying to write an application for red5 that uses some servlet classes in order to package a requestion for facebook. the client side is a Adobe flash builder application. is it possible to send session information from the flex application in order for the red5 client side to create proper HttpServletRequest and HttpServletResponse objects? in tomcat the code would be: public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; ... }

    Read the article

  • How to Upload a file from client to server using OFBIZ?

    - by SIVAKUMAR.J
    Hi all, Im new to ofbiz.So is my question is have any mistake forgive me for my mistakes.Im new to ofbiz so i did not know some terminologies in ofbiz.Sometimes my question is not clear because of lack of knowledge in ofbiz.So try to understand my question and give me a good solution with respect to my level.Because some solutions are in very high level cannot able to understand for me.So please give the solution with good examples. My problem is i created a project inside the ofbiz/hot-deploy folder namely "productionmgntSystem".Inside the folder "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem" i created a .ftl file namely "app_details_1.ftl" .The following are the coding of this file <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT"> function uploadFile() { //alert("Before calling upload.jsp"); window.location='<@ofbizUrl>testing_service1</@ofbizUrl>' } </script> </head> <!-- <form action="<@ofbizUrl>testing_service1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> --> <form action="<@ofbizUrl>logout1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> <center style="height: 299px; "> <table border="0" style="height: 177px; width: 788px"> <tr style="height: 115px; "> <td style="width: 103px; "> <td style="width: 413px; "><h1>APPLICATION DETAILS</h1> <td style="width: 55px; "> </tr> <tr> <td style="width: 125px; ">Application name : </td> <td> <input name="app_name_txt" id="txt_1" value=" " /> </td> </tr> <tr> <td style="width: 125px; ">Excell sheet &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </td> <td> <input type="file" name="filename"/> </td> </tr> <tr> <td> <!-- <input type="button" name="logout1_cmd" value="Logout" onclick="logout1()"/> --> <input type="submit" name="logout_cmd" value="logout"/> </td> <td> <!-- <input type="submit" name="upload_cmd" value="Submit" /> --> <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/> </td> </tr> </table> </center> </form> </html> the following coding is present in the file "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem\WEB-INF\controller.xml" ...... ....... ........ <request-map uri="testing_service1"> <security https="true" auth="true"/> <event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.WebServices1" invoke="testingService"/> <response name="ok" type="view" value="ok_view"/> <response name="exception" type="view" value="exception_view"/> </request-map> .......... ............ .......... <view-map name="ok_view" type="ftl" page="ok_view.ftl"/> <view-map name="exception_view" type="ftl" page="exception_view.ftl"/> ................ ............. ............. The following are the coding present in the file "ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req\WebServices1.java" package org.ofbiz.productionmgntSystem.web_app_req; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; public class WebServices1 { public static String testingService(HttpServletRequest request, HttpServletResponse response) { //int i=0; String result="ok"; System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- Start"); String contentType=request.getContentType(); System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- contentType : "+contentType); String str=new String(); // response.setContentType("text/html"); //PrintWriter writer; if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) after if (contentType != null)"); try { // writer=response.getWriter(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try Start"); DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //this loop converting the uploaded file into byte code while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); //for saving the file name String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; //extracting the index of file pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; //creating a new file with the same name and writing the content in new file FileOutputStream fileOut = new FileOutputStream("/"+saveFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try End"); } catch(IOException ioe) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch IOException"); //ioe.printStackTrace(); return("exception"); } catch(Exception ex) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch Exception"); return("exception"); } } else { System.out.println("\n\n\t********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) else part"); result="exception"; } System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- End"); return(result); } } I want to upload a file to the server.The file is get from user "<input type="file"..> tag in the "app_details_1.ftl" file & it is updated into the server by using the method "testingService(HttpServletRequest request, HttpServletResponse response)" in the class "WebServices1".But the file is not uploaded. Give me a good solution for uploading a file to the server. Thanks & Regards, Sivakumar.J

    Read the article

  • Issues with timed out downloads via TomCat?

    - by Ira Baxter
    We get, in our opinion, a lot of failed download attempts and want to understand why. We offer downloads via an email link (typical): http://www.semanticdesigns.com/deliverEval/<productname> This is processed by Tomcat on Linux via a jsp file, with the following code: response.addHeader( "Content-Disposition", "attachment; filename=" + fileTail ); response.addHeader( "Content-Type", "application/x-msdos-program" ); byte[] buf = new byte[8192]; int read; try { java.io.FileInputStream input = new java.io.FileInputStream( filename ); java.io.OutputStream o = response.getOutputStream(); while( ( read = input.read( buf, 0, 8192 ) ) != -1 ){ o.write( buf, 0, read ); } o.flush(); } catch( Exception e ){ util.fatalError( request.getRequestURI(), "Error sending file '" + filename + "' to client", e ); throw e; } We get a lot of reported errors (about 50% error rate): URI --- /deliverEval/download.jsp Code Message: Error sending file '/home/sd/ShippingMasters/DMS/Domains/C/GCC3/Tools/TestCoverage/SD_C~GCC3_TestCoverage.1.6.12.exe' to client Stack Trace ----------- null at org.apache.coyote.tomcat5.OutputBuffer.realWriteBytes(byte[], int, int) (Unknown Source) at org.apache.tomcat.util.buf.ByteChunk.append(byte[], int, int) (Unknown Source) at org.apache.coyote.tomcat5.OutputBuffer.writeBytes(byte[], int, int) (Unknown Source) at org.apache.coyote.tomcat5.OutputBuffer.write(byte[], int, int) (Unknown Source) at org.apache.coyote.tomcat5.CoyoteOutputStream.write(byte[], int, int) (Unknown Source) at org.apache.jsp.deliverEval.download_jsp._jspService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) (Unknown Source) at org.apache.jasper.runtime.HttpJspBase.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) (Unknown Source) at javax.servlet.http.HttpServlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.jasper.servlet.JspServletWrapper.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean) (Unknown Source) at org.apache.jasper.servlet.JspServlet.serviceJspFile(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.Throwable, boolean) (Unknown Source) at org.apache.jasper.servlet.JspServlet.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) (Unknown Source) at javax.servlet.http.HttpServlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.catalina.core.ApplicationFilterChain.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) (Unknown Source) at org.apache.catalina.core.StandardWrapperValve.invoke(org.apache.catalina.Request, org.apache.catalina.Response, org.apache.catalina.ValveContext) (Unknown Source) We don't understand why this rate should be so high. Is there any way to get more information about the cause of the error? It is useful to know that these are pretty big documents, 3-50 megabytes. They reside on the Linux server so reading them is just a local disk read, and is unlikely to be a contributor to the problem. But sheer size might be an issue for the recipients browser? Is this kind of error rate typical for downloads? My personal experience downloading other's documents suggests no; our internal attempts show this to be very reliable, but we're operating on our internal network for such experiments so we're missing the complexity of the intervening internet.

    Read the article

  • java servlet programming errror

    - by abson
    C:\Tomcat5.5\webapps\WEB-INF\classes>javac MyServlet.java MyServlet.java:2: package javax.servlet does not exist import javax.servlet.*; ^ MyServlet.java:3: package javax.servlet.http does not exist import javax.servlet.http.*; ^ MyServlet.java:5: cannot find symbol symbol: class HttpServlet public class MyServlet extends HttpServlet ^ MyServlet.java:7: cannot find symbol symbol : class HttpServletRequest location: class MyServlet public void doGet(HttpServletRequest req, HttpServletResponse res) throws Serv letException,IOException ^ MyServlet.java:7: cannot find symbol symbol : class HttpServletResponse location: class MyServlet public void doGet(HttpServletRequest req, HttpServletResponse res) throws Serv letException,IOException ^ MyServlet.java:7: cannot find symbol symbol : class ServletException location: class MyServlet public void doGet(HttpServletRequest req, HttpServletResponse res) throws Serv letException,IOException ^ 6 errors

    Read the article

  • Why download popup window in browser not showing up when using JAX-RS v.s. standard servlet?

    - by masato-san
    When I try using standard servlet approach, in my browser the popup window shows up asking me whether to open .xls file or save it. I tried the exactly same code via JAX-RS and the browser popup won't show up somehow. Has anyone encounter this mystery? Standard servlet that works: package local.test.servlet; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import local.test.jaxrs.ExcellaTestResource; import org.apache.poi.ss.usermodel.Workbook; import org.bbreak.excella.core.BookData; import org.bbreak.excella.core.exception.ExportException; import org.bbreak.excella.reports.exporter.ExcelExporter; import org.bbreak.excella.reports.exporter.ReportBookExporter; import org.bbreak.excella.reports.model.ConvertConfiguration; import org.bbreak.excella.reports.model.ReportBook; import org.bbreak.excella.reports.model.ReportSheet; import org.bbreak.excella.reports.processor.ReportProcessor; @WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"}) public class ExcelServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //C:\Users\m-takayashiki\.netbeans\6.9\config\GF3\domain1 // ================== ?????? ======================= URL templateFileUrl = ExcellaTestResource.class.getResource("?????????.xls"); // /C:/Users/m-takayashiki/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/?????????.xls System.out.println(templateFileUrl.getPath()); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("??????"); outputBook.addReportSheet(outputSheet); // ======================================================== // --------------- ?????? ------------------------- reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); System.out.println("wtf???"); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } } //end doGet() @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } @Override public String getExtention() { return null; } @Override public String getFormatType() { return ExcelExporter.FORMAT_TYPE; } @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { System.out.println(book.getFirstVisibleTab()); System.out.println(book.getSheetName(0)); //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class JAX-RS way that won't display popup: package local.test.jaxrs; import java.net.URL; import java.net.URLDecoder; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.Produces; import org.apache.poi.ss.usermodel.Workbook; import org.bbreak.excella.core.BookData; import org.bbreak.excella.core.exception.ExportException; import org.bbreak.excella.reports.exporter.ExcelExporter; import org.bbreak.excella.reports.exporter.ReportBookExporter; import org.bbreak.excella.reports.model.ConvertConfiguration; import org.bbreak.excella.reports.model.ReportBook; import org.bbreak.excella.reports.model.ReportSheet; import org.bbreak.excella.reports.processor.ReportProcessor; @Path("excellaTest") public class ExcellaTestResource { @Context private UriInfo context; @Context private HttpServletResponse response; @Context private HttpServletRequest request; public ExcellaTestResource() { } @Path("horizontalProcess") @GET //@Produces("application/vnd.ms-excel") @Produces("application/vnd.ms-excel") public void getProcessHorizontally() { try { //C:\Users\m-takayashiki\.netbeans\6.9\config\GF3\domain1 // ================== ?????? ======================= URL templateFileUrl = this.getClass().getResource("?????????.xls"); // /C:/Users/m-takayashiki/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/?????????.xls System.out.println(templateFileUrl.getPath()); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("??????"); outputBook.addReportSheet(outputSheet); // ======================================================== // --------------- ?????? ------------------------- reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); System.out.println("wtf???"); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } //return response; return; } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } @Override public String getExtention() { return null; } @Override public String getFormatType() { return ExcelExporter.FORMAT_TYPE; } @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class

    Read the article

  • How to use Twitter4j With JSF2 for Login? [on hold]

    - by subodh
    I am trying to do login with Twitter and using Twitter4j for that and wrote this code In JSF <h:commandButton id="twitterbutton" value="Sign up with Twitter" action="#{twitterLoginBean.redirectTwitterLogin}" immediate="true" styleClass="twitterbutton"/> In ManagedBean public String redirectTwitterLogin() throws ServletException, IOException, TwitterException { HttpServletRequest request = (HttpServletRequest) FacesContext .getCurrentInstance().getExternalContext().getRequest(); HttpServletResponse response = (HttpServletResponse) FacesContext .getCurrentInstance().getExternalContext().getResponse(); Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(apiKey, apiSecret); RequestToken requestToken = twitter.getOAuthRequestToken(); if (requestToken != null) { AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); while (null == accessToken) { try { String pin = br.readLine(); accessToken = twitter .getOAuthAccessToken(requestToken, pin); } catch (TwitterException te) { System.out .println("Failed to get access token, caused by: " + te.getMessage()); System.out.println("Retry input PIN"); } } request.setAttribute(IS_AUTHENTICATED, true); if (accessToken != null) { LOGGER.debug("We have a valid oauth token! Make the facebook request"); doApiCall(twitter, request, response); return null; } } else { LOGGER.debug("We don't have auth code yet, fetching the Authorization URL..."); String authorizationUrl = requestToken.getAuthorizationURL(); LOGGER.debug("Redirecting to the Authorization URL: {}", authorizationUrl); request.setAttribute(IS_AUTHENTICATED, false); redirect(authorizationUrl, response); return null; } return null; } In above code i want first Login window of twitter will show and then again same method will call and after user will login i can show user information userId,Handel,location etc. Redirect private void redirect(String url, HttpServletResponse response) throws IOException { String urlWithSessionID = response.encodeRedirectURL(url); response.sendRedirect(urlWithSessionID); } But this code is not working Can anyone tell better Solution for this ?

    Read the article

  • migrating an embedded jetty server from v6 to v7

    - by Ceilingfish
    Hi chaps, I have an embedded servlet which I use in unit tests, looks like this: public class UnitTestWebservices extends AbstractHandler { private Server server; private Map<Route,String> data = new HashMap<Route,String>(); public UnitTestWebservices(int port) throws Exception { server = new Server(port); server.setHandler(this); server.start(); } public void handle(String url, HttpServletRequest request, HttpServletResponse response, int arg3) throws IOException, ServletException { final Route route = Route.valueOf(request.getMethod(), url); final String content = data.get(route); if(content != null) { final ServletOutputStream stream = response.getOutputStream(); stream.print(content); stream.flush(); stream.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } .... } That's written using version 6.1.24 of Jetty. I tried switching over to use Jetty 7.1.1.v20100517, and updated that code to this: public class UnitTestWebservices extends AbstractHandler { private Server server; private Map<Route,String> data = new HashMap<Route,String>(); public UnitTestWebservices(int port) throws Exception { server = new Server(port); server.setHandler(this); server.start(); } public void handle(String url, Request request, HttpServletRequest servletRequest, HttpServletResponse response) throws IOException, ServletException { final Route route = Route.valueOf(request.getMethod(), url); final String content = data.get(route); request.setHandled(true); response.setContentType("application/json"); if(content != null) { response.setStatus(HttpServletResponse.SC_OK); final Writer stream = response.getWriter(); stream.append(content); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } } But whenever I tried to access make a request to the server it would hang indefinitely. Has anyone experienced anything similar?. It also printed this into the log: log4j:WARN No appenders could be found for logger (org.eclipse.jetty.util.log). log4j:WARN Please initialize the log4j system properly. org.eclipse.jetty.server.Server@670655dd STOPPED +-UnitTestWebservices@50ef5502 started

    Read the article

  • problem with overriding autologin in spring security?

    - by sword101
    greetings everybody iam using spring security 3 remember me service as follows <http> <remember-me/> ....</http> and i want to perform some logic in the autologin so i tried to override the AbstractRememberMeServices as follows: package com.foo; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.RememberMeServices; public abstract class AbstractRememberMeServices implements RememberMeServices{ @Override public Authentication autoLogin(HttpServletRequest arg0, HttpServletResponse arg1) { System.out.println("Auto Login"); return null; } @Override public void loginSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication arg2) { System.out.println("Login Success"); } } but the autologin occurs with no action,the user auto login but the print statement is not printed? what's wrong?

    Read the article

  • problem with overriding autologin in spring framework?

    - by sword101
    greetings everybody iam using spring 3 remember me service as follows <http> <remember-me/> ....</http> and i want to perform some logic in the autologin so i tried to override the AbstractRememberMeServices as follows: package com.foo; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.RememberMeServices; public abstract class AbstractRememberMeServices implements RememberMeServices{ @Override public Authentication autoLogin(HttpServletRequest arg0, HttpServletResponse arg1) { System.out.println("Auto Login"); return null; } @Override public void loginSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication arg2) { System.out.println("Login Success"); } } but the autologin occurs with no action,the user auto login but the print statement is not printed? what's wrong?

    Read the article

  • Why is this simple file upload not working? JSF

    - by Nitesh Panchal
    Hello, Why is this code not working? I always get size() = 0, whenever i upload file. xhtml file :- <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Abc</title> </h:head> <h:body> <center> <form method="post" enctype="multipart/form-data" id="form" action="/upload/uploadFile"> <input type="file"/> <br/> <input type="Submit" value="upload"/> </form> </center> </h:body> </html> This is my servlet :- package servlets; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet(name="uploadFile", urlPatterns={"/uploadFile"}) public class uploadFile extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException { System.out.println("executed!"); List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); System.out.println(items.size()); for (FileItem item : items) { if (!item.isFormField()) { System.out.println("Name: " + item.getName()); System.out.println("Size: " + item.getSize()); System.out.println("Type: " + item.getContentType()); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (FileUploadException ex) { ex.printStackTrace(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (FileUploadException ex) { ex.printStackTrace(); } } @Override public String getServletInfo() { return "Short description"; } }

    Read the article

  • Java EE 6 and NoSQL/MongoDB on GlassFish using JPA and EclipseLink 2.4 (TOTD #175)

    - by arungupta
    TOTD #166 explained how to use MongoDB in your Java EE 6 applications. The code in that tip used the APIs exposed by the MongoDB Java driver and so requires you to learn a new API. However if you are building Java EE 6 applications then you are already familiar with Java Persistence API (JPA). Eclipse Link 2.4, scheduled to release as part of Eclipse Juno, provides support for NoSQL databases by mapping a JPA entity to a document. Their wiki provides complete explanation of how the mapping is done. This Tip Of The Day (TOTD) will show how you can leverage that support in your Java EE 6 applications deployed on GlassFish 3.1.2. Before we dig into the code, here are the key concepts ... A POJO is mapped to a NoSQL data source using @NoSQL or <no-sql> element in "persistence.xml". A subset of JPQL and Criteria query are supported, based upon the underlying data store Connection properties are defined in "persistence.xml" Now, lets lets take a look at the code ... Download the latest EclipseLink 2.4 Nightly Bundle. There is a Installer, Source, and Bundle - make sure to download the Bundle link (20120410) and unzip. Download GlassFish 3.1.2 zip and unzip. Install the Eclipse Link 2.4 JARs in GlassFish Remove the following JARs from "glassfish/modules": org.eclipse.persistence.antlr.jar org.eclipse.persistence.asm.jar org.eclipse.persistence.core.jar org.eclipse.persistence.jpa.jar org.eclipse.persistence.jpa.modelgen.jar org.eclipse.persistence.moxy.jar org.eclipse.persistence.oracle.jar Add the following JARs from Eclipse Link 2.4 nightly build to "glassfish/modules": org.eclipse.persistence.antlr_3.2.0.v201107111232.jar org.eclipse.persistence.asm_3.3.1.v201107111215.jar org.eclipse.persistence.core.jpql_2.4.0.v20120407-r11132.jar org.eclipse.persistence.core_2.4.0.v20120407-r11132.jar org.eclipse.persistence.jpa.jpql_2.0.0.v20120407-r11132.jar org.eclipse.persistence.jpa.modelgen_2.4.0.v20120407-r11132.jar org.eclipse.persistence.jpa_2.4.0.v20120407-r11132.jar org.eclipse.persistence.moxy_2.4.0.v20120407-r11132.jar org.eclipse.persistence.nosql_2.4.0.v20120407-r11132.jar org.eclipse.persistence.oracle_2.4.0.v20120407-r11132.jar Start MongoDB Download latest MongoDB from here (2.0.4 as of this writing). Create the default data directory for MongoDB as: sudo mkdir -p /data/db/sudo chown `id -u` /data/db Refer to Quickstart for more details. Start MongoDB as: arungup-mac:mongodb-osx-x86_64-2.0.4 <arungup> ->./bin/mongod./bin/mongod --help for help and startup optionsMon Apr  9 12:56:02 [initandlisten] MongoDB starting : pid=3124 port=27017 dbpath=/data/db/ 64-bit host=arungup-mac.localMon Apr  9 12:56:02 [initandlisten] db version v2.0.4, pdfile version 4.5Mon Apr  9 12:56:02 [initandlisten] git version: 329f3c47fe8136c03392c8f0e548506cb21f8ebfMon Apr  9 12:56:02 [initandlisten] build info: Darwin erh2.10gen.cc 9.8.0 Darwin Kernel Version 9.8.0: Wed Jul 15 16:55:01 PDT 2009; root:xnu-1228.15.4~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_40Mon Apr  9 12:56:02 [initandlisten] options: {}Mon Apr  9 12:56:02 [initandlisten] journal dir=/data/db/journalMon Apr  9 12:56:02 [initandlisten] recover : no journal files present, no recovery neededMon Apr  9 12:56:02 [websvr] admin web console waiting for connections on port 28017Mon Apr  9 12:56:02 [initandlisten] waiting for connections on port 27017 Check out the JPA/NoSQL sample from SVN repository. The complete source code built in this TOTD can be downloaded here. Create Java EE 6 web app Create a Java EE 6 Maven web app as: mvn archetype:generate -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee6 -DgroupId=model -DartifactId=javaee-nosql -DarchetypeVersion=1.5 -DinteractiveMode=false Copy the model files from the checked out workspace to the generated project as: cd javaee-nosqlcp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/model src/main/java Copy "persistence.xml" mkdir src/main/resources cp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/META-INF ./src/main/resources Add the following dependencies: <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>2.4.0-SNAPSHOT</version> <scope>provided</scope></dependency><dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.nosql</artifactId> <version>2.4.0-SNAPSHOT</version></dependency><dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.7.3</version></dependency> The first one is for the EclipseLink latest APIs, the second one is for EclipseLink/NoSQL support, and the last one is the MongoDB Java driver. And the following repository: <repositories> <repository> <id>EclipseLink Repo</id> <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url> <snapshots> <enabled>true</enabled> </snapshots> </repository>  </repositories> Copy the "Test.java" to the generated project: mkdir src/main/java/examplecp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/example/Test.java ./src/main/java/example/ This file contains the source code to CRUD the JPA entity to MongoDB. This sample is explained in detail on EclipseLink wiki. Create a new Servlet in "example" directory as: package example;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * @author Arun Gupta */@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})public class TestServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>"); try { Test.main(null); } catch (Exception ex) { ex.printStackTrace(); } out.println("</body>"); out.println("</html>"); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }} Build the project and deploy it as: mvn clean packageglassfish3/bin/asadmin deploy --force=true target/javaee-nosql-1.0-SNAPSHOT.war Accessing http://localhost:8080/javaee-nosql/TestServlet shows the following messages in the server.log: connecting(EISLogin( platform=> MongoPlatform user name=> "" MongoConnectionSpec())) . . .Connected: User: Database: 2.7  Version: 2.7 . . .Executing MappedInteraction() spec => null properties => {mongo.collection=CUSTOMER, mongo.operation=INSERT} input => [DatabaseRecord( CUSTOMER._id => 4F848E2BDA0670307E2A8FA4 CUSTOMER.NAME => AMCE)]. . .Data access result: [{TOTALCOST=757.0, ORDERLINES=[{DESCRIPTION=table, LINENUMBER=1, COST=300.0}, {DESCRIPTION=balls, LINENUMBER=2, COST=5.0}, {DESCRIPTION=rackets, LINENUMBER=3, COST=15.0}, {DESCRIPTION=net, LINENUMBER=4, COST=2.0}, {DESCRIPTION=shipping, LINENUMBER=5, COST=80.0}, {DESCRIPTION=handling, LINENUMBER=6, COST=55.0},{DESCRIPTION=tax, LINENUMBER=7, COST=300.0}], SHIPPINGADDRESS=[{POSTALCODE=L5J1H7, PROVINCE=ON, COUNTRY=Canada, CITY=Ottawa,STREET=17 Jane St.}], VERSION=2, _id=4F848E2BDA0670307E2A8FA8,DESCRIPTION=Pingpong table, CUSTOMER__id=4F848E2BDA0670307E2A8FA7, BILLINGADDRESS=[{POSTALCODE=L5J1H8, PROVINCE=ON, COUNTRY=Canada, CITY=Ottawa, STREET=7 Bank St.}]}] You'll not see any output in the browser, just the output in the console. But the code can be easily modified to do so. Once again, the complete Maven project can be downloaded here. Do you want to try accessing relational and non-relational (aka NoSQL) databases in the same PU ?

    Read the article

  • Losing sessions on GlassFish

    - by synti
    I have a web application that logs users in a @SessionScoped managed bean. It's all the basic stuff, pretty much like this: users logs in using regular http form and gets redirect to user area (wich is protected using a filter). But if any resource on that area is accessed, the request somehow uses a new session, wich has no managed bean, no user, and the filter does his job, redirecting him to login page. Here's the login form: <h:form> <h:outputLabel for="email" value="Email "/> <p:inputText id="email" size="30" value="#{loginManager.email}"/> <h:outputLabel for="password" value="Password "/> <p:password id="password" size="12" value="#{loginManager.password}"/> <p:commandButton value="Login" action="#{loginManager.login()}"/> </h:form> The loginManager managed bean: @ManagedBean @SessionScoped public class LoginManager implements Serializable { @EJB private UserService userService; private User user; private String email; private String password; public String login() { user = userService.findBy(email, password); if (user == null) { // FacesMessage stuff } else { return "/user/welcome.xhtml?faces-redirect=true"; } } public String logout() { FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); return "/index.xhtml?faces-redirect=true"; } // Getters, setters (no setter for user) and serialVersionUID And then comes the filter that protects the user area: @WebFilter(urlPatterns="/user/*", displayName="UserFilter") public class UserFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpSession session = ((HttpServletRequest)request).getSession(false); LoginManager loginManager = (LoginManager) session.getAttribute("loginManager"); if (loginManager == null || !loginManager.hasUser()) { HttpServletResponse resp = (HttpServletResponse) response; resp.sendRedirect("index.xhtml"); } final User user = loginManager.getUser(); if (user.isValid()) { chain.doFilter(request, response); } else { HttpServletResponse resp = (HttpServletResponse) response; resp.sendRedirect("index.xhtml"); } } The UserService is just a stateless EJB that handles persistence. Part of the JSF for user area: <h:form> <p:panelMenu> <p:submenu label="Items"> <p:menuitem value="Add item" action="#{userItens.addItems}" ajax="false"/> <p:menuitem value="My items" /> </p:submenu> </p:panelMenu> </h:form> And finally the userItens managed bean. @ManagedBean @RequestScoped public class UserItens { private User user; @PostConstruct private void init() { HttpSession session = (HttpSession) FacesContext.getCurrentInstance() .getExternalContext().getSession(false); LoginManager loginManager = (LoginManager) session.getAttribute("loginManager"); if (loginManager != null) user = loginManager.getUser(); } public String addItems() { // Doesn't get here. Seems like UserFilter comes first, doesn't find // an user and redirects. } I'm using glassfish and session timeout is now on 0.

    Read the article

  • Sending XML to Servlet from Action Script

    - by John Doe
    I am only getting empty arrays on output. Anyone know what Exactly I'm doing wrong? package myDungeonAccessor; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class myDungeonAccessorServlet extends HttpServlet { private myDungeonAccessor dataAccessor; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet myDungeonAccessorServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet myDungeonAccessorServlet at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); // PrintWriter out = response.getWriter(); System.out.println("yo mom"); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //System.out.println("heppo"); //dataAccessor = new myDungeonAccessor(); System.out.println("Hello"); try { System.out.println("HEADERS: " + request.getHeaderNames()); ObjectInputStream in = new ObjectInputStream(request.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream()); } catch(Exception e) { e.printStackTrace(); } System.out.println("WAZZUP"); byte [] buffer = new byte[4096]; //in.read(buffer); System.out.println("TEST!"); String s = new String(buffer); System.out.println("Update S:" + s); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; } }

    Read the article

  • Embedded Tomcat Cluster

    - by ThreaT
    Can someone please explain with an example how an Embedded Tomcat Cluster works. Would a load balancer be necessary? Since we're using embedded tomcat, how would two separate jar files (each a standalone web application with their own embedded tomcat instance) know where eachother are and let eachother know their status, etc? Here is the code I have so far which is just a regular embedded tomcat without any clustering: import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.Writer; public class Main { public static void main(String[] args) throws LifecycleException, InterruptedException, ServletException { Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath()); Tomcat.addServlet(ctx, "hello", new HttpServlet() { protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Writer w = resp.getWriter(); w.write("Hello, World!"); w.flush(); } }); ctx.addServletMapping("/*", "hello"); tomcat.start(); tomcat.getServer().await(); } } Source: java dzone

    Read the article

  • Axis 1.4 Java: Modify HTTP response code

    - by Achim Bitzer
    Hello, Is there a way to modify the HTTP response code when using apache axis 1.4 for java? This would be useful for testing purposes, for example simulating server side errors. I've already tried the following: Set the HTTP code directly in the http servlet Request: MessageContext context = MessageContext.getCurrentContext(); HttpServletResponse response = (HttpServletResponse) context.getProperty( HTTPConstants.MC_HTTP_SERVLETRESPONSE); response.setStatus(e.getErrorCode()); // no effect Set the HTTP code as axis message context property: MessageContext context = MessageContext.getCurrentContext(); context.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, e.getErrorCode()); But this didn't seem to work, the actual HTTP code always was 200. Any ideas would be greatly appreciated :-) Greetings, Achim Bitzer

    Read the article

1 2 3 4 5 6 7 8  | Next Page >