Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'java.io.FileNotFoundException: at sun.net.www.protocol.http.HttpURLConnection.getInputStream0 (Unknown Source)' error?

Tags:

java

jnlp

I'm trying to convert an applet to a Java application. So I generated the JNLP file and passed all arguments needed with POST method. As soon as I launch the application from JNLP, I get this error:

java.io.FileNotFoundException: http://PATH_TO_A_DIRECTORY/reopen.php
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.access$200(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$9.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$9.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessController.doPrivilegedWithCombiner(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at maarchcm.MaarchCM.sendHttpRequest(MaarchCM.java:368)
    at maarchcm.MaarchCM.editObject(MaarchCM.java:261)
    at maarchcm.MaarchCM.test(MaarchCM.java:106)
    at maarchcm.MaarchCM.main(MaarchCM.java:188)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javaws.Launcher.executeApplication(Unknown Source)
    at com.sun.javaws.Launcher.executeMainClass(Unknown Source)
    at com.sun.javaws.Launcher.doLaunchApp(Unknown Source)
    at com.sun.javaws.Launcher.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

The exception says that the file "reopen.php" is missing, but the path mentioned in the exception is wrong, and I don't call it in my code. This works fine when I launch it as an applet, but not as an application. I really don't know what can be the error in the code. Here is my code.

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import netscape.javascript.JSException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import netscape.javascript.JSObject;

public class MaarchCM extends JApplet {
    //INIT PARAMETERS
    protected String url;
    protected String objectType;
    protected String objectTable;
    protected String objectId;
    protected String userLocalDirTmp;
    protected String userMaarch;
    protected String userMaarchPwd;
    protected String psExecMode;

    protected String messageStatus;

    Hashtable app = new Hashtable();
    Hashtable messageResult = new Hashtable();

    //XML PARAMETERS
    protected String status;
    protected String appPath;
    protected String fileContent;
    protected String fileExtension;
    protected String error;
    protected String endMessage;
    protected String os;

    protected String fileContentTosend;

    public myLogger logger;

    public void init() throws JSException
    {
        System.out.println("----------BEGIN PARAMETERS----------");
        this.url = this.getParameter("url");
        this.objectType = this.getParameter("objectType");
        this.objectTable = this.getParameter("objectTable");
        this.objectId = this.getParameter("objectId");
        this.userMaarch = this.getParameter("userMaarch");
        this.userMaarchPwd = this.getParameter("userMaarchPwd");
        this.psExecMode = this.getParameter("psExecMode");

        System.out.println("URL : " + this.url);
        System.out.println("OBJECT TYPE : " + this.objectType);
        System.out.println("OBJECT TABLE : " + this.objectTable);
        System.out.println("OBJECT ID : " + this.objectId);
        System.out.println("USER MAARCH : " + this.userMaarch);
        System.out.println("PSEXEC MODE : " + this.psExecMode);

        System.out.println("----------END PARAMETERS----------");
        try {
            this.editObject();
            this.destroy();
            this.stop();
            System.exit(0);
        } catch (Exception ex) {
            Logger.getLogger(MaarchCM.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void test(String[] args)
    {
        System.out.println("----------TESTS----------");
        System.out.println("----------BEGIN PARAMETERS----------");
        this.url = args[0];
        this.objectType = args[1];
        this.objectTable = args[2];
        this.objectId = args[3];
        this.userMaarch = args[4];
        this.userMaarchPwd = args[5];
        this.psExecMode = args[6];

        System.out.println("URL : " + this.url);
        System.out.println("OBJECT TYPE : " + this.objectType);
        System.out.println("OBJECT TABLE : " + this.objectTable);
        System.out.println("OBJECT ID : " + this.objectId);
        System.out.println("USER MAARCH : " + this.userMaarch);
        System.out.println("USER MAARCHPWD : " + this.userMaarchPwd);
        System.out.println("PSEXEC MODE : " + this.psExecMode);

        System.out.println("----------END PARAMETERS----------");
        try {
            this.editObject();
        } catch (Exception ex) {
            Logger.getLogger(MaarchCM.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void parse_xml(InputStream flux_xml) throws SAXException, IOException, ParserConfigurationException
    {
        this.logger.log("----------BEGIN PARSE XML----------", Level.INFO);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(flux_xml);
        this.messageResult.clear();
        NodeList level_one_list = doc.getChildNodes();
        for (Integer i=0; i < level_one_list.getLength(); i++) {
            NodeList level_two_list = level_one_list.item(i).getChildNodes();
            if ("SUCCESS".equals(level_one_list.item(i).getNodeName())) {
                for(Integer j=0; j < level_one_list.item(i).getChildNodes().getLength(); j++ ) {
                    this.messageResult.put(level_two_list.item(j).getNodeName(),level_two_list.item(j).getTextContent());
                }
                this.messageStatus = "SUCCESS";
            } else if ("ERROR".equals(level_one_list.item(i).getNodeName()) ) {
                for(Integer j=0; j < level_one_list.item(i).getChildNodes().getLength(); j++ ) {
                    this.messageResult.put(level_two_list.item(j).getNodeName(),level_two_list.item(j).getTextContent());
                }
                this.messageStatus = "ERROR";
            }
        }
        this.logger.log("----------END PARSE XML----------", Level.INFO);
    }

    public void processReturn(Hashtable result) {
        Iterator itValue = result.values().iterator(); 
        Iterator itKey = result.keySet().iterator();
        while(itValue.hasNext()) {
            String value = (String)itValue.next();
            String key = (String)itKey.next();
            this.logger.log(key + " : " + value, Level.INFO);
            if ("STATUS".equals(key)) {
                this.status = value;
            }
            if ("OBJECT_TYPE".equals(key)) {
                this.objectType = value;
            }
            if ("OBJECT_TABLE".equals(key)) {
                this.objectTable = value;
            }
            if ("OBJECT_ID".equals(key)) {
                this.objectId = value;
            }
            if ("APP_PATH".equals(key)) {
                //this.appPath = value;
            }
            if ("FILE_CONTENT".equals(key)) {
                this.fileContent = value;
            }
            if ("FILE_EXTENSION".equals(key)) {
                this.fileExtension = value;
            }
            if ("ERROR".equals(key)) {
                this.error = value;
            }
            if ("END_MESSAGE".equals(key)) {
                this.endMessage = value;
            }
        }
        //send message error to Maarch if necessary
        if (!this.error.isEmpty()) {
            this.sendJsMessage(this.error.toString());
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try{
            System.out.println(args[0]);
            System.out.println(args[1]);
            System.out.println(args[2]);
            System.out.println(args[3]);
            System.out.println(args[4]);
            MaarchCM maarchCM = new MaarchCM();
            maarchCM.test(args);
        }
       catch(Exception e) {
           String exMessage = e.toString();
           System.out.println(exMessage);
       }
    }

    public String editObject() throws Exception, InterruptedException, JSException {
        System.out.println("----------BEGIN EDIT OBJECT----------");
        System.out.println("----------BEGIN LOCAL DIR TMP IF NOT EXISTS----------");
        String os = System.getProperty("os.name").toLowerCase();
        boolean isUnix = os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0;
        boolean isWindows = os.indexOf("win") >= 0;
        boolean isMac = os.indexOf("mac") >= 0;
        this.userLocalDirTmp = System.getProperty("user.home");
        //this.userLocalDirTmp = "C:/repertoire avec espaces";
        //this.userLocalDirTmp = "c:\\maarch";
        //this.userLocalDirTmp = "\\\\192.168.21.100\\Public\\montage_nas\\avec espaces";

        fileManager fM = new fileManager();
        fM.createUserLocalDirTmp(this.userLocalDirTmp);
        if (isWindows) {
            System.out.println("This is Windows");
            this.userLocalDirTmp = this.userLocalDirTmp + "\\maarchTmp\\";
            //this.appPath = this.userLocalDirTmp.replaceAll(" ", "%20") + "start.bat";
            //this.appPath = "\""+this.userLocalDirTmp + "start.bat\"";
            this.appPath = this.userLocalDirTmp + "start.bat";
            this.os = "win";
        } else if (isMac) {
            System.out.println("This is Mac");
            this.userLocalDirTmp = this.userLocalDirTmp + "/maarchTmp/";
            this.appPath = this.userLocalDirTmp + "start.sh";
            this.os = "mac";
        } else if (isUnix) {
            System.out.println("This is Unix or Linux");
            this.userLocalDirTmp = this.userLocalDirTmp + "/maarchTmp/";
            this.appPath = this.userLocalDirTmp + "start.sh";
            this.os = "linux";
        } else {
            System.out.println("Your OS is not supported!!");
        }
        System.out.println("APP PATH: " + this.appPath);
        System.out.println("----------BEGIN LOCAL DIR TMP IF NOT EXISTS----------");

        fM.createUserLocalDirTmp(this.userLocalDirTmp);
        System.out.println("----------END LOCAL DIR TMP IF NOT EXISTS----------");

        System.out.println("Create the logger");
        this.logger = new myLogger(this.userLocalDirTmp);

        if (this.psExecMode.equals("OK")) {
            this.logger.log("----------BEGIN PSEXEC MODE----------", Level.INFO);
            boolean isPsExecExists = fM.isPsExecFileExists(this.userLocalDirTmp + "PsExec.exe");
            if (!isPsExecExists) {
                this.logger.log("----------BEGIN TRANSFER OF PSEXEC----------", Level.INFO);
                String urlToSend = this.url + "?action=sendPsExec&objectType=" + this.objectType
                        + "&objectTable=" + this.objectTable + "&objectId=" + this.objectId;
                sendHttpRequest(urlToSend, "none");
                this.logger.log("MESSAGE STATUS : " + this.messageStatus.toString(), Level.INFO);
                this.logger.log("MESSAGE RESULT : ", Level.INFO);
                this.processReturn(this.messageResult);
                this.logger.log("CREATE THE FILE : " + this.userLocalDirTmp + "PsExec.exe", Level.INFO);
                fM.createFile(this.fileContent, this.userLocalDirTmp + "PsExec.exe");
                this.fileContent = "";
                this.logger.log("----------END TRANSFER OF PSEXEC----------", Level.INFO);
            }
            this.logger.log("----------END PSEXEC MODE----------", Level.INFO);
        }

        this.logger.log("----------BEGIN OPEN REQUEST----------", Level.INFO);
        String urlToSend = this.url + "?action=editObject&objectType=" + this.objectType
                        + "&objectTable=" + this.objectTable + "&objectId=" + this.objectId;
        sendHttpRequest(urlToSend, "none");
        this.logger.log("MESSAGE STATUS : " + this.messageStatus.toString(), Level.INFO);
        this.logger.log("MESSAGE RESULT : ", Level.INFO);
        this.processReturn(this.messageResult);
        this.logger.log("----------END OPEN REQUEST----------", Level.INFO);

        String fileToEdit = "thefile." + this.fileExtension;

        this.logger.log("----------BEGIN CREATE THE BAT TO LAUNCH IF NECESSARY----------", Level.INFO);
        this.logger.log("create the file : "  + this.appPath, Level.INFO);
        fM.createBatFile(
            this.appPath, 
            this.userLocalDirTmp, 
            fileToEdit, 
            this.os,
            this.userMaarch,
            this.userMaarchPwd,
            this.psExecMode,
            this.userLocalDirTmp
        );
        this.logger.log("----------END CREATE THE BAT TO LAUNCH IF NECESSARY----------", Level.INFO);

        if ("ok".equals(this.status)) {
            this.logger.log("RESPONSE OK", Level.INFO);

            this.logger.log("----------BEGIN EXECUTION OF THE EDITOR----------", Level.INFO);
            this.logger.log("CREATE FILE IN LOCAL PATH", Level.INFO);
            fM.createFile(this.fileContent, this.userLocalDirTmp + fileToEdit);

            //this.logger.log("CREATE FILE TO CHANGE RIGHTS IN THE TMP DIR", Level.INFO);
            //fM.createRightsFile(this.userLocalDirTmp, this.userMaarch);

            /*this.logger.log("LAUNCH VBS TO CHANGE RIGHTS IN THE TMP DIR", Level.INFO);
            final String vbsPath = this.userLocalDirTmp + "setRights.vbs";
            Process procVbs = fM.launchApp("cmd /c wscript //B " + vbsPath);
            procVbs.waitFor();*/

            final String exec;

            this.logger.log("LAUNCH THE EDITOR !", Level.INFO);
            if (isUnix) {
                exec = this.appPath;
            }else{
               exec = "\""+this.appPath+"\""; 
            }

            this.logger.log("EXEC PATH : " + exec, Level.INFO);
            Process proc = fM.launchApp(exec);
            proc.waitFor();

            this.logger.log("----------END EXECUTION OF THE EDITOR----------", Level.INFO);

            this.logger.log("----------BEGIN RETRIEVE CONTENT OF THE OBJECT----------", Level.INFO);
            this.fileContentTosend = fM.encodeFile(this.userLocalDirTmp + "thefile." + this.fileExtension);
            this.logger.log("----------END RETRIEVE CONTENT OF THE OBJECT----------", Level.INFO);

            String urlToSave = this.url + "?action=saveObject&objectType=" + this.objectType 
                            + "&objectTable=" + this.objectTable + "&objectId=" + this.objectId;
            this.logger.log("----------BEGIN SEND OF THE OBJECT----------", Level.INFO);
            this.logger.log("URL TO SAVE : " + urlToSave, Level.INFO);
            sendHttpRequest(urlToSave, this.fileContentTosend);
            this.logger.log("MESSAGE STATUS : " + this.messageStatus.toString(), Level.INFO);
            this.logger.log("LAST MESSAGE RESULT : ", Level.INFO);
            this.processReturn(this.messageResult);
            //send message to Maarch at the end
            if (!this.endMessage.isEmpty()) {
                this.sendJsMessage(this.endMessage.toString());
            }
            this.sendJsEnd();
            this.logger.log("----------END SEND OF THE OBJECT----------", Level.INFO);
        } else {
            this.logger.log("RESPONSE KO", Level.WARNING);
        }
        this.logger.log("----------END EDIT OBJECT----------", Level.INFO);
        return "ok";
    }

    public void sendJsMessage(String message) throws JSException
    {
        JSObject jso;
        jso = JSObject.getWindow(this);
        this.logger.log("----------JS CALL sendAppletMsg TO MAARCH----------", Level.INFO);
        jso.call("sendAppletMsg", new String[] {String.valueOf(message)});
    }

    public void sendJsEnd() throws InterruptedException, JSException
    {
        JSObject jso;
        jso = JSObject.getWindow(this);
        this.logger.log("----------JS CALL endOfApplet TO MAARCH----------", Level.INFO);
        jso.call("endOfApplet", new String[] {String.valueOf(this.objectType), this.endMessage});    
    }

    public void sendHttpRequest(String theUrl, String postRequest) throws Exception {
        URL UrlOpenRequest = new URL(theUrl);
        HttpURLConnection HttpOpenRequest = (HttpURLConnection) UrlOpenRequest.openConnection();
        HttpOpenRequest.setDoOutput(true);
        HttpOpenRequest.setRequestMethod("POST");
        if (!"none".equals(postRequest)) {
            OutputStreamWriter writer = new OutputStreamWriter(HttpOpenRequest.getOutputStream());
            writer.write("fileContent=" + this.fileContentTosend + "&fileExtension=" + this.fileExtension);
            writer.flush();
        } else {
            OutputStreamWriter writer = new OutputStreamWriter(HttpOpenRequest.getOutputStream());
            writer.write("foo=bar");
            writer.flush();
        }
        int statusCode = HttpOpenRequest.getResponseCode();
        System.out.println("Coooode: "+statusCode); 
        this.parse_xml(HttpOpenRequest.getInputStream());
        HttpOpenRequest.disconnect();
    }
}
like image 263
Imane Avatar asked Mar 01 '26 12:03

Imane


1 Answers

You will get a FileNotFoundException from HttpURLConnection.getInputStream when the response from the server is "404 Not Found" or "410 Gone". (Any other problem will give you a different exception.)

So why would you be getting a 404 or 410?

The most likely explanation of a 404 is that the URL is incorrect. It is also possible that you have a problem with your HTTP proxy configs, or the web server you are talking to is itself misconfigured or broken, or ... is sending 404 responses inappropriately1.

(I assume that http://PATH_TO_A_DIRECTORY/reopen.php is not the real URL.)

A 410 is only possible if the URL is correct, but it refers to a resource that existed in the past but has since been removed. It is (IMO) highly unlikely that you will encounter this.


The exception says that the file "reopen.php" is missing, but the path mentioned in the exception is wrong, and I don't call it in my code.

The url in the exception can be different to the url that you supplied if the server is sending a 3xx redirect. So, I suspect that the problem is that the server is redirecting to a URL for a resource which doesn't exist. That is a server bug!

You could confirm this by debugging, or reading the source code2 for

      sun.net.www.protocol.http.HttpURLConnection

or you could check the redirection behavior using your web browser's development tools.


1 - Some web developers code sites to send inappropriate response codes, through ignorance, laziness ... or to try to mislead web scrapers.
2 - To find source code for an OpenJDK class, google for "<name-of-class> source code". Alternatively, you can download or checkout the source code from https://openjdk.java.net/

like image 190
Stephen C Avatar answered Mar 04 '26 01:03

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!