Search in sources :

Example 46 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class WebServerManager method preferencesFromMiniServerPreferences.

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Catch is covering both JDOMException and IOException, FindBugs seems confused")
private void preferencesFromMiniServerPreferences(File MSFile, File WSFile) {
    XmlFile xmlFile = new XmlFile() {
    };
    try {
        Element MSRoot = xmlFile.rootFromFile(MSFile);
        Element WSRoot = new Element(WebServerPreferences.WEB_SERVER_PREFERENCES);
        // NOI18N
        Element MSPrefs = MSRoot.getChild("MiniServerPreferences");
        for (Object pref : MSPrefs.getChildren()) {
            WSRoot.addContent((Element) pref);
        }
        for (Attribute attr : MSPrefs.getAttributes()) {
            if (attr.getName().equals("getDisallowedFrames")) {
                // NOI18N
                Element DF = new Element(WebServerPreferences.DISALLOWED_FRAMES);
                // NOI18N
                String[] frames = attr.getValue().split("\\n");
                for (String frame : frames) {
                    DF.addContent(new Element(WebServerPreferences.FRAME).addContent(frame));
                }
                WSRoot.addContent(DF);
            } else if (attr.getName().equals("getPort")) {
                // NOI18N
                WSRoot.setAttribute(WebServerPreferences.PORT, attr.getValue());
            } else if (attr.getName().equals("getClickDelay")) {
                // NOI18N
                WSRoot.setAttribute(WebServerPreferences.CLICK_DELAY, attr.getValue());
            } else if (attr.getName().equals("getRefreshDelay")) {
                // NOI18N
                WSRoot.setAttribute(WebServerPreferences.REFRESH_DELAY, attr.getValue());
            } else {
                // double cast because clone() is Protected on Object
                WSRoot.setAttribute(attr.clone());
            }
        }
        Document WSDoc = XmlFile.newDocument(WSRoot);
        File parent = new File(WSFile.getParent());
        if (!parent.exists()) {
            // directory known to not exist from previous conditional
            boolean created = parent.mkdir();
            if (!created) {
                log.error("Failed to create directory {}", parent.toString());
                throw new java.io.IOException("Failed to create directory " + parent.toString());
            }
        }
        // known to not exist or this method would not have been called
        boolean created = WSFile.createNewFile();
        if (!created) {
            log.error("Failed to new create file {}", WSFile.toString());
            throw new java.io.IOException("Failed to create new file " + WSFile.toString());
        }
        xmlFile.writeXML(WSFile, WSDoc);
    } catch (IOException | JDOMException ex) {
        log.error("Error converting miniServer preferences to Web Server preferences.", ex);
    }
}
Also used : XmlFile(jmri.jmrit.XmlFile) Attribute(org.jdom2.Attribute) Element(org.jdom2.Element) IOException(java.io.IOException) Document(org.jdom2.Document) JDOMException(org.jdom2.JDOMException) File(java.io.File) XmlFile(jmri.jmrit.XmlFile) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 47 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class WebServerPreferences method openFile.

public final void openFile(String fileName) throws FileNotFoundException {
    WebServerPreferencesXml prefsXml = new WebServerPreferencesXml();
    File file = new File(fileName);
    Element root;
    try {
        root = prefsXml.rootFromFile(file);
    } catch (FileNotFoundException ex) {
        log.debug("Could not find Web Server preferences file. Normal if preferences have not been saved before.");
        throw ex;
    } catch (IOException | JDOMException ex) {
        log.error("Exception while loading web server preferences: " + ex);
        root = null;
    }
    if (root != null) {
        load(root);
    }
}
Also used : Element(org.jdom2.Element) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) JDOMException(org.jdom2.JDOMException) File(java.io.File) XmlFile(jmri.jmrit.XmlFile)

Example 48 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class RosterServlet method doPost.

/**
     * Handle any POST request as an upload of a roster file from client.
     *
     * @param request  servlet request
     * @param response servlet response
     * @throws javax.servlet.ServletException if unable to process uploads
     * @throws java.io.IOException            if communications is cut with
     *                                        client
     */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    OutputStream out = null;
    InputStream fileContent = null;
    String rosterFolderName = Roster.getDefault().getRosterLocation() + "roster" + File.separator;
    String tempFolderName = System.getProperty("java.io.tmpdir");
    if (!tempFolderName.endsWith(File.separator)) {
        //make sure path ends with a separator
        tempFolderName += File.separator;
    }
    Locale rl = request.getLocale();
    //get the uploaded file(s)
    List<FileMeta> files = MultipartRequestHandler.uploadByJavaServletAPI(request);
    List<String> msgList = new ArrayList<>();
    //loop thru files returned and validate and (if ok) save each
    for (FileMeta fm : files) {
        log.debug("processing uploaded '{}' file '{}' ({}), group='{}', roster='{}', temp='{}'", fm.getFileType(), fm.getFileName(), fm.getFileSize(), fm.getRosterGroup(), rosterFolderName, tempFolderName);
        //only allow xml files or image files
        if (!fm.getFileType().equals("text/xml") && !fm.getFileType().startsWith("image")) {
            String m = String.format(rl, Bundle.getMessage(rl, "ErrorInvalidFileType"), fm.getFileName(), fm.getFileType());
            log.error(m);
            msgList.add(m);
            //stop processing this one
            break;
        }
        //save received file to temporary folder
        File fileTemp = new File(tempFolderName + fm.getFileName());
        try {
            out = new FileOutputStream(fileTemp);
            fileContent = fm.getContent();
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = fileContent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            log.debug("file '{}' of type '{}' temp saved to {}", fm.getFileType(), fm.getFileName(), tempFolderName);
        } catch (IOException e) {
            String m = String.format(rl, Bundle.getMessage(rl, "ErrorSavingFile"), fm.getFileName());
            log.error(m);
            msgList.add(m);
            //stop processing this one
            break;
        } finally {
            if (out != null) {
                out.close();
            }
            if (fileContent != null) {
                fileContent.close();
            }
        }
        //finally
        //reference to target file name and location
        File fileNew = new File(rosterFolderName + fm.getFileName());
        //save image file, replacing if parm is set that way. return appropriate message
        if (fm.getFileType().startsWith("image")) {
            if (fileNew.exists()) {
                if (!fm.getFileReplace()) {
                    String m = String.format(rl, Bundle.getMessage(rl, "ErrorFileExists"), fm.getFileName());
                    log.error(m);
                    msgList.add(m);
                    //get rid of temp file 
                    fileTemp.delete();
                } else {
                    //delete the old file
                    fileNew.delete();
                    if (fileTemp.renameTo(fileNew)) {
                        String m = String.format(rl, Bundle.getMessage(rl, "FileReplaced"), fm.getFileName());
                        log.debug(m);
                        msgList.add(m);
                    } else {
                        String m = String.format(rl, Bundle.getMessage(rl, "ErrorRenameFailed"), fm.getFileName());
                        log.error(m);
                        msgList.add(m);
                        //get rid of temp file 
                        fileTemp.delete();
                    }
                }
            } else {
                if (fileTemp.renameTo(fileNew)) {
                    String m = String.format(rl, Bundle.getMessage(rl, "FileAdded"), fm.getFileName());
                    log.debug(m);
                    msgList.add(m);
                } else {
                    String m = String.format(rl, Bundle.getMessage(rl, "ErrorRenameFailed"), fm.getFileName());
                    log.error(m);
                    msgList.add(m);
                    //get rid of temp file 
                    fileTemp.delete();
                }
            }
        } else {
            // create a temp rosterentry to check, based on uploaded file
            RosterEntry reTemp = null;
            try {
                reTemp = RosterEntry.fromFile(new File(tempFolderName + fm.getFileName()));
            } catch (JDOMException e) {
                //handle XML failures
                String m = String.format(rl, Bundle.getMessage(rl, "ErrorInvalidXML"), fm.getFileName(), e.getMessage());
                log.error(m);
                msgList.add(m);
                //get rid of temp file 
                fileTemp.delete();
                break;
            }
            //get existing entry if found
            RosterEntry reOld = Roster.getDefault().getEntryForId(reTemp.getId());
            if (reOld != null) {
                if (!fm.getFileReplace()) {
                    String m = String.format(rl, Bundle.getMessage(rl, "ErrorFileExists"), fm.getFileName());
                    log.error(m);
                    msgList.add(m);
                    //get rid of temp file 
                    fileTemp.delete();
                } else {
                    //replace specified
                    //remove the old entry from roster
                    Roster.getDefault().removeEntry(reOld);
                    //saves XML file to roster folder and makes backup
                    reTemp.updateFile();
                    //add the new entry to roster
                    Roster.getDefault().addEntry(reTemp);
                    //save modified roster.xml file
                    Roster.getDefault().writeRoster();
                    String m = String.format(rl, Bundle.getMessage(rl, "RosterEntryReplaced"), fm.getFileName(), reTemp.getDisplayName());
                    log.debug(m);
                    msgList.add(m);
                    //get rid of temp file 
                    fileTemp.delete();
                }
            } else {
                //move the file to proper location
                fileTemp.renameTo(fileNew);
                Roster.getDefault().addEntry(reTemp);
                Roster.getDefault().writeRoster();
                String m = String.format(rl, Bundle.getMessage(rl, "RosterEntryAdded"), fm.getFileName(), reTemp.getId());
                log.debug(m);
                msgList.add(m);
            }
        }
    }
    //for FileMeta
    //respond with a json list of messages from the upload attempts
    response.setContentType("application/json");
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(response.getOutputStream(), msgList);
}
Also used : Locale(java.util.Locale) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) JDOMException(org.jdom2.JDOMException) FileOutputStream(java.io.FileOutputStream) RosterEntry(jmri.jmrit.roster.RosterEntry) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 49 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class StartupActionsManager method savePreferences.

@Override
public synchronized void savePreferences(Profile profile) {
    Element element = new Element(STARTUP, NAMESPACE);
    actions.stream().forEach((action) -> {
        log.debug("model is {} ({})", action.getName(), action);
        if (action.getName() != null) {
            Element e = ConfigXmlManager.elementFromObject(action, true);
            if (e != null) {
                element.addContent(e);
            }
        } else {
            // get an error with a stack trace if this occurs
            log.error("model does not have a name.", new Exception());
        }
    });
    try {
        ProfileUtils.getAuxiliaryConfiguration(profile).putConfigurationFragment(JDOMUtil.toW3CElement(element), true);
        this.isDirty = false;
    } catch (JDOMException ex) {
        log.error("Unable to create create XML", ex);
    }
}
Also used : Element(org.jdom2.Element) JDOMException(org.jdom2.JDOMException) InitializationException(jmri.util.prefs.InitializationException) JDOMException(org.jdom2.JDOMException) JmriException(jmri.JmriException)

Example 50 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class JsonServerPreferences method openFile.

public final void openFile(String fileName) throws FileNotFoundException {
    JsonServerPreferencesXml prefsXml = new JsonServerPreferences.JsonServerPreferencesXml();
    File file = new File(fileName);
    Element root;
    try {
        root = prefsXml.rootFromFile(file);
    } catch (FileNotFoundException ea) {
        log.info("Could not find JSON Server preferences file.  Normal if preferences have not been saved before.");
        throw ea;
    } catch (IOException | JDOMException eb) {
        log.error("Exception while loading JSON server preferences: {}", eb.getLocalizedMessage());
        root = null;
    }
    if (root != null) {
        this.load(root);
    }
}
Also used : Element(org.jdom2.Element) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) JDOMException(org.jdom2.JDOMException) File(java.io.File) XmlFile(jmri.jmrit.XmlFile)

Aggregations

Element (org.jdom2.Element)60 JDOMException (org.jdom2.JDOMException)34 IOException (java.io.IOException)29 Document (org.jdom2.Document)24 File (java.io.File)22 SAXBuilder (org.jdom2.input.SAXBuilder)22 XmlFile (jmri.jmrit.XmlFile)12 ArrayList (java.util.ArrayList)9 List (java.util.List)8 URL (java.net.URL)7 FileNotFoundException (java.io.FileNotFoundException)6 HashMap (java.util.HashMap)5 BufferedInputStream (java.io.BufferedInputStream)4 FileInputStream (java.io.FileInputStream)4 NoProcessSpecifiedException (de.hpi.bpt.scylla.creation.SimulationConfiguration.SimulationConfigurationCreator.NoProcessSpecifiedException)3 NotAuthorizedToOverrideException (de.hpi.bpt.scylla.creation.SimulationConfiguration.SimulationConfigurationCreator.NotAuthorizedToOverrideException)3 HeadlessException (java.awt.HeadlessException)3 Attribute (org.jdom2.Attribute)3 ScalingFileChooser (de.hpi.bpt.scylla.GUI.ScalingFileChooser)2 PropertyChangeEvent (java.beans.PropertyChangeEvent)2