Как исправить ошибку «java.io.FileNotFoundException: at sun.net.www.protocol.http.HttpURLConnection.getInputStream0 (Unknown Source)»? - PullRequest
1 голос
/ 21 июня 2019

Я пытаюсь преобразовать апплет в приложение Java. Поэтому я сгенерировал файл JNLP и передал все необходимые аргументы с помощью метода POST. Как только я запускаю приложение из JNLP, я получаю эту ошибку:

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)

Исключение говорит, что файл "reopen.php" отсутствует, но путь, упомянутый в исключении, неверен, и я не вызываю его в своем коде. Это прекрасно работает, когда я запускаю его как апплет, но не как приложение. Я действительно не знаю, в чем может быть ошибка в коде. Вот мой код.

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();
    }
}

1 Ответ

1 голос
/ 21 июня 2019

Вы получите FileNotFoundException от HttpURLConnection.getInputStream, если ответ от сервера «404 Not Found» или «410 Gone».(Любая другая проблема даст вам другое исключение.)

Так почему бы вам получить 404 или 410?

Наиболее вероятным объяснением 404 является то, что URL неверен, нотакже возможно, что у вас есть проблема с вашими настройками прокси-сервера http или сервер HTTP, с которым вы разговариваете, неправильно настроен или содержит ошибки.

(я предполагаю, что http://PATH_TO_A_DIRECTORY/reopen.php не является реальным URL.)

410 возможен, только если URL-адрес правильный, но он относится к ресурсу, который существовал в прошлом, но с тех пор был удален.(ИМО) крайне маловероятно, что вы столкнетесь с этим.


Исключение говорит о том, что файл "reopen.php" отсутствует, но путь, указанный в исключении, неверен, иЯ не называю это в своем коде.

URL-адрес в исключении может отличаться от URL-адреса, который вы указали, если сервер отправляет перенаправление 3xx.Итак, я подозреваю, что проблема в том, что сервер перенаправляет на URL для ресурса, который не существует.Это ошибка сервера!

Вы можете подтвердить это путем отладки или чтения исходного кода 1 для

      sun.net.www.protocol.http.HttpURLConnection

, или вы можете проверить поведение перенаправления, используяинструменты разработки веб-браузера.


1 - чтобы найти исходный код для класса OpenJDK, перейдите на страницу "Исходный код ". Кроме того, вы можете скачать или оформить исходный код с https://openjdk.java.net/

...