Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

In this page you can find the example usage for org.dom4j Document addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:net.sf.cpsolver.studentsct.StudentSectioningXMLSaver.java

License:Open Source License

/**
 * Save an XML file/*from   w ww  .  j a  v  a 2  s. co  m*/
 * 
 * @param outFile
 *            output file
 */
public void save(File outFile) throws Exception {
    if (outFile == null)
        outFile = new File(iOutputFolder, "solution.xml");
    outFile.getParentFile().mkdirs();
    sLogger.debug("Writting XML data to:" + outFile);

    Document document = DocumentHelper.createDocument();
    document.addComment("Student Sectioning");

    if ((iSaveCurrent || iSaveBest)) { // &&
                                       // !getModel().assignedVariables().isEmpty()
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo()
                : getSolution().getExtendedInfo());
        for (String key : new TreeSet<String>(solutionInfo.keySet())) {
            String value = solutionInfo.get(key);
            comments.append("    " + key + ": " + value + "\n");
        }
        document.addComment(comments.toString());
    }

    Element root = document.addElement("sectioning");
    root.addAttribute("version", "1.0");
    root.addAttribute("initiative", getModel().getProperties().getProperty("Data.Initiative"));
    root.addAttribute("term", getModel().getProperties().getProperty("Data.Term"));
    root.addAttribute("year", getModel().getProperties().getProperty("Data.Year"));
    root.addAttribute("created", String.valueOf(new Date()));

    Element offeringsEl = root.addElement("offerings");
    for (Offering offering : getModel().getOfferings()) {
        Element offeringEl = offeringsEl.addElement("offering");
        offeringEl.addAttribute("id", getId("offering", offering.getId()));
        if (iShowNames)
            offeringEl.addAttribute("name", offering.getName());
        for (Course course : offering.getCourses()) {
            Element courseEl = offeringEl.addElement("course");
            courseEl.addAttribute("id", getId("course", course.getId()));
            if (iShowNames)
                courseEl.addAttribute("subjectArea", course.getSubjectArea());
            if (iShowNames)
                courseEl.addAttribute("courseNbr", course.getCourseNumber());
            if (iShowNames && course.getLimit() >= 0)
                courseEl.addAttribute("limit", String.valueOf(course.getLimit()));
            if (iShowNames && course.getProjected() != 0)
                courseEl.addAttribute("projected", String.valueOf(course.getProjected()));
        }
        for (Config config : offering.getConfigs()) {
            Element configEl = offeringEl.addElement("config");
            configEl.addAttribute("id", getId("config", config.getId()));
            if (config.getLimit() >= 0)
                configEl.addAttribute("limit", String.valueOf(config.getLimit()));
            if (iShowNames)
                configEl.addAttribute("name", config.getName());
            for (Subpart subpart : config.getSubparts()) {
                Element subpartEl = configEl.addElement("subpart");
                subpartEl.addAttribute("id", getId("subpart", subpart.getId()));
                subpartEl.addAttribute("itype", subpart.getInstructionalType());
                if (subpart.getParent() != null)
                    subpartEl.addAttribute("parent", getId("subpart", subpart.getParent().getId()));
                if (iShowNames)
                    subpartEl.addAttribute("name", subpart.getName());
                if (subpart.isAllowOverlap())
                    subpartEl.addAttribute("allowOverlap", "true");
                for (Section section : subpart.getSections()) {
                    Element sectionEl = subpartEl.addElement("section");
                    sectionEl.addAttribute("id", getId("section", section.getId()));
                    sectionEl.addAttribute("limit", String.valueOf(section.getLimit()));
                    if (section.getNameByCourse() != null)
                        for (Map.Entry<Long, String> entry : section.getNameByCourse().entrySet())
                            sectionEl.addElement("cname").addAttribute("id", entry.getKey().toString())
                                    .setText(entry.getValue());
                    if (section.getParent() != null)
                        sectionEl.addAttribute("parent", getId("section", section.getParent().getId()));
                    if (iShowNames && section.getChoice().getInstructorIds() != null)
                        sectionEl.addAttribute("instructorIds", section.getChoice().getInstructorIds());
                    if (iShowNames && section.getChoice().getInstructorNames() != null)
                        sectionEl.addAttribute("instructorNames", section.getChoice().getInstructorNames());
                    if (iShowNames)
                        sectionEl.addAttribute("name", section.getName());
                    if (section.getPlacement() != null) {
                        TimeLocation tl = section.getPlacement().getTimeLocation();
                        if (tl != null) {
                            Element timeLocationEl = sectionEl.addElement("time");
                            timeLocationEl.addAttribute("days",
                                    sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                            timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                            timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
                            if (tl.getBreakTime() != 0)
                                timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
                            if (iShowNames && tl.getTimePatternId() != null)
                                timeLocationEl.addAttribute("pattern",
                                        getId("timePattern", tl.getTimePatternId()));
                            if (iShowNames && tl.getDatePatternId() != null)
                                timeLocationEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                            if (iShowNames && tl.getDatePatternName() != null
                                    && tl.getDatePatternName().length() > 0)
                                timeLocationEl.addAttribute("datePatternName", tl.getDatePatternName());
                            timeLocationEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                            if (iShowNames)
                                timeLocationEl.setText(tl.getLongName());
                        }
                        for (RoomLocation rl : section.getRooms()) {
                            Element roomLocationEl = sectionEl.addElement("room");
                            roomLocationEl.addAttribute("id", getId("room", rl.getId()));
                            if (iShowNames && rl.getBuildingId() != null)
                                roomLocationEl.addAttribute("building", getId("building", rl.getBuildingId()));
                            if (iShowNames && rl.getName() != null)
                                roomLocationEl.addAttribute("name", rl.getName());
                            roomLocationEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
                            if (rl.getPosX() != null && rl.getPosY() != null)
                                roomLocationEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
                            if (rl.getIgnoreTooFar())
                                roomLocationEl.addAttribute("ignoreTooFar", "true");
                        }
                    }
                    if (iSaveOnlineSectioningInfo) {
                        if (section.getSpaceHeld() != 0.0)
                            sectionEl.addAttribute("hold", sStudentWeightFormat.format(section.getSpaceHeld()));
                        if (section.getSpaceExpected() != 0.0)
                            sectionEl.addAttribute("expect",
                                    sStudentWeightFormat.format(section.getSpaceExpected()));
                    }
                }
            }
        }
        if (!offering.getReservations().isEmpty()) {
            for (Reservation r : offering.getReservations()) {
                Element reservationEl = offeringEl.addElement("reservation");
                reservationEl.addAttribute("id", getId("reservation", r.getId()));
                if (r instanceof GroupReservation) {
                    GroupReservation gr = (GroupReservation) r;
                    reservationEl.addAttribute("type", "group");
                    for (Long studentId : gr.getStudentIds())
                        reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
                    if (gr.getLimit() >= 0.0)
                        reservationEl.addAttribute("limit", String.valueOf(gr.getLimit()));
                } else if (r instanceof IndividualReservation) {
                    reservationEl.addAttribute("type", "individual");
                    for (Long studentId : ((IndividualReservation) r).getStudentIds())
                        reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
                } else if (r instanceof CurriculumReservation) {
                    reservationEl.addAttribute("type", "curriculum");
                    CurriculumReservation cr = (CurriculumReservation) r;
                    if (cr.getLimit() >= 0.0)
                        reservationEl.addAttribute("limit", String.valueOf(cr.getLimit()));
                    reservationEl.addAttribute("area", cr.getAcademicArea());
                    for (String clasf : cr.getClassifications())
                        reservationEl.addElement("classification").addAttribute("code", clasf);
                    for (String major : cr.getMajors())
                        reservationEl.addElement("major").addAttribute("code", major);
                } else if (r instanceof CourseReservation) {
                    reservationEl.addAttribute("type", "course");
                    CourseReservation cr = (CourseReservation) r;
                    reservationEl.addAttribute("course", getId("course", cr.getCourse().getId()));
                }
                for (Config config : r.getConfigs())
                    reservationEl.addElement("config").addAttribute("id", getId("config", config.getId()));
                for (Map.Entry<Subpart, Set<Section>> entry : r.getSections().entrySet()) {
                    for (Section section : entry.getValue()) {
                        reservationEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                    }
                }
            }
        }
    }

    Element studentsEl = root.addElement("students");
    for (Student student : getModel().getStudents()) {
        Element studentEl = studentsEl.addElement("student");
        studentEl.addAttribute("id", getId("student", student.getId()));
        if (student.isDummy())
            studentEl.addAttribute("dummy", "true");
        if (iSaveStudentInfo) {
            for (AcademicAreaCode aac : student.getAcademicAreaClasiffications()) {
                Element aacEl = studentEl.addElement("classification");
                if (aac.getArea() != null)
                    aacEl.addAttribute("area", aac.getArea());
                if (aac.getCode() != null)
                    aacEl.addAttribute("code", aac.getCode());
            }
            for (AcademicAreaCode aac : student.getMajors()) {
                Element aacEl = studentEl.addElement("major");
                if (aac.getArea() != null)
                    aacEl.addAttribute("area", aac.getArea());
                if (aac.getCode() != null)
                    aacEl.addAttribute("code", aac.getCode());
            }
            for (AcademicAreaCode aac : student.getMinors()) {
                Element aacEl = studentEl.addElement("minor");
                if (aac.getArea() != null)
                    aacEl.addAttribute("area", aac.getArea());
                if (aac.getCode() != null)
                    aacEl.addAttribute("code", aac.getCode());
            }
        }
        for (Request request : student.getRequests()) {
            if (request instanceof FreeTimeRequest) {
                Element requestEl = studentEl.addElement("freeTime");
                FreeTimeRequest ft = (FreeTimeRequest) request;
                requestEl.addAttribute("id", getId("request", request.getId()));
                requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
                if (request.isAlternative())
                    requestEl.addAttribute("alternative", "true");
                if (request.getWeight() != 1.0)
                    requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
                TimeLocation tl = ft.getTime();
                if (tl != null) {
                    requestEl.addAttribute("days",
                            sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                    requestEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                    requestEl.addAttribute("length", String.valueOf(tl.getLength()));
                    if (iShowNames && tl.getDatePatternId() != null)
                        requestEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                    requestEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                    if (iShowNames)
                        requestEl.setText(tl.getLongName());
                }
                if (iSaveInitial && request.getInitialAssignment() != null) {
                    requestEl.addElement("initial");
                }
                if (iSaveCurrent && request.getAssignment() != null) {
                    requestEl.addElement("current");
                }
                if (iSaveBest && request.getBestAssignment() != null) {
                    requestEl.addElement("best");
                }
            } else if (request instanceof CourseRequest) {
                CourseRequest cr = (CourseRequest) request;
                Element requestEl = studentEl.addElement("course");
                requestEl.addAttribute("id", getId("request", request.getId()));
                requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
                if (request.isAlternative())
                    requestEl.addAttribute("alternative", "true");
                if (request.getWeight() != 1.0)
                    requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
                requestEl.addAttribute("waitlist", cr.isWaitlist() ? "true" : "false");
                if (cr.getTimeStamp() != null)
                    requestEl.addAttribute("timeStamp", cr.getTimeStamp().toString());
                boolean first = true;
                for (Course course : cr.getCourses()) {
                    if (first)
                        requestEl.addAttribute("course", getId("course", course.getId()));
                    else
                        requestEl.addElement("alternative").addAttribute("course",
                                getId("course", course.getId()));
                    first = false;
                }
                for (Choice choice : cr.getWaitlistedChoices()) {
                    Element choiceEl = requestEl.addElement("waitlisted");
                    choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
                    choiceEl.setText(choice.getId());
                }
                for (Choice choice : cr.getSelectedChoices()) {
                    Element choiceEl = requestEl.addElement("selected");
                    choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
                    choiceEl.setText(choice.getId());
                }
                if (iSaveInitial && request.getInitialAssignment() != null) {
                    Element assignmentEl = requestEl.addElement("initial");
                    Enrollment enrollment = request.getInitialAssignment();
                    if (enrollment.getReservation() != null)
                        assignmentEl.addAttribute("reservation",
                                getId("reservation", enrollment.getReservation().getId()));
                    for (Section section : enrollment.getSections()) {
                        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                        if (iShowNames)
                            sectionEl.setText(section.getName() + " "
                                    + (section.getTime() == null ? " Arr Hrs"
                                            : " " + section.getTime().getLongName())
                                    + (section.getNrRooms() == 0 ? ""
                                            : " " + section.getPlacement().getRoomName(","))
                                    + (section.getChoice().getInstructorNames() == null ? ""
                                            : " " + section.getChoice().getInstructorNames()));
                    }
                }
                if (iSaveCurrent && request.getAssignment() != null) {
                    Element assignmentEl = requestEl.addElement("current");
                    Enrollment enrollment = request.getAssignment();
                    if (enrollment.getReservation() != null)
                        assignmentEl.addAttribute("reservation",
                                getId("reservation", enrollment.getReservation().getId()));
                    for (Section section : enrollment.getSections()) {
                        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                        if (iShowNames)
                            sectionEl.setText(section.getName() + " "
                                    + (section.getTime() == null ? " Arr Hrs"
                                            : " " + section.getTime().getLongName())
                                    + (section.getNrRooms() == 0 ? ""
                                            : " " + section.getPlacement().getRoomName(","))
                                    + (section.getChoice().getInstructorNames() == null ? ""
                                            : " " + section.getChoice().getInstructorNames()));
                    }
                }
                if (iSaveBest && request.getBestAssignment() != null) {
                    Element assignmentEl = requestEl.addElement("best");
                    Enrollment enrollment = request.getBestAssignment();
                    if (enrollment.getReservation() != null)
                        assignmentEl.addAttribute("reservation",
                                getId("reservation", enrollment.getReservation().getId()));
                    for (Section section : enrollment.getSections()) {
                        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                        if (iShowNames)
                            sectionEl.setText(section.getName() + " "
                                    + (section.getTime() == null ? " Arr Hrs"
                                            : " " + section.getTime().getLongName())
                                    + (section.getNrRooms() == 0 ? ""
                                            : " " + section.getPlacement().getRoomName(","))
                                    + (section.getChoice().getInstructorNames() == null ? ""
                                            : " " + section.getChoice().getInstructorNames()));
                    }
                }
            }
        }
    }

    if (iShowNames) {
        Progress.getInstance(getModel()).save(root);
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outFile);
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
        fos.flush();
        fos.close();
        fos = null;
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
    }

    if (iConvertIds)
        IdConvertor.getInstance().save();
}

From source file:net.sf.eclipsecs.core.config.GlobalCheckConfigurationWorkingSet.java

License:Open Source License

/**
 * Transforms the check configurations to a document.
 *///from w  w  w .j  a v a  2  s  . co m
private static Document createCheckConfigurationsDocument(List<CheckConfigurationWorkingCopy> configurations,
        ICheckConfiguration defaultConfig) {

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement(XMLTags.CHECKSTYLE_ROOT_TAG);
    root.addAttribute(XMLTags.VERSION_TAG, CheckConfigurationFactory.CURRENT_CONFIG_FILE_FORMAT_VERSION);

    if (defaultConfig != null) {
        root.addAttribute(XMLTags.DEFAULT_CHECK_CONFIG_TAG, defaultConfig.getName());
    }

    for (ICheckConfiguration config : configurations) {

        // don't store built-in configurations to persistence or local
        // configurations
        if (config.getType() instanceof BuiltInConfigurationType || !config.isGlobal()) {
            continue;
        }

        Element configEl = root.addElement(XMLTags.CHECK_CONFIG_TAG);
        configEl.addAttribute(XMLTags.NAME_TAG, config.getName());
        configEl.addAttribute(XMLTags.LOCATION_TAG, config.getLocation());
        configEl.addAttribute(XMLTags.TYPE_TAG, config.getType().getInternalName());
        if (config.getDescription() != null) {
            configEl.addAttribute(XMLTags.DESCRIPTION_TAG, config.getDescription());
        }

        // Write resolvable properties
        for (ResolvableProperty prop : config.getResolvableProperties()) {

            Element propEl = configEl.addElement(XMLTags.PROPERTY_TAG);
            propEl.addAttribute(XMLTags.NAME_TAG, prop.getPropertyName());
            propEl.addAttribute(XMLTags.VALUE_TAG, prop.getValue());
        }

        for (Map.Entry<String, String> entry : config.getAdditionalData().entrySet()) {

            Element addEl = configEl.addElement(XMLTags.ADDITIONAL_DATA_TAG);
            addEl.addAttribute(XMLTags.NAME_TAG, entry.getKey());
            addEl.addAttribute(XMLTags.VALUE_TAG, entry.getValue());
        }
    }
    return doc;
}

From source file:net.sf.eclipsecs.core.projectconfig.ProjectConfigurationWorkingCopy.java

License:Open Source License

/**
 * Produces the sax events to write a project configuration.
 * /*  w w  w  .j  ava  2  s  .  c om*/
 * @param config
 *            the configuration
 */
private Document writeProjectConfig(ProjectConfigurationWorkingCopy config) throws CheckstylePluginException {

    Document doc = DocumentHelper.createDocument();

    Element root = doc.addElement(XMLTags.FILESET_CONFIG_TAG);
    root.addAttribute(XMLTags.FORMAT_VERSION_TAG, ProjectConfigurationFactory.CURRENT_FILE_FORMAT_VERSION);
    root.addAttribute(XMLTags.SIMPLE_CONFIG_TAG, Boolean.toString(config.isUseSimpleConfig()));
    root.addAttribute(XMLTags.SYNC_FORMATTER_TAG, Boolean.toString(config.isSyncFormatter()));

    ICheckConfiguration[] workingCopies = config.getLocalCheckConfigWorkingSet().getWorkingCopies();
    for (int i = 0; i < workingCopies.length; i++) {
        writeLocalConfiguration(workingCopies[i], root);
    }

    for (FileSet fileSet : config.getFileSets()) {
        writeFileSet(fileSet, config.getProject(), root);
    }

    // write filters
    for (IFilter filter : config.getFilters()) {
        writeFilter(filter, root);
    }

    return doc;
}

From source file:net.sf.jvifm.model.AppStatus.java

License:Open Source License

public static boolean writeAppStatus() {

    try {// w w  w. j av  a 2  s .c om

        String[][] currentPath = Main.fileManager.getAllCurrentPath();
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("tabs");

        for (int i = 0; i < currentPath.length; i++) {
            Element tabElement = root.addElement("tab");
            tabElement.addAttribute("left", currentPath[i][0]);
            tabElement.addAttribute("right", currentPath[i][1]);
        }

        FileOutputStream fos = new FileOutputStream(appStatusPath);
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding("UTF-8");
        BufferedOutputStream out = new BufferedOutputStream(fos);
        XMLWriter writer = new XMLWriter(out, outformat);
        writer.write(document);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;

}

From source file:net.sf.jvifm.model.BookmarkManager.java

License:Open Source License

@SuppressWarnings("unchecked")
public void store() {

    try {/*from w w w.j  a  v a 2  s. c o  m*/

        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("bookmarks");

        for (Iterator it = bookmarkList.iterator(); it.hasNext();) {

            Bookmark bm = (Bookmark) it.next();

            Element bookmarkElement = root.addElement("bookmark");

            bookmarkElement.addElement("name").addText(bm.getName());
            bookmarkElement.addElement("path").addText(bm.getPath());
            if (bm.getKey() != null)
                bookmarkElement.addElement("key").addText(bm.getKey());

        }

        FileOutputStream fos = new FileOutputStream(storePath);
        OutputFormat outformat = OutputFormat.createPrettyPrint();

        outformat.setEncoding("UTF-8");
        BufferedOutputStream out = new BufferedOutputStream(fos);
        XMLWriter writer = new XMLWriter(out, outformat);

        writer.write(document);
        writer.flush();
        writer.close();
        fos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.sf.jvifm.model.MimeManager.java

License:Open Source License

@SuppressWarnings("unchecked")
public void store() {

    try {/*from  w ww  . ja va2  s  .  com*/
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("mimes");
        for (Iterator it = mimeInfo.keySet().iterator(); it.hasNext();) {
            String postfix = (String) it.next();
            Element filetypeEle = root.addElement("filetype");
            filetypeEle.addAttribute("postfix", postfix);
            List<String> appPathList = mimeInfo.get(postfix);
            for (String appPath : appPathList) {
                filetypeEle.addElement("appPath").addText(appPath);
            }
        }

        FileOutputStream fos = new FileOutputStream(storePath);
        OutputFormat outformat = OutputFormat.createPrettyPrint();

        outformat.setEncoding("UTF-8");
        BufferedOutputStream out = new BufferedOutputStream(fos);
        XMLWriter writer = new XMLWriter(out, outformat);

        writer.write(document);
        writer.flush();
        writer.close();
        fos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.sf.jvifm.model.ShortcutsManager.java

License:Open Source License

public void store() {

    try {//from w ww  .j  a va 2 s  .co  m

        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("commands");

        for (Shortcut shortcut : shortcutsList) {

            Element shortcutElement = root.addElement("command");

            shortcutElement.addElement("name").addText(shortcut.getName());
            shortcutElement.addElement("text").addText(shortcut.getText());

        }

        FileOutputStream fos = new FileOutputStream(storePath);
        OutputFormat outformat = OutputFormat.createPrettyPrint();

        outformat.setEncoding("UTF-8");
        BufferedOutputStream out = new BufferedOutputStream(fos);
        XMLWriter writer = new XMLWriter(out, outformat);

        writer.write(document);
        writer.flush();
        writer.close();
        fos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.sf.kraken.KrakenPlugin.java

License:Open Source License

/**
 * Returns the web options config for the given transport, if it exists.
 *
 * @param type type of the transport we want the options config for.
 * @return XML document with the options config.
 *//*from ww w.ja  va2 s  . c  o m*/
public Document getOptionsConfig(TransportType type) {
    // Load any custom-defined servlets.
    File optConf = new File(this.pluginDirectory, "web" + File.separator + "WEB-INF" + File.separator
            + "options" + File.separator + type.toString() + ".xml");
    Document optConfXML;
    try {
        FileReader reader = new FileReader(optConf);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        optConfXML = xmlReader.read(reader);
    } catch (FileNotFoundException e) {
        // Non-existent: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    } catch (DocumentException e) {
        // Bad config: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    }
    return optConfXML;
}

From source file:net.sf.kraken.KrakenPlugin.java

License:Open Source License

/**
 * Returns the web global options, if it exists.
 *
 * @return XML document with the options config.
 *///from   w  w  w . j  a  v  a  2 s.  c o  m
public Document getOptionsConfig() {
    // Load any custom-defined servlets.
    File optConf = new File(this.pluginDirectory,
            "web" + File.separator + "WEB-INF" + File.separator + "options" + File.separator + "global.xml");
    Document optConfXML;
    try {
        FileReader reader = new FileReader(optConf);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        optConfXML = xmlReader.read(reader);
    } catch (FileNotFoundException e) {
        // Non-existent: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    } catch (DocumentException e) {
        // Bad config: Return empty config
        optConfXML = DocumentHelper.createDocument();
        optConfXML.addElement("optionsconfig");
    }
    return optConfXML;
}

From source file:nidonuevo.model.Engine.java

public void saveToXML() {

    //        try {
    //            Thread.sleep(3000);//Para esperar a q se cargue todo, despues lo borraremos
    //        } catch (InterruptedException ex) {
    //            Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
    //        }//  w w w.j a  v a 2  s.co m
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("GameData");
    //PLAYER
    Element player = root.addElement("Player");
    player.addElement("name").addText(LMS.getPlayer().getName());
    player.addElement("happiness").addText("" + LMS.getPlayer().getHappiness());
    player.addElement("numberOfFriends").addText("" + LMS.getPlayer().getNumberOfFriends());
    player.addElement("level").addText("" + LMS.getPlayer().getLevel());
    player.addElement("numerOfTrophies").addText("" + LMS.getPlayer().getNumberOfTrophies());
    ////FRIENDS
    Element friends = player.addElement("Friends");
    for (int i = 0; i < LMS.getPlayer().getFriends().size(); i++) {
        Element friend = friends.addElement("Friend").addAttribute("id",
                "" + LMS.getPlayer().getFriends().get(i).getId());
    }
    ////INVENTORY
    Element inventory = player.addElement("Inventory");
    inventory.addElement("Capacity").addText("" + LMS.getPlayer().getInventory().getCapacity());
    inventory.addElement("Quantity").addText("" + LMS.getPlayer().getInventory().getQuantity());
    //////ITEMS
    Element items = inventory.addElement("Items");
    for (int i = 0; i < LMS.getPlayer().getInventory().getItems().size(); i++) {
        Element item = items.addElement("Item").addAttribute("id",
                "" + LMS.getPlayer().getInventory().getItems().get(i).getId());
        item.addElement("stock").addText("" + LMS.getPlayer().getInventory().getItems().get(i).getStock());
    }
    //Mapa Actual
    Element cMap = root.addElement("CurrentMap");
    cMap.addElement("Map").addText("" + getCurrentMap());

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        XMLWriter writer = new XMLWriter(new FileWriter("GameData.xml"), format);
        writer.write(document);
        writer.setIndentLevel(2);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
    }

}