FileInputStream or URL.openPath()?

I'm trying to create a web-based game and I need to read a file from a specific URL. The file is created locally using a FileOutputStream and an ObjectOutputStream, then uploaded. When the file is used, an InputStream is fed from a URL.openStream() into an ObjectInputStream. The variable is then set to cast from the ObjectInputStream's getObject().
My question here is: Can I write a file with FileOutputStream and then read it with a URL.openStream or do I need some other solution (fFileInputStream for example)? Any input (sic!) would be greatly appreciated!

I'm trying to create a web-based game and I need to read a file from a specific URL. The file is created locally using a FileOutputStream and an ObjectOutputStream, then uploaded. When the file is used, an InputStream is fed from a URL.openStream() into an ObjectInputStream. The variable is then set to cast from the ObjectInputStream's getObject().
My question here is: Can I write a file with FileOutputStream and then read it with a URL.openStream or do I need some other solution (fFileInputStream for example)? Any input (sic!) would be greatly appreciated!

Similar Messages

  • DoPost is not getting called in my servlet

    Hi All
    I have a servlet where I have doGet and doPost methods. My doGet is working but code written in my doPost is not getting fired.Please have a look :
    public class TestServlet extends HttpServlet {
    int count;
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    String initial = config.getInitParameter("initial");
    try {
    count = Integer.parseInt(initial);
    catch (NumberFormatException e) {
    count = 0;
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    count++;
    out.println("Since loading (and with a possible initialization");
    out.println("parameter figured in), this servlet has been accessed");
    out.println(count + " times.");
    doPost(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException {
         PrintWriter out = res.getWriter();
         out.println("in do post");
    Thanks
    Sunit

    Hi Zsom ,
    Thanks for your reply. Here is my code for calling the servlet.
              String base = "http://host:ip/Test2/TestServlet";
              String fileName = sourceFile.getPath();
              System.out.println("sourceFile size " + sourceFile.length());
              FileInputStream fin = new FileInputStream(sourceFile);
              URL url = new URL(base + "?name=" + sourceFile.getName());
              con = url.openConnection();
              con.setRequestProperty("REQUEST_METHOD", "POST");
              con.setDoInput(true);
              con.setDoOutput(true);
              con.setUseCaches(true);
              con.setRequestProperty("Content-Type", "multipart-formdata");
              DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
              int c = 30720;
              byte b[] = new byte[c];
              for (int i = fin.read(b, 0, c); i >= 0; i = fin.read(b, 0, c)) {
                   dataOut.write(b, 0, i);
              System.out.println(dataOut.size());
              dataOut.close();
              fin.close();
              //deleting files from tmp folder
              //File tmpDir = new File("C:\\tmpGravity");
              //deleteDir(tmpDir);
    regards
    Sunit

  • Transfering file from Servlet to Client

    Hello Everyone,
    I have been trying to transfer a file from the Server to the Client. So far I could only make it work in the other way around, from Client to the Server and below it is this code.
    Client.java
    public void transferFile()
              URLConnection con;               
            try
                   File sourceFile = new File("upArrow.png");
                String destPath = "c:\\Temp";
                String fileName = sourceFile.getPath();
                destPath += File.separator + sourceFile.getName();
                FileInputStream fin = new FileInputStream(sourceFile);
                URL url = new URL("http://"+cref.host+":"+cref.port+"/ewb/soldlogs?mode="+URLEncoder.encode("transferFile")+"&name=" + URLEncoder.encode(fileName) + "&path=" + URLEncoder.encode(destPath));
                con = url.openConnection();
        //        con.setRequestProperty("REQUEST_METHOD", "POST");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setUseCaches(true);
                con.setRequestProperty("Content-Type", "multipart-formdata");
                DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
             //   int c = 30720;
              //     int c = Integer.MAX_VALUE/2;
                   int c = 35720;
                byte b[] = new byte[c];
                for(int i = fin.read(b, 0, c); i >= 0; i = fin.read(b, 0, c))
                    dataOut.write(b, 0, i);
                   dataOut.flush();
                dataOut.close();
                fin.close();
                InputStream input = con.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(input));
                String strRes = null;
                while((strRes = br.readLine()) != null)
                    System.out.println(strRes);
                input.close();
                br.close();
            catch(Exception e)
                System.out.println("Error: " + e.toString());
            finally
                con = null;
         }Server.java - Servlet
    else if(mode.equalsIgnoreCase("transferFile")) {
                   String fileName = req.getParameter("name");
                   String destIP = req.getParameter("path");
                   attachPath = destIP;
                   res.setContentType("text/plain");
                   System.out.println("File : " + fileName + " is ready to transfer to " + destIP);
                   File destFile = new File(destIP);
                   DataInputStream dataIn = new DataInputStream(req.getInputStream());
                   BufferedOutputStream buffOut = new BufferedOutputStream(new FileOutputStream(destFile));
                   int c = 30720;
                   byte b[] = new byte[c];
                   try
                        for(int j = dataIn.read(b, 0, c); j >= 0; j = dataIn.read(b, j, c))
                             buffOut.write(b, 0, j);
                             c += j;
                        catch(Exception e)
                             System.out.println("Error in Servlet : " + e.getMessage());
                      dataIn.close();
                      buffOut.close();                 
                        System.out.println("Now, done...");
                   }The Above code is working fine, but as I said it transfer files from the Client to the Server, I wanna do the other way, I tried to change the code but it is not working.
    Any Help is appreciated,
    Thanks in advance

    ZeroTodd wrote:
    The Above code is working fine, but as I said it transfer files from the Client to the Server, I wanna do the other way, I tried to change the code but it is not working.48 posts, and you still make an "it is not working post".
    You are apparently using HTTP to do the transfer. From client to server is an UPLOAD; hence you use a multi-part form and you write the file using an output stream.
    From server to client is far easier: it is a simple DOWNLOAD. So in the client code, open an URLConnection to a specific url that results in the file, configure the URLconnection to do a GET request and read out the response using an input stream. If it doesn't work, the url is apparently not valid.
    Search on google for "urlconnection file download" and you'll get plenty of examples.

  • WebDynpro 4 Java & Persistence options : Any Idea how 2 read an XML?

    Hi,
    I was wondering if there is an easy way to store modified (or new) values in a WebDynpro application.
    e.g. A User adds a new row to an existing Table UI in Web Dynpro application with create button. I want to save this row either in an XML file, in a table connecting to database or in an ABAP table via RFC connection. Which option is a light (on resources?) and easy to implement. I think it's reading and writing to an XML file. What are the other options, if any?
    I've been trying to read an xml file (stored under src/mimes/Components/<com.sap.myComp>/test.xml as below:
    //controller code
    private static final String FILE_NAME = "test.xml";
    private static final WDWebResourceType FILE_EXT = WDWebResourceType.XML;
    IWDResource resource = WDWebResource.getWebResource(wdComponentAPI.getDeployableObjectPart(), EditView.FILE_EXT, EditView.FILE_NAME);
    wdContext.currentContextElement().setFile(resource);
    //end controller code
    //view Init() code
    IWDResource resource = wdContext.currentContextElement().getFile();
    File file = new File(resource.getResourceName().toString());
    /* I've also tried below
            FileInputStream fis = null;
         fis = new FileInputStream(file);
            url = file.getAbsolutePath();
            //url is null when printed?
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    content = doc.getDocumentElement().getNodeName().toString();
    //end view Init() code
    When I print the value of content, I get it's initial value which is null. What is wrong?? any ideas?
    How to get the correct path to the stored xml and how to display its contents? I've read enough posts on SDN but couldn't get it working.
    Appreciate your help.
    Regards,
    N.

    hi,
    U r retriving the elements by tag name.So it just chks the tag name ie.<book> & gives u array of elements.But u need retrive d attribute of <book> tag itself.
    =Solution =====
    Add one more statement ----> var[]= doc.getElementsByName("book");
    Now u hav book elements as an array & can retrive id in for loop
    for(var; var.length;var++)
    doc.element[var].id.value

  • PDF Filename in WebResource URL

    Hi,
    I've got a maybe simple problem, but didn't find any solution.
    I get an PDF File from my application and open it as an external window.
    This works fine
    The URL contains not the filename but "unknown.pdf...".
    How can i change that?
    Following the code where i read the file and open the external window.
    File file = controller.getReportFile(...);
    byte[] fileData = null;
    try {
       fis = new FileInputStream(file);
       fileData = new byte[(int) file.length()];
       fis.read(fileData);
       fis.close();
    catch(Exception e) {
    IWDWindow = null;
    try {
       IWDWebResource webResource = WDWebResource.getWebResource(fileData,    WDWebResourceType.PDF);
       window = wdComponentAPI.getWindowManager().createExternalWindow(webResource.getURL(), "Report", false);
       window.open();
    catch(Exception e) {
    The URL looks like this (short form..)
    ".../~wd_key29_......./unknown.pdf?sap.session....."
    I appreciate any help

    Thank you for your reply.
    I'll try to detail what i want to do.
    The context of the view looks like this:
    Reports.creationDate
    Reports.filename
    Reports.filesize
    Reports.period
    This context is build up in wdDoModifyView and each context element will be bind to a column of a table, which i create manually.
    The table is now filled with these context. One column includes a download link (LinkToAction) which is binded to the action "onActionDownloadReport".
    In this action i read the leadSelection, get the filename of the current context element and send it to my background application which returns me the file.
    The rest is shown in the first posting.
    I tried to create the context attribute PdfSource as binary and the code you given me.
    But nothing happens. It's also "unknown.pdf"
    Maybe i have to bind the PdfSource to LinkToAction?
    Following the code where i create the download link in table.
    IWDLinkToAction link = (IWDLinkToAction) view.createElement(IWDLinkToAction.class, null);
    link.setText("Download");
    link.setOnAction(wdThis.wdGetDownloadReportAction());
    column.setTableCellEditor(link);
    table.addColumn(column);
    Regards
    Ingo

  • Problem in getting the image through URL

    hi all,
    I facing the problem,Inwhich i am unable find the solution...I am using the following code to display the image
    public void doGet(HttpServletRequest request,HttpServletResponse response)
                        throws IOException, ServletException {
                   int data=0;
                   response.setContentType("image/png");
                   ServletOutputStream out = response.getOutputStream();
                   String file = request.getContextPath()+imageNames[0];
                   //String file = "C:/Program Files/Apache Group/Tomcat 4.1/webapps/ImageComm/WEB-INF/images"+imageNames[index];
                   BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                   System.out.println("the size of the inputStream is..."+in.available());
                   System.out.println("the context path is..."+request.getContextPath());          
                   while ((data = in.read()) != -1) {
                   out.write(data);
    with the above i am not getting any error at the compile time but it was giving exception like FileNotFoundException.
    but the same thing(URL address) when i am copying on the browser it was displayig the image.
    (what might be the reason)
    one more thing when i commented on the url address and try to use the actual realpath address it was displaying the image with out any problem
    can anybody give me the solution like where to keep my images by which i can able to get the images through url address
    thanks in advance
    lakshman

    hi all,
    I am getting the image from the server.but the problem is i am getting the Exception as ArrayOutOfBound exception.
    It was displaying the Image for the first time.and when ever it was going for the second time in to the paint method it was displaying the IOException in reading the stream from the connection.
    can anybody give me the solution in rectifying that exception.
    thanks in advance
    lakshman

  • The URL ( xdo://AR.XXINV_REPRINT.en.US/?getSource=true ) is invalid.

    Hi There,
    I am getting below error when bursting a report in Oracle eBusiness Suite(XML Publisher).
    This report works fine in DEV and TEST, but started giving below error when migrated to PROD:
    XML/BI Publisher Version : 5.6.3
    Request ID: 2338377
    All Parameters: ReportRequestID=2338376:DebugFlag=Y
    Report Req ID: 2338376
    Debug Flag: Y
    Updating request description
    Updated description
    Retrieving XML request information
    Node Name:TL1RDB800
    Preparing parameters
    null output =/oraproduct/apps/EBIZD/ebizdcomn/admin/out/EBIZD_tl1rdb800/o2338377.out
    inputfilename =/oraproduct/apps/EBIZD/ebizdcomn/admin/out/EBIZD_tl1rdb800/o2338376.out
    Data XML File:/oraproduct/apps/EBIZD/ebizdcomn/admin/out/EBIZD_tl1rdb800/o2338376.out
    Set Bursting parameters..
    Temp. Directory:/oratemp/EBIZD/ConsolidatedBilling
    [030413_040224973][][STATEMENT] Oracle XML Parser version ::: Oracle XDK Java 9.0.4.0.0 Production
    Start bursting process..
    [030413_040224980][][STATEMENT] /oratemp/EBIZD/ConsolidatedBilling
    [030413_040225003][][STATEMENT] BurstingProcessor ::: Property Key ---> burstng-source
    [030413_040225003][][STATEMENT] Inside burstingConfigParser
    [030413_040225005][oracle.apps.xdo.batch.BurstingProcessorEngine][STATEMENT] ========================> startElement() ::: startDocument is entered <========================
    [030413_040225108][oracle.apps.xdo.batch.BurstingProcessorEngine][STATEMENT] ========================> startElement() ::: startDocument is entered <========================
    [030413_040225109][oracle.apps.xdo.batch.BurstingProcessorEngine][STATEMENT] ========================> startElement() ::: endDocument is entered <========================
    [030413_040225142][][EXCEPTION] The URL ( xdo://AR.XXINV_REPRINT.en.US/?getSource=true ) is invalid.
    [030413_040225143][oracle.apps.xdo.batch.BurstingProcessorEngine][EXCEPTION] java.lang.NullPointerException
         at com.sun.java.util.collections.Hashtable.put(Hashtable.java:381)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.validateTemplateLocation(BurstingProcessorEngine.java:3394)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.createBurstingDocument(BurstingProcessorEngine.java:2084)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstDocument(BurstingProcessorEngine.java:2054)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.endDocument(BurstingProcessorEngine.java:1214)
         at oracle.xml.parser.v2.XMLContentHandler.endDocument(XMLContentHandler.java:105)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:276)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:201)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstingRequest(BurstingProcessorEngine.java:2153)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstingEndElement(BurstingProcessorEngine.java:1802)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.endElement(BurstingProcessorEngine.java:1127)
         at oracle.xml.parser.v2.XMLContentHandler.endElement(XMLContentHandler.java:196)
         at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1212)
         at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:301)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:268)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:227)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstingConfigParser(BurstingProcessorEngine.java:959)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.process(BurstingProcessorEngine.java:903)
         at oracle.apps.xdo.oa.cp.JCP4XDOBurstingEngine.runProgram(JCP4XDOBurstingEngine.java:269)
         at oracle.apps.fnd.cp.request.Run.main(Run.java:161)
    [030413_040225143][][ERROR] The template xdo://AR.XXINV_REPRINT.en.US/?getSource=true can't be fetched.
    [030413_040225143][][STATEMENT] template Filenull
    [030413_040225143][][EXCEPTION] Error while generating the Document...
    [030413_040225144][][EXCEPTION] java.lang.NullPointerException
         at com.sun.java.util.collections.Hashtable.containsKey(Hashtable.java:300)
         at oracle.apps.xdo.batch.bursting.ProcessDocument.getXSLFile(ProcessDocument.java:393)
         at oracle.apps.xdo.batch.bursting.ProcessDocument.processTemplate(ProcessDocument.java:255)
         at oracle.apps.xdo.batch.bursting.ProcessCoreDocument.processLayout(ProcessCoreDocument.java:112)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.addDocument2Queue(BurstingProcessorEngine.java:3206)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.createBurstingDocument(BurstingProcessorEngine.java:2112)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstDocument(BurstingProcessorEngine.java:2054)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.endDocument(BurstingProcessorEngine.java:1214)
         at oracle.xml.parser.v2.XMLContentHandler.endDocument(XMLContentHandler.java:105)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:276)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:201)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstingRequest(BurstingProcessorEngine.java:2153)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstingEndElement(BurstingProcessorEngine.java:1802)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.endElement(BurstingProcessorEngine.java:1127)
         at oracle.xml.parser.v2.XMLContentHandler.endElement(XMLContentHandler.java:196)
         at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1212)
         at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:301)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:268)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:227)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.burstingConfigParser(BurstingProcessorEngine.java:959)
         at oracle.apps.xdo.batch.BurstingProcessorEngine.process(BurstingProcessorEngine.java:903)
         at oracle.apps.xdo.oa.cp.JCP4XDOBurstingEngine.runProgram(JCP4XDOBurstingEngine.java:269)
         at oracle.apps.fnd.cp.request.Run.main(Run.java:161)
    [030413_040225226][][STATEMENT] initConfig(): config file used :null
    [030413_040225227][][STATEMENT] initCustomFactories(): loading custom delivery channels :{}
    [030413_040225227][oracle.apps.xdo.delivery.DeliveryManager][STATEMENT] initConfig(): loading default properties :{}
    [030413_040225227][oracle.apps.xdo.batch.BurstingProcessorEngine][STATEMENT] ========================> startElement() ::: endDocument is entered <========================
    Bursting process complete..
    Generating Bursting Status Report..
    --Exception
    /oratemp/EBIZD/ConsolidatedBilling/030413_040224997/___.pdf (No such file or directory)
    java.io.FileNotFoundException: /oratemp/EBIZD/ConsolidatedBilling/030413_040224997/___.pdf (No such file or directory)
         at java.io.FileInputStream.open(Native Method)
         at java.io.FileInputStream.<init>(FileInputStream.java:106)
         at java.io.FileInputStream.<init>(FileInputStream.java:66)
         at oracle.apps.xdo.oa.cp.JCP4XDOBurstingEngine.zipOutputFiles(JCP4XDOBurstingEngine.java:503)
         at oracle.apps.xdo.oa.cp.JCP4XDOBurstingEngine.runProgram(JCP4XDOBurstingEngine.java:275)
         at oracle.apps.fnd.cp.request.Run.main(Run.java:161)
    [030413_040225249][oracle.apps.xdo.batch.bursting.FileHandler][STATEMENT] /oratemp/EBIZD/ConsolidatedBilling/030413_040224997/xdo0.tmp is deleted
    [030413_040225254][oracle.apps.xdo.batch.bursting.FileHandler][STATEMENT] /oratemp/EBIZD/ConsolidatedBilling/030413_040224997/xdo1.tmp is not deleted
    Below is the Bursting Control File:
    <?xml version="1.0" encoding="UTF-8"?>
    <xapi:requestset xmlns:xapi="http://xmlns.oracle.com/oxp/xapi" type="bursting">
    <xapi:request select="/XXINV/LIST_G_SETUP/G_SETUP/LIST_G_SITES/G_SITES">
    <xapi:delivery>
    <xapi:filesystem output="${RDF_CUSTOMER_NAME}_${RDF_CUTOFF_DATE}_${BILLING_NO}_${CUSTOMER_NUMBER}.pdf"/>
    </xapi:delivery>     
    <xapi:document output-type="pdf">
    <xapi:template type="rtf" location="xdo://AR.XXINV_REPRINT.en.US/?getSource=true">
    </xapi:template>
    </xapi:document>
    </xapi:request>
    </xapi:requestset>
    Thanks
    Yogi

    Hi,
    Found the cause of the error:
    When the Data Definition was migrated from DEV to PROD using the ldt files, somehow it dropped the default territory which is 'United States'.
    Hence the path of the template xdo://AR.XXINV_REPRINT.en.US is throwing an error.
    The below query can be used to determine the value that should go in the bursting control file in the path:
    SELECT APPLICATION_SHORT_NAME||'.'||
    TEMPLATE_CODE||'.'||
    DEFAULT_LANGUAGE ||'.'||
    DEFAULT_TERRITORY
    FROM XDO_TEMPLATES_VL
    WHERE TEMPLATE_CODE like '%XXINV%REPRINT%'
    REUSULT:
    AR.XXINV_REPRINT.en.00
    Hence AR.XXINV_REPRINT.en.US should be replaced with AR.XXINV_REPRINT.en.00 in the bursting control file which will fix the issue.
    Thanks
    Yogi

  • Could not load file/URL (file not found) error for JNLP file

    I am completely baffled in trying to figure out why I am getting the following error for some JNLP files but not others:
    Error: could not load file/URL specified: C:\Users\tom\AppData\Local\Temp\javaws2
    java.io.FileNotFoundException: C:\Users\tom\AppData\Local\Temp\javaws2 (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at com.sun.javaws.jnl.LaunchDescFactory.buildDescriptor(Unknown Source)
    at com.sun.javaws.Main.launchApp(Unknown Source)
    at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
    at com.sun.javaws.Main$1.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)I have Googled around this forum and elsewhere, and have seen reports that this error is IE-specific, and seems to have something to do with no-cache headers being sent, or with the client browser's cache being full or turned off (which is not my case). I saw the information in the JavaWS FAQ, which recommended turning off security constraints for the JNLP's URI. I tried that, and it didn't help. One of the very baffling things is that I have created several variations of the JNLP file, with varying combinations of jars and property resources, and some combinations always work while other combinations never work. Here's an example:
    <jnlp spec="1.0+" codebase="$$codebase">
       <information>
          <title>demo app</title>
          <description>illustrates weird bug</description>
       </information>
       <resources>
          <j2se version="1.5+"/>
          <jar href="randomFile.jar"/>
          <property name="xxx" value="xxxx"/>
          <property name="swing.metalTheme" value="steel"/>
       </resources>
    </jnlp>The above file always fails with the error shown at the top of this message. However, if I remove either of the two properties, it works fine. And I have created other variations with lots of properties, some of which work. All of these variations are in the same directory in the war file, served by the exact same servlet (a slightly modified version of the jnlp.sample.servlet.JnlpDownloadServlet provided with JDK 1.6.0_3). Assuming that a no-cache header is the problem, what on earth could be causing some JNLP files to always be served with a no-cache header, while others are never served with a no-cache header?
    On a related note, any recommended debugging techniques for seeing what headers are being transmitted? I tried adding a simple check for a "debug=true" parameter in the servlet that causes it to set the content type to "text/plain" instead of JNLP, and that allows me to see (rather than execute) the JNLP XML that's being returned, but it doesn't show me the HTTP headers that are being sent back. If any caching headers are being set, I think it must be being set by the servlet container itself, as it's nothing being set in the servlet code that I can see. So I don't see any way on the server side Java code to output or log the actual HTTP response (or is there?). Any tips in that regard much appreciated.
    Edited by: TomC125468 on Aug 19, 2009 1:35 PM

    Hi Luca-Sanna,
    Thanks for the response. Re browsers, yes, it fails in IE but it succeeds in Firefox. The info on the JavaWS FAQ and other places all seem to indicate that it's an IE issue concerning handling of the cache-control headers.
    I should check in my webserver forum (Sun WebServer 7) to see about logging options. Sniffing on the client side is not possible, as my app is required to use HTTPS exclusively, and unfortunately that also precludes a telnet GET request.

  • Reading binary data from a URL

    Below are 2 snippets of code that read data from a binary file. A small sample of the output is shown at the bottom of each code fragment. The first one uses the URL class to read a remote file. The ouput for this fragment is incorrect in some cases. The second uses a stream reader to read a local file (the output is correct in this case). Both fragments read the same file.
    As you can notice, some of the bytes read are the same in both cases. Some others are not.
    I hope you can suggest how I can fix my URL version.
    Thanks for your help.
    Miguel
    Program A: Reads a remote file with URL
    URL url = new URL("http:localhost//myfile.awg");
    URLConnection connection = url.openConnection();
    BufferedReader bin = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while(true) {
    System.out.println(Integer.toHexString(bin.read()));
    7d 3 0 0
    22 30 3 3e
    fd b9 2a 0
    b2 2 0 1
    Program B: Rads a local file
    DataInputStream din = new DataInputStream(new BufferedInputStream
    (new FileInputStream("c:\\inetpub\\wwwroot\\myfile.awg")));
    while(true) {
    System.out.println(Integer.toHexString(din.read()));
    8e 3 0 0
    99 30 3 3e
    81 b9 2a 0
    b2 2 0 1

    What can I use instead?
    Thanks,
    MiguelBufferedInputStream as in Program B.

  • Exception on creation of service metadata for WSDL URL

    Hi expert,
    im consuming a wsdl file in my wdj dc , and on trying to execute im getting exception as follows .
    WsdlApp--com.sap.tc.webdynpro.model.webservice.exception.WSModelRuntimeException: Exception on creation of service metadata for WSDL URL 'E:\***********\MIOS_*********_********.wsdl' and service factory configuration 'null'
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getOrCreateWsrService(WSModelInfo.java:422)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.readOperationsFromWSDL(WSModelInfo.java:372)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.importMetadataInternal(WSModelInfo.java:342)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.importMetadata(WSModelInfo.java:326)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo$Cache.getModelInfo(WSModelInfo.java:199)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getModelInfoFromCacheOrCreate(WSModelInfo.java:1035)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getModelInfoFromCacheOrCreate(WSModelInfo.java:248)
    at com.sap.tc.webdynpro.model.webservice.gci.WSTypedModel.<init>(WSTypedModel.java:41)
    at com.*****.wsdlwdj.batch.****************Batch.<init>(******************Batch.java:51)
    at com.*****.wsdlwdj.comp.*************Component.test**********Auth(************Component.java:266)
    at com.*****.wsdlwdj.comp.wdp.Internal****Component.test****Auth(Internal********Component.java:331)
    at com.*****.wsdlwdj.comp.WsdlView.wdDoInit(WsdlView.java:97)
    at com.*****.wsdlwdj.comp.wdp.InternalWsdlView.wdDoInit(InternalWsdlView.java:129)
    at com.sap.tc.webdynpro.progmodel.generation.DelegatingView.doInit(DelegatingView.java:61)
    at com.sap.tc.webdynpro.progmodel.controller.Controller.initController(Controller.java:215)
    at com.sap.tc.webdynpro.progmodel.view.View.initController(View.java:445)
    at com.sap.tc.webdynpro.progmodel.controller.Controller.init(Controller.java:200)
    at com.sap.tc.webdynpro.progmodel.view.ViewManager.getView(ViewManager.java:709)
    at com.sap.tc.webdynpro.progmodel.view.ViewManager.bindRoot(ViewManager.java:579)
    at com.sap.tc.webdynpro.progmodel.view.ViewManager.init(ViewManager.java:155)
    at com.sap.tc.webdynpro.clientserver.window.WebDynproWindow.doOpen(WebDynproWindow.java:295)
    at com.sap.tc.webdynpro.clientserver.window.ApplicationWindow.show(ApplicationWindow.java:182)
    at com.sap.tc.webdynpro.clientserver.window.ApplicationWindow.open(ApplicationWindow.java:177)
    at com.sap.tc.webdynpro.clientserver.cal.ClientApplication.init(ClientApplication.java:364)
    at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.initApplication(ApplicationSession.java:783)
    at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:303)
    at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessingStandalone(ClientSession.java:741)
    at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:694)
    at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:253)
    at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:185)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doGet(DispatcherServlet.java:46)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.sap.engine.services.servlets_jsp.server.runtime.RequestDispatcherImpl.doWork(RequestDispatcherImpl.java:321)
    at com.sap.engine.services.servlets_jsp.server.runtime.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:377)
    at com.sap.tc.webdynpro.clientserver.session.RequestManager.setSpnegoParameter(RequestManager.java:963)
    at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:157)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doGet(DispatcherServlet.java:46)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
    at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:386)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:364)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:1064)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:265)
    at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
    at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:175)
    at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
    at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
    at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:104)
    at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:176)
    Caused by: com.sap.engine.services.webservices.jaxrpc.exceptions.WebserviceClientException: GenericServiceFactory initialization problem. Could not load web service model. See nested exception for details.
    at com.sap.engine.services.webservices.espbase.client.dynamic.impl.DGenericServiceImpl.generateProxyFiles(DGenericServiceImpl.java:158)
    at com.sap.engine.services.webservices.espbase.client.dynamic.impl.DGenericServiceImpl.<init>(DGenericServiceImpl.java:56)
    at com.sap.engine.services.webservices.espbase.client.dynamic.GenericServiceFactory.createService(GenericServiceFactory.java:92)
    at com.sap.engine.services.webservices.espbase.client.dynamic.GenericServiceFactory.createService(GenericServiceFactory.java:114)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getOrCreateWsrService(WSModelInfo.java:420)
    ... 55 more
    Caused by: com.sap.engine.services.webservices.jaxrpc.exceptions.ProxyGeneratorException: Proxy Generator Error. Problem with WSDL file parsing. See nested message.
    at com.sap.engine.services.webservices.jaxrpc.wsdl2java.ProxyGenerator.generateProxy(ProxyGenerator.java:182)
    at com.sap.engine.services.webservices.espbase.client.dynamic.impl.DGenericServiceImpl.generateProxyFiles(DGenericServiceImpl.java:155)
    ... 59 more
    Caused by: com.sap.engine.lib.xml.util.NestedException: IO Exception occurred while parsing file:/usr/sap/*****/JC**/j2ee/cluster/server1/E:/****/FolderName/WSDLNAME.wsdl (No such file or directory) -> java.io.FileNotFoundException: /usr/sap/***/JC**/j2ee/cluster/server1/E:/WSDL FILE/FolderName/wsdlname.wsdl (No such file or directory)
    at com.sap.engine.services.webservices.wsdl.WSDLDOMLoader.loadDOMDocument(WSDLDOMLoader.java:1039)
    at com.sap.engine.services.webservices.wsdl.WSDLDOMLoader.loadWSDLDocument(WSDLDOMLoader.java:1126)
    at com.sap.engine.services.webservices.jaxrpc.wsdl2java.ProxyGenerator.generateProxy(ProxyGenerator.java:178)
    ... 60 more
    Caused by: java.io.FileNotFoundException: /usr/sap/***/JC**/j2ee/cluster/server1/E:/WSDL FILE/FolderName/wsdlname.wsdl (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:69)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:156)
    at java.net.URL.openStream(URL.java:913)
    at com.sap.engine.lib.xml.parser.AbstractXMLParser.parse(AbstractXMLParser.java:201)
    at com.sap.engine.lib.xml.parser.AbstractXMLParser.parse(AbstractXMLParser.java:263)
    at com.sap.engine.lib.xml.parser.Parser.parse_DTDValidation(Parser.java:260)
    at com.sap.engine.lib.xml.parser.Parser.parse(Parser.java:271)
    at com.sap.engine.lib.xml.parser.DOMParser.parse(DOMParser.java:101)
    at com.sap.engine.lib.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:127)
    at com.sap.engine.services.webservices.wsdl.WSDLDOMLoader.loadDOMDocument(WSDLDOMLoader.java:1023)
    ... 62 more
    Regards
    Govardan

    im using 7.01 and here we have options to use No Logical Destinations , but now i created destinations at visual admin at Server>Services>Web Service Security>WebService Clients>Sap.com-->Dynamic WS Proxies., as WS_METADATA_DEST and WS_MODELDATA_DEST     and have filled in other details too like url  , user name , password etc
    now im getting another error like as shown below please help
    com.****.wsdlwdj.applicaiton.WsdlApp
    [EXCEPTION]
    com.sap.tc.webdynpro.model.webservice.exception.WSModelRuntimeException: Exception on creation of service metadata for WS metadata destination 'WS_METADATA_DEST' and WS interface '{http://****.com/****}MIOS_Matrix***********'. One possible reason is that the metadata destination 'WS_METADATA_DEST' has not been properly configured; check configuration.
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getOrCreateWsrService(WSModelInfo.java:440)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.readOperationsFromWSDL(WSModelInfo.java:372)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.importMetadataInternal(WSModelInfo.java:342)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.importMetadata(WSModelInfo.java:326)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo$Cache.getModelInfo(WSModelInfo.java:199)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getModelInfoFromCacheOrCreate(WSModelInfo.java:1035)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getModelInfoFromCacheOrCreate(WSModelInfo.java:248)
    at com.sap.tc.webdynpro.model.webservice.gci.WSTypedModel.<init>(WSTypedModel.java:41)
    at com.****.wsdlwdj.model.test.TestModel.<init>(TestModel.java:51)
    at com.****.wsdlwdj.comp.VcWsdlComponent.matrixAuthExecut(VcWsdlComponent.java:448)
    at com.****.wsdlwdj.comp.wdp.InternalVcWsdlComponent.matrixAuthExecut(InternalVcWsdlComponent.java:280)
    at com.****.wsdlwdj.comp.VcWsdlComponent.wdDoInit(VcWsdlComponent.java:132)
    at com.****.wsdlwdj.comp.wdp.InternalVcWsdlComponent.wdDoInit(InternalVcWsdlComponent.java:225)
    at com.sap.tc.webdynpro.progmodel.generation.DelegatingComponent.doInit(DelegatingComponent.java:108)
    at com.sap.tc.webdynpro.progmodel.controller.Controller.initController(Controller.java:215)
    at com.sap.tc.webdynpro.progmodel.controller.Controller.init(Controller.java:200)
    at com.sap.tc.webdynpro.clientserver.cal.ClientComponent.init(ClientComponent.java:430)
    at com.sap.tc.webdynpro.clientserver.cal.ClientApplication.init(ClientApplication.java:362)
    at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.initApplication(ApplicationSession.java:783)
    at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:303)
    at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessingStandalone(ClientSession.java:741)
    at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:694)
    at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:253)
    at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:185)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doGet(DispatcherServlet.java:46)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.sap.engine.services.servlets_jsp.server.runtime.RequestDispatcherImpl.doWork(RequestDispatcherImpl.java:321)
    at com.sap.engine.services.servlets_jsp.server.runtime.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:377)
    at com.sap.tc.webdynpro.clientserver.session.RequestManager.setSpnegoParameter(RequestManager.java:963)
    at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:157)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
    at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doGet(DispatcherServlet.java:46)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
    at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:386)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:364)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:1064)
    at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:265)
    at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
    at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:175)
    at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
    at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
    at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:104)
    at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:176)
    Caused by: com.sap.engine.services.webservices.espbase.discovery.BaseIOException: Invalid Response Code 500 while accessing URL: http://devpid:8000/sap/xi/engine?type=entry&version=3.0&Sender.Service=BS_****_PORTAL&Interface=http%3A%2F%2F****.com%2Fbank_report%5EMIOS_Authorizers_List_Portal&sap-user=xi_portal&sap-password=****1234. Response Message: Empty HTTP request received. Content Type: text/xml. Body Content: <SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP:Header>
    </SOAP:Header>
    <SOAP:Body>
    <SOAP:Fault xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>SOAP:Client</faultcode><faultstring>Empty HTTP request received</faultstring><faultactor>http://sap.com/xi/XI/Message/30</faultactor><detail><SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1"><SAP:Category>XIProtocol</SAP:Category><SAP:Code area="MESSAGE">EMPTY_HTTP_REQUEST_RECEIVED</SAP:Code><SAP:P1/><SAP:P2/><SAP:P3/><SAP:P4/><SAP:AdditionalText/><SAP:ApplicationFaultMessage namespace=""/><SAP:Stack>Empty HTTP query received; message processing not possible
    </SAP:Stack></SAP:Error></detail></SOAP:Fault>
    </SOAP:Body>
    </SOAP:Envelope>
    at com.sap.engine.services.webservices.server.management.discovery.DestinationsResolver.resolveURL(DestinationsResolver.java:246)
    at com.sap.engine.services.webservices.server.management.discovery.DestinationsResolver.resolveEntity(DestinationsResolver.java:130)
    at com.sap.engine.services.webservices.espbase.query.WSQueryImpl.initialize(WSQueryImpl.java:184)
    at com.sap.engine.services.webservices.espbase.query.WSQueryImpl.findWSInterfaces(WSQueryImpl.java:151)
    at com.sap.engine.services.webservices.server.management.discovery.ServiceDiscoveryImpl.getWSDLUrl(ServiceDiscoveryImpl.java:71)
    at com.sap.engine.services.webservices.espbase.client.dynamic.GenericServiceFactory.createService(GenericServiceFactory.java:134)
    at com.sap.tc.webdynpro.model.webservice.metadata.WSModelInfo.getOrCreateWsrService(WSModelInfo.java:429)
    ... 49 more

  • Problems with file uploading servlet, the form action doesnt capture url

    Hi, i have one problem. I am working on a project , i have created a servlet that takes uploaded files and processses them and links them back to user to download. The servlet works perfectly from my computer, I am using apache-tomcat-6.0.16 and java 1.6 , I have two forms called encrypt.html and decrypt.html, I will post both of them, now the problem is when somebody access it on the internet while i am running apache, they get a connection was reset on a firefox browser and same stuff on Internet Explorer.
    i have checked my server logs and saw nothing unusual there, So please if you can help me, it is my project.
    I am pasting html file and error message that other users where getting remotely.
    <html>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <title>Stego Form</title>
    <link rel='STYLESHEET' type='text/css' href='encrypt.css'>
    </head>
    <body>
    <center>
    <form name='encrypt' enctype='multipart/form-data' method='POST' action='http://localhost:8080/examples/temp2
    ' accept-charset='UTF-8'>
    <input type='hidden' name='sfm_form_submitted' value='yes'>
    </input>
    <input type='hidden' name='eord' value='e'>
    <select name='encryption' size='1'>
             <option value='Select an encryption' selected>
             Select an encryption
             </option>
             <option value='DES'>
             DES
             </option>
             <option value='Tripple DES'>
             Tripple DES
             </option>
    </select>
             <input type='file' name='overt' size='20'>
             <input type='file' name='covert' size='20'>
             <input type='submit' name='submit' value='Submit'>
    </form>
    </center>
    </body>
    </html>so it works for me even if i access the page with my ip , but for others it doesnt work,
    now the user got this xhtml page that i will show, i cant find attach button so i am pasting here.
    here is the servlet coding
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    public class temp2 extends HttpServlet
        FileInputStream fin;
        String filenames[] = new String[2],fieldname,fieldval;
        String keyfile,IVfile;
        String names[] = new String[2];
        public temp2()
            super();
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            String eord="";
            List lst = null;
            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (!isMultiPart) // check whether the post request is actually multipart
                System.out.println("ERROR NOT MULTIPART");
                System.exit(0);
            DiskFileItemFactory fif = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(fif);
            sfu.setSizeMax(10000000);
            try {  lst = sfu.parseRequest(request);  }
            catch (FileUploadException ex)
            { System.out.println("ERROR IN PARSING FILES" + ex); System.exit(0);  }
            if(lst.isEmpty())  // check whether request is empty
                System.out.println("ERROR LIST SIZE NOT GOOD : " + lst.size());
                System.exit(0);
            Iterator x = lst.iterator();
            int i = 0;
            FileItem f = (FileItem)x.next();
            f = (FileItem)x.next();
            System.out.println(f.getFieldName());
            if(f.getFieldName().equalsIgnoreCase("eord")) // check hidden field to know the case : encrypt or decrypt
                eord = f.getString();
                System.out.println(f.getString());
            else // if it is not first field exit
                System.out.println("Invalid FORM");
                System.exit(0);
            f = (FileItem)x.next(); // next field
            if(f.getFieldName().equalsIgnoreCase("encryption")) // type of encryption des / tdes
                fieldname = f.getFieldName();
                fieldval = f.getString();
                System.out.println(f.getString());
            if(eord.equalsIgnoreCase("e")) // if it is encryption form only file required
                while(x.hasNext())
                    f = (FileItem)x.next();
                    if(!f.isFormField())
                        int check = f.getName().lastIndexOf(File.separator);
                        System.out.println(File.separator);
                        if(check==-1)
                            System.out.println(f.getName());
                            System.out.println("Unsupported browser : " + check);
                            System.exit(0);
                        File ff = new File("e:\\apache\\webapps\\temp\\"+f.getName().substring(check));
                        names[i] = ff.getName(); // original file names
                        try
                            f.write(ff);
                            filenames[i] = ff.getAbsolutePath();
                        // renamed    
                            ff.deleteOnExit();
                        }catch(Exception e) {System.out.println("Error writing file"+ ff.getAbsolutePath()); System.exit(0);}
                        i++;
                    try { System.in.read(); } catch(Exception e) {}
                }// endwhile
                if(fieldval.equalsIgnoreCase("DES"))
                    System.out.println("DES 1"+filenames[1]);
                    javades o = new javades(filenames[1]); // the file to be encrypted   
                    filenames[1] = "e:\\apache\\webapps\\temp\\files\\" + names[1];
                    System.out.println("should be original" + filenames[1]);
                else if(fieldval.equalsIgnoreCase("Tripple DES"))
                    javatdes o = new javatdes(filenames[1]);
                    filenames[1] = "e:\\apache\\webapps\\temp\\files\\" + names[1];
                    System.out.println(filenames[1]);
                System.out.println("Calling stego");
                filenames[0] = "e:\\apache\\webapps\\temp\\" + names[0];
                System.out.println("file 1 "+ filenames[0]);
                System.out.println("file 2"+ filenames[1]);
                try { System.in.read(); } catch(Exception e) {}
                stego s = new stego(filenames[0],filenames[1]);
                System.out.println("mainext " + s.mainext);
                // encryption done, and new files are loaded, now lets hide
                if(s.mainext.equalsIgnoreCase("wav"))
                    s.encodewav();
                    System.out.println("Encoded wave");
                else if(s.mainext.equalsIgnoreCase("bmp"))
                    System.out.println("Encoded bmp");
                    s.encodebmp();
                System.out.println("done !");
                PrintWriter pr = response.getWriter();
                pr.println("Greetings , Your work is done and saved, now download the following files");
                pr.println("The secret key file is needed for getting back your hidden file, so download that too");
                pr.write("<a href=\"/temp/files/IV.txt\">click here</a>");
                pr.write("<br/><a href=\"/temp/files/key.txt\">click here</a>");
                pr.write("<br/><a href=\"/temp/files/"+names[0]+"\">click here</a>");
                return;
            // if it is decryption case
            else if(eord.equalsIgnoreCase("d"))
                while(x.hasNext())
                    f = (FileItem)x.next();
                    if(!f.isFormField())
                        int check = f.getName().lastIndexOf(File.separator);
                        System.out.println(File.separator);
                        if(check==-1)
                            System.out.println(f.getName());
                            System.out.println("Unsupported browser : " + check);
                            System.exit(0);
                        File ff = new File("e:\\apache\\webapps\\temp\\"+f.getName().substring(check));
    // else if ladder to store paths of stegofile keyfile and IVfile                   
                        if(f.getFieldName().equalsIgnoreCase("stegofile"))
                            filenames[0] = ff.getAbsolutePath();
                        else if(f.getFieldName().equalsIgnoreCase("keyfile"))
                            keyfile = ff.getAbsolutePath();
                        else if(f.getFieldName().equalsIgnoreCase("IVfile"))
                            IVfile = ff.getAbsolutePath();
                        try
                            f.write(ff); // writes whole file at once
                        }catch(Exception e) {System.out.println("Error writing file"); System.exit(0);}
                }// endwhile
                System.out.println("Calling stego");
                System.out.println("file 1 "+ filenames[0]);
                stego s = new stego(filenames[0]);
                System.out.println("mainext " + s.mainext);
                if(s.mainext.equalsIgnoreCase("wav"))
                    s.decodewav();
                    System.out.println("Encoded wave");
                else if(s.mainext.equalsIgnoreCase("bmp"))
                    s.decodebmp();
                    System.out.println("Encoded bmp");
                System.out.println("done !");
                ////// hidden file has been retrieved , now lets decrypt it
                System.out.println("ext " + s.ext);
                filenames[0] = "e:\\apache\\webapps\\temp\\"+s.filename;
                System.out.println(filenames[0]);
                System.out.println(keyfile);
                System.out.println(IVfile);
                if(fieldval.equalsIgnoreCase("DES"))
                    javades o = new javades(filenames[0],keyfile,IVfile); // the file to be encrypted   
                    filenames[0] = "e:\\apache\\webapps\\temp\\" + ( new File(filenames[0]).getName());
                    System.out.println("should be original" + filenames[0]);
                else if(fieldval.equalsIgnoreCase("Tripple DES"))
                    javatdes o = new javatdes(filenames[0],keyfile,IVfile);
                    filenames[0] = "e:\\apache\\webapps\\temp\\" + ( new File(filenames[0]).getName());
                    System.out.println(filenames[0]);
                PrintWriter pr = response.getWriter();
                pr.write("Greetings, you have successfully retrieved your hidden file, now download it from here <br>");
                pr.write("<a href=\"http://localhost:8080/temp/files/" + (new File(filenames[0]).getName())+"\">Click here</a>");
    }and here is the xhtml file the user receives, whe he clicks the submit button,
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html [
      <!ENTITY % htmlDTD
        PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "DTD/xhtml1-strict.dtd">
      %htmlDTD;
      <!ENTITY % netErrorDTD
        SYSTEM "chrome://global/locale/netError.dtd">
      %netErrorDTD;
    <!ENTITY loadError.label "Problem loading page">
    <!ENTITY retry.label "Try Again">
    <!-- Specific error messages -->
    <!ENTITY connectionFailure.title "Unable to connect">
    <!ENTITY connectionFailure.longDesc "&sharedLongDesc;">
    <!ENTITY deniedPortAccess.title "This address is restricted">
    <!ENTITY deniedPortAccess.longDesc "">
    <!ENTITY dnsNotFound.title "Server not found">
    <!ENTITY dnsNotFound.longDesc "
    <ul>
      <li>Check the address for typing errors such as
        <strong>ww</strong>.example.com instead of
        <strong>www</strong>.example.com</li>
      <li>If you are unable to load any pages, check your computer's network
        connection.</li>
      <li>If your computer or network is protected by a firewall or proxy, make sure
        that &brandShortName; is permitted to access the Web.</li>
    </ul>
    ">
    <!ENTITY fileNotFound.title "File not found">
    <!ENTITY fileNotFound.longDesc "
    <ul>
      <li>Check the file name for capitalization or other typing errors.</li>
      <li>Check to see if the file was moved, renamed or deleted.</li>
    </ul>
    ">
    <!ENTITY generic.title "Oops.">
    <!ENTITY generic.longDesc "
    <p>&brandShortName; can't load this page for some reason.</p>
    ">
    <!ENTITY malformedURI.title "The address isn't valid">
    <!ENTITY malformedURI.longDesc "
    <ul>
      <li>Web addresses are usually written like
        <strong>http://www.example.com/</strong></li>
      <li>Make sure that you're using forward slashes (i.e.
        <strong>/</strong>).</li>
    </ul>
    ">
    <!ENTITY netInterrupt.title "The connection was interrupted">
    <!ENTITY netInterrupt.longDesc "&sharedLongDesc;">
    <!ENTITY netOffline.title "Offline mode">
    <!ENTITY netOffline.longDesc "
    <ul>
      <li>Uncheck "Work Offline" in the File menu, then try again.</li>
    </ul>
    ">
    <!ENTITY netReset.title "The connection was reset">
    <!ENTITY netReset.longDesc "&sharedLongDesc;">
    <!ENTITY netTimeout.title "The connection has timed out">
    <!ENTITY netTimeout.longDesc "&sharedLongDesc;">
    <!ENTITY protocolNotFound.title "The address wasn't understood">
    <!ENTITY protocolNotFound.longDesc "
    <ul>
      <li>You might need to install other software to open this address.</li>
    </ul>
    ">
    <!ENTITY proxyConnectFailure.title "The proxy server is refusing connections">
    <!ENTITY proxyConnectFailure.longDesc "
    <ul>
      <li>Check the proxy settings to make sure that they are correct.</li>
      <li>Contact your network administrator to make sure the proxy server is
        working.</li>
    </ul>
    ">
    <!ENTITY proxyResolveFailure.title "Unable to find the proxy server">
    <!ENTITY proxyResolveFailure.longDesc "
    <ul>
      <li>Check the proxy settings to make sure that they are correct.</li>
      <li>Check to make sure your computer has a working network connection.</li>
      <li>If your computer or network is protected by a firewall or proxy, make sure
        that &brandShortName; is permitted to access the Web.</li>
    </ul>
    ">
    <!ENTITY redirectLoop.title "The page isn't redirecting properly">
    <!ENTITY redirectLoop.longDesc "
    <ul>
      <li>This problem can sometimes be caused by disabling or refusing to accept
        cookies.</li>
    </ul>
    ">
    <!ENTITY unknownSocketType.title "Unexpected response from server">
    <!ENTITY unknownSocketType.longDesc "
    <ul>
      <li>Check to make sure your system has the Personal Security Manager
        installed.</li>
      <li>This might be due to a non-standard configuration on the server.</li>
    </ul>
    ">
    <!ENTITY sharedLongDesc "
    <ul>
      <li>The site could be temporarily unavailable or too busy. Try again in a few
        moments.</li>
      <li>If you are unable to load any pages, check your computer's network
        connection.</li>
      <li>If your computer or network is protected by a firewall or proxy, make sure
        that &brandShortName; is permitted to access the Web.</li>
    </ul>
    ">
      <!ENTITY % globalDTD
        SYSTEM "chrome://global/locale/global.dtd">
      %globalDTD;
    ]>
    <!-- ***** BEGIN LICENSE BLOCK *****
       - Version: MPL 1.1/GPL 2.0/LGPL 2.1
       - The contents of this file are subject to the Mozilla Public License Version
       - 1.1 (the "License"); you may not use this file except in compliance with
       - the License. You may obtain a copy of the License at
       - http://www.mozilla.org/MPL/
       - Software distributed under the License is distributed on an "AS IS" basis,
       - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
       - for the specific language governing rights and limitations under the
       - License.
       - The Original Code is mozilla.org code.
       - The Initial Developer of the Original Code is
       - Netscape Communications Corporation.
       - Portions created by the Initial Developer are Copyright (C) 1998
       - the Initial Developer. All Rights Reserved.
       - Contributor(s):
       -   Adam Lock <[email protected]>
       -   William R. Price <[email protected]>
       -   Henrik Skupin <[email protected]>
       -   Jeff Walden <[email protected]>
       - Alternatively, the contents of this file may be used under the terms of
       - either the GNU General Public License Version 2 or later (the "GPL"), or
       - the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
       - in which case the provisions of the GPL or the LGPL are applicable instead
       - of those above. If you wish to allow use of your version of this file only
       - under the terms of either the GPL or the LGPL, and not to allow others to
       - use your version of this file under the terms of the MPL, indicate your
       - decision by deleting the provisions above and replace them with the notice
       - and other provisions required by the LGPL or the GPL. If you do not delete
       - the provisions above, a recipient may use your version of this file under
       - the terms of any one of the MPL, the GPL or the LGPL.
       - ***** END LICENSE BLOCK ***** -->
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>Problem loading page</title>
        <link rel="stylesheet" href="temp2_files/netError.css" type="text/css" media="all"/>
        <!-- XXX this needs to be themeable -->
        <link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAICSURBVHjaYvz//z8DJQAggJhwiDPvnmlzc2aR0O+JGezt+AwACCCsBhxfYhn59N41FWtXIxZOLu70niRGXVwGAAQQNgNYHj96O8HaWYdJW5ubwd4/mI2Ng7sblwEAAYRhwMm1URk/vn4SUNWVYGD8+YZBXZOZm5OLzRjoCmNsBgAEEKoBN82Y7l851GLrqMjM8Oc7A8O/3wwMP54wuAQFCXNycUzGZgBAAKEYcOaKZO2/f//5FbUVgBrfMoRVcgHpNwyKGjKMXDwCan0prFboBgAEELIBzDcvXyy2cVZhYPj9GWj7H4jo/38MDJ9OMDj7O/KzsjH3oxsAEEBwA/bNNipiZf7FI6cqwcDw8x2qqp8fGORUpVn4BEXlgGHhhCwFEEAwA9gfP3hdZ+Oizcjw+wvCdjgAuuLrFQbXIH9hTm7uqcgyAAEENuD4ctcebm5mbikFYRTbV7V/Q6j88Z5BSuY7q4CQgAjQFR4wYYAAAhtw89L5ZFsnRaDtn4CW/YXrAQcisit+PGVwDgrnZ2NnnwATBQggpsNLvGYLCAmxi8tLARWg+h3FBVBXSEj/ZZWQkRcCuiIQJAQQQCyvnj5KMDTkZ2JgYmRg4FchnHv+vmEwttLmeXT3VjKQtx4ggFgk5TXebV63UfT3ijOMxOZAVlZWdiB1EMQGCCBGSrMzQIABAFR3kRM3KggZAAAAAElFTkSuQmCC"/>
        <script type="application/x-javascript"><![CDATA[
          // Error url MUST be formatted like this:
          //   moz-neterror:page?e=error&u=url&d=desc
          // Note that this file uses document.documentURI to get
          // the URL (with the format from above). This is because
          // document.location.href gets the current URI off the docshell,
          // which is the URL displayed in the location bar, i.e.
          // the URI that the user attempted to load.
          function getErrorCode()
            var url = document.documentURI;
            var error = url.search(/e\=/);
            var duffUrl = url.search(/\&u\=/);
            return decodeURIComponent(url.slice(error + 2, duffUrl));
          function getDescription()
            var url = document.documentURI;
            var desc = url.search(/d\=/);
            // desc == -1 if not found; if so, return an empty string
            // instead of what would turn out to be portions of the URI
            if (desc == -1) return "";
            return decodeURIComponent(url.slice(desc + 2));
          function retryThis()
            // Session history has the URL of the page that failed
            // to load, not the one of the error page. So, just call
            // reload(), which will also repost POST data correctly.
            try {
              location.reload();
            } catch (e) {
              // We probably tried to reload a URI that caused an exception to
              // occur;  e.g. a non-existent file.
          function initPage()
            var err = getErrorCode();
            // if it's an unknown error or there's no title or description
            // defined, get the generic message
            var errTitle = document.getElementById("et_" + err);
            var errDesc  = document.getElementById("ed_" + err);
            if (!errTitle || !errDesc)
              errTitle = document.getElementById("et_generic");
              errDesc  = document.getElementById("ed_generic");
            var title = document.getElementById("errorTitleText");
            if (title)
              title.parentNode.replaceChild(errTitle, title);
              // change id to the replaced child's id so styling works
              errTitle.id = "errorTitleText";
            var sd = document.getElementById("errorShortDescText");
            if (sd)
              sd.textContent = getDescription();
            var ld = document.getElementById("errorLongDesc");
            if (ld)
              ld.parentNode.replaceChild(errDesc, ld);
              // change id to the replaced child's id so styling works
              errDesc.id = "errorLongDesc";
            // remove undisplayed errors to avoid bug 39098
            var errContainer = document.getElementById("errorContainer");
            errContainer.parentNode.removeChild(errContainer);
        ]]></script>
      </head>
      <body dir="ltr">
        <!-- ERROR ITEM CONTAINER (removed during loading to avoid bug 39098) -->
        <!-- PAGE CONTAINER (for styling purposes only) -->
        <div id="errorPageContainer">
          <!-- Error Title -->
          <div id="errorTitle">
            <h1 id="errorTitleText">The connection was reset</h1>
          </div>
          <!-- LONG CONTENT (the section most likely to require scrolling) -->
          <div id="errorLongContent">
            <!-- Short Description -->
            <div id="errorShortDesc">
              <p id="errorShortDescText">The connection to the server was reset while the page was loading.</p>
            </div>
            <!-- Long Description (Note: See netError.dtd for used XHTML tags) -->
            <div id="errorLongDesc">
    <ul>
      <li>The site could be temporarily unavailable or too busy. Try again in a few
        moments.</li>
      <li>If you are unable to load any pages, check your computer's network
        connection.</li>
      <li>If your computer or network is protected by a firewall or proxy, make sure
        that Firefox is permitted to access the Web.</li>
    </ul>
    </div>
          </div>
          <!-- Retry Button -->
          <xul:button xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="errorTryAgain" label="Try Again" oncommand="retryThis();"/>
        </div>
        <!--
        - Note: It is important to run the script this way, instead of using
        - an onload handler. This is because error pages are loaded as
        - LOAD_BACKGROUND, which means that onload handlers will not be executed.
        -->
        <script type="application/x-javascript">initPage();</script>
      </body>
    </html>thank you for your prompt reply in advance,
    Regards,
    Mihir Pandya

    Hi, thank you for your replies, I found out few things about my servlet, and its portability
    and i have few questions, although i marked this topic as answered i guess its ok to post
    I am using javax.servlet.context.tempdir to store my files in that servletcontext temporary directory. But i dont know how to give hyperlink
    of the modified files to the user for them to download the modified files.
    What i am using to get the tempdir i will paste
    File baseurl = (File)this.getServletContext().getAttribute("javax.servlet.context.tempdir");
    System.out.println(baseurl);
    baseurl = new File(baseurl.getAbsolutePath()+File.separator+"temp"+File.separator+"files");
    baseurl.mkdirs();so i am storing my files in that temp/files folder and the servlet processes them and modifies them, then how to present them as
    links to the user for download ?
    and as the servlet is multithreaded by nature, if my servlet gets 2 different requests with same file names, i guess one of them will be overwritten
    And i want to create unique directory for each request made to the servlet , so file names dont clash.
    one another thing is that i want my servlet to be executed by my <form action> only, I dont want the user to simply type url and trigger the servlet
    Reply A.S.A.P. please..
    Thanks and regards,
    Mihir Pandya

  • Get file path name for an given FileInputStream

    It sounds wired, but I do want to see if it is possible. Say we have a FileInputStream fis, which has been instantiated and valid. I would like to get the File associated with this FileInputStream. Is this possible and how?
    Thanks.

    It sounds wired, but I do want to see if it is
    possible. Say we have a FileInputStream fis, which
    has been instantiated and valid. I would like to get
    the File associated with this FileInputStream. Is
    this possible and how?
    Thanks.A FileInputStream may not be associated with a "disk file" at all. From javadocs, FileInputStream can be created from a [url http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileInputStream.html#FileInputStream(java.io.FileDescriptor)]FileDescriptor, which can represent [url http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileDescriptor.html#skip-navbar_top]an open file, an open socket, or another source or sink of bytes.

  • Download File by url in another server? (Content-Disposition","attachment)

    Can the file be downloaded by a url in another server?
    ie.
    Server A: JSP program
    Server B: filepath + filename = "http://xxx.com/xx/x.doc"
    e.g.
        response.setContentType("APPLICATION/OCTET-STREAM");
           response.setHeader("Content-disposition", "inline" );            
           response.setHeader("Content-Disposition","attachment; filename=\""+ fn.trim() + "\"");     
              java.io.FileInputStream fileInputStream =new java.io.FileInputStream(filepath+filename);
              int i;          
              while ((i=fileInputStream.read()) != -1) {
                      out.write(i);
              fileInputStream.close();
              out.close();     

    I tried this but it doesn't work. In the report column it shows up as Download" >_ .
    This seems to indicate that the href code is not being interpreted correctly.
    Following is exactly what I have in the URL field:
    <a href="#OWNER#.DOWNLOAD_MY_FILE?p_file=#NOTIFICATION_SEQ_ID#&v_type=SUMMARY">Download</a>Yes, I have granted execute rights to the procedure.
    Thanks,
    Dale

  • Url char-encoding problem

    I am connecting to a web-server. The URL has Japanese characters embedded in it.
    When run from NetBeans 6.8 everything works ok.
    When run from the shell, the server appears to not understand the Japanese characters. For example, if the Japanese characters represent a user name, none of the names are ever understood.
    Default charset when run from IDE is "UTF-8".
    Default when run from shell: "Cp1252".
    I don't want a systemic solution [for example a command-line switch, or config file setting]. I want to control every IO stream's encoding manually.
    This is the test that comes closest to what I think should work:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStreamWriter baosStreamWrt = new OutputStreamWriter(baos, utf8.newEncoder());
    BufferedWriter bufWrt = new BufferedWriter(baosStreamWrt);
    bufWrt.write(url_with_jp_characters);
    bufWrt.flush();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    InputStreamReader inStreamRdr = new InputStreamReader(bais, utf8.newDecoder());
    BufferedReader bufRdr = new BufferedReader(inStreamRdr);
    String faulty_url = bufRdr.readLine();
    URL webpage = new URL(faulty_url);
    URLConnection urlConn = webpage.openConnection();
    BufferedReader webIn = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), utf8.newDecoder()));
    BufferedWriter response = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/tmp/dump.txt"), utf8.newEncoder()));
    response.("checking the the url: ")
    response.write(faulty_url);
    response.newLine();
    while(true) {
      String webLine = webIn.readLine();
      if(webLine == null) { break; }
      response.write(webLine);
      response.newLine();
    response.close();
    webIn.close();
    ....Inspecting the response from the server in the file "/tmp/dump.txt":
    (1) the file is formatted "UTF-8".
    (2) the url, written in the first line of the file, is valid and a cut/paste into a browser works correctly.
    (3) many correctly formed Japanese words are in the response from the server that is saying: "I have no idea how to understand/(decode?) the user name you sent me in the URL."
    At this point I have a choice:
    (1) I don't understand the source of the problem?
    (2) I need to keep banging away at trying to get the url correctly encoded.
    Finally, how can I debug this???
    (1) It works in the IDE, so I don't have those debugging tools.
    (2) My terminal cannot display asian characters.
    (3) Writing output to files involves another encoder for the FileWriter which taints everything in the file.
    (4) I don't have a webserver to act as a surrogate for the real one.
    thanks.

    Kayaman wrote:
    rerf wrote:
    And I don't know why NetBeans allowed me to get around not using this command.Because of the default charset of UTF-8 that's set in Netbeans.I see that, but something more subtle was happeneing I think. I still don't fully understand. Here is my best explanation. Exact code:
    ....for(File f : files) {
      BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f), utf8.newDecoder()));
      String jpName = in.readLine().split(";")[0];
      String jpNameForUrlUsage = URLEncoder.encode(jpName, "UTF-8");
      String dumpFileName = (outputDir + f.getName().split(".txt")[0] + "-dump.txt");
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dumpFileName), utf8.newEncoder()));
      URL url = new URL("http://www.abc.cp.jp?name=" + jpNameForUrlUsage);
      URLConnection urlConn = url.openConnection();
    }....In my first post, I formed the complete url, then encoded it to utf-8 using ByteArray[Input / Output]Streams. But, my understanding is that you can't just encode Japanese characters to utf-8 and then append them to a url. A special method call is needed to transform the Japanese characters into something understandable by the URL (and its not as simple as just encoding the characters to utf-8). After posting, I actually made an effort to read all of javadoc for java.net.URL:
    java.net.URL
    The URL class does not itself encode or decode any URL components according to the escaping mechanism defined in RFC2396. It is the responsibility of the caller to encode any fields, which need to be escaped prior to calling URL, and also to decode any escaped fields, that are returned from URL. Furthermore, because URL has no knowledge of URL escaping, it does not recognise equivalence between the encoded or decoded form of the same URL. For example, the two URLs:
    http://foo.com/hello world/ and http://foo.com/hello%20world
    would be considered not equal to each other.
    Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().....
    Then, it all made sense. I had already diagnosed that it was just the Japanese character part of the URL that caused the failure. And I remember reading that the Chinese were upset that they could not use asian characters in URLs. So, even though in my browser it looks like a Japanese character is in it, its really not. Chrome browser is doing some transform from what I see in my browser URL and what the actual URL is. That is why cutting/pasting the url I was forming in Java into the browser is not a good representation of what is going on. Chrome, behind the scenes does what the URLEncoder class does.
    Yet, I could very easily be wrong:
    On the one hand NetBeans worked, and the shell did not. The relevant difference being default charset.
    But on the other hand, in my initial post, I completely encoded that url into utf-8 using ByteArray[Input / Output]Streams. I am no expert on character encodings, but if the url I created in the initial posting is not utf-8 encoded then I need a few pointers on how to character encode.
    final thought:
    I can't just encode a Japanese character to UTF-8, append it to a URL, and expect it to work. A browser can make it look that way so its deceiving. That is why there is the class URLEncoder. I don't understand why NetBeans appears to invoke it for me without my knowledge. And maybe its not. Having the default charset as utf-8 might obviate the need for a URLEncoder() call (but I don't see why it should).

  • Need HELP! Opening a PDF file from different URL

    I have a application that links to viewpdf.class. This class file will go to the FTP where the pdf file is located and open it. How do i do this using java? Here is what I have.. .i'm stuck
    URL url = new URL("ftp://user01:[email protected]/"+ folder_name +"README.pdf;type=i");
    URLConnection urlc = url.openConnection();
    InputStream is = urlc.getInputStream();thanks Tony
    here is how it looks like if it is on the local host.
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class viewpdf extends HttpServlet
        private ResourceBundle rb;
        public viewpdf()
            rb = ResourceBundle.getBundle("LocalStrings");
        public static void streamCopy(FileInputStream fileInputStream, ServletOutputStream servletOutputStream)
            throws IOException
            if(fileInputStream == null || servletOutputStream == null)
                return;
            byte abyte0[] = new byte[8192];
            int i;
            synchronized(fileInputStream)
                synchronized(servletOutputStream)
                    while((i = fileInputStream.read(abyte0)) != -1)
                        servletOutputStream.write(abyte0, 0, i);
        public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException
            ServletOutputStream servletOutputStream;
            String filename;
            String output;
            FileInputStream fileInputStream;
            servletOutputStream = res.getOutputStream();
            res.setContentType("application/pdf");
            ServletContext servletcontext = getServletContext();
            filename = req.getParameter("file");
            String folder_code = req.getParameter("fold");
            try{
                filename = servletcontext.getRealPath(rb.getString("file_location")) + "/" + fold + "/" + file;
            fileInputStream = null;
            fileInputStream = new FileInputStream(file);
            streamCopy(fileInputStream, servletOutputStream);
            catch(FileNotFoundException e)
            filename = servletcontext.getRealPath(rb.getString("file_location")) + "/filenotfound.pdf";
            fileInputStream = null;
            fileInputStream = new FileInputStream(file);
            streamCopy(fileInputStream, servletOutputStream);
    }

    That servlet already is Java. And the servlet code isn't what "opens" the PDF, it's the browser that sends the request that does that. I'm assuming that when you say "open it" you mean to start up an instance of Adobe Acrobat and ask it to display the document.

Maybe you are looking for

  • HT201471 Does anyone know if video comes out of the headphone jack like the Itouch does on a Ipad3?

    I was wondering if the video out put comes out of the headphone jack on a Ipad3 like it does on a Itouch?

  • POS XI POSDM integration

    Hi Experts,                      I am into POS XI POSDM integration . My queries are,    1. Is there any specific forum in XI where I can get in touch with those, who have undertaken the following type of integtarion.     2. My scenerio is File 2 XI

  • How to Select Data from different Tables Using Linq

    Hi, I have two different tables, I just want to collect data from tables using Linq to SQL Queries. The tables looks like This  ID Name ImageUrl  Other Table is ID EmpID CheckInTime CheckOutTime  What I want to Collect data from CheckInTime and want

  • Another BT-WiFi login issue

    Hi, Jeez this is a muddle, what with BT-Wifi, Openzone, FON and a multitude of web pages. In short I cannot login to BT-Wifi. I rang 0800 0223322 and took the option to 'Hold' but it just goes 'Clunk' So...this is what I know. I can login to MyBT usi

  • BW 7.3 ,can we extract delta data from mutiproviders using OHD

    Hi Gurus, My requirement is to extract the delta data from multiple infocube (more than one IC) using open hub destination to third party system. We thought of implementing BW 7.3 so that we can extract delta data from multiproviders instead of cubes