Example usage for org.dom4j DocumentHelper createDocument

List of usage examples for org.dom4j DocumentHelper createDocument

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createDocument.

Prototype

public static Document createDocument() 

Source Link

Usage

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

License:Open Source License

public static Document exportModel(StudentSectioningModel model) {
    Document document = DocumentHelper.createDocument();
    Element requestElement = document.addElement("request");
    requestElement.addAttribute("campus", model.getProperties().getProperty("Data.Initiative"));
    requestElement.addAttribute("year", model.getProperties().getProperty("Data.Year"));
    requestElement.addAttribute("term", model.getProperties().getProperty("Data.Term"));
    for (Student student : model.getStudents()) {
        Element studentElement = requestElement.addElement("student");
        studentElement.addAttribute("key", String.valueOf(student.getId()));
        Element courseRequestsElement = studentElement.addElement("updateCourseRequests");
        courseRequestsElement.addAttribute("commit", "true");
        Collections.sort(student.getRequests(), new Comparator<Request>() {
            @Override//from  www.j av  a2 s .c om
            public int compare(Request r1, Request r2) {
                if (r1.isAlternative() != r2.isAlternative()) {
                    return (r1.isAlternative() ? 1 : -1);
                }
                return Double.compare(r1.getPriority(), r2.getPriority());
            }
        });
        boolean hasSchedule = false;
        for (Request request : student.getRequests()) {
            if (request.getAssignment() != null)
                hasSchedule = true;
            if (request instanceof FreeTimeRequest) {
                FreeTimeRequest ftReq = (FreeTimeRequest) request;
                Element ftReqElement = courseRequestsElement.addElement("freeTime");
                requestElement.addAttribute("days", ftReq.getTime().getDayHeader());
                int startSlot = ftReq.getTime().getStartSlot();
                int startTime = startSlot * Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN;
                ftReqElement.addAttribute("startTime",
                        s2zDF.format(startTime / 60) + s2zDF.format(startTime % 60));
                int endTime = startTime + ftReq.getTime().getLength() * Constants.SLOT_LENGTH_MIN
                        - ftReq.getTime().getBreakTime();
                ftReqElement.addAttribute("endTime", s2zDF.format(endTime / 60) + s2zDF.format(endTime % 60));
                ftReqElement.addAttribute("length",
                        String.valueOf(ftReq.getTime().getLength() * Constants.SLOT_LENGTH_MIN));
            } else {
                CourseRequest crReq = (CourseRequest) request;
                Element crReqElement = courseRequestsElement.addElement("courseOffering");
                Course course = crReq.getCourses().get(0);
                crReqElement.addAttribute("subjectArea", course.getSubjectArea());
                crReqElement.addAttribute("courseNumber", course.getCourseNumber());
                crReqElement.addAttribute("waitlist", crReq.isWaitlist() ? "true" : "false");
                crReqElement.addAttribute("alternative", crReq.isAlternative() ? "true" : "false");
                for (int i = 1; i < crReq.getCourses().size(); i++) {
                    Course altCourse = crReq.getCourses().get(i);
                    Element altCourseElement = crReqElement.addElement("alternative");
                    altCourseElement.addAttribute("subjectArea", altCourse.getSubjectArea());
                    altCourseElement.addAttribute("courseNumber", altCourse.getCourseNumber());
                }
            }
        }
        if (hasSchedule) {
            Element requestScheduleElement = studentElement.addElement("requestSchedule");
            requestScheduleElement.addAttribute("type", "commit");
            for (Request request : student.getRequests()) {
                if (request instanceof CourseRequest) {
                    CourseRequest crReq = (CourseRequest) request;
                    Enrollment enrollment = crReq.getAssignment();
                    if (enrollment == null)
                        continue;
                    Element crReqElement = requestScheduleElement.addElement("courseOffering");
                    Course course = enrollment.getCourse();
                    crReqElement.addAttribute("subjectArea", course.getSubjectArea());
                    crReqElement.addAttribute("courseNumber", course.getCourseNumber());
                    for (Section section : enrollment.getSections()) {
                        Element classEl = crReqElement.addElement("class");
                        classEl.addAttribute("id", section.getSubpart().getInstructionalType());
                        classEl.addAttribute("assignmentId", String.valueOf(section.getId()));
                    }
                }
            }
        }
    }
    return document;
}

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

License:Open Source License

/**
 * Save an XML file// w  ww .  j a v  a2 s  . c o  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.ConfigurationWriter.java

License:Open Source License

/**
 * Writes the modules of the configuration to the output stream.
 *
 * @param out//from  w ww .  java  2  s .co  m
 *            the ouput stream.
 * @param modules
 *            the modules
 * @param checkConfig
 *            the Check configuration object
 * @throws CheckstylePluginException
 *             error writing the checkstyle configuration
 */
public static void write(OutputStream out, List<Module> modules, ICheckConfiguration checkConfig)
        throws CheckstylePluginException {

    try {
        // pass the configured modules through the save filters
        SaveFilters.process(modules);

        Document doc = DocumentHelper.createDocument();
        doc.addDocType(XMLTags.MODULE_TAG, "-//Puppy Crawl//DTD Check Configuration 1.3//EN",
                "http://www.puppycrawl.com/dtds/configuration_1_3.dtd");

        String lineSeperator = System.getProperty("line.separator"); //$NON-NLS-1$

        String comment = lineSeperator
                + "    This configuration file was written by the eclipse-cs plugin configuration editor" //$NON-NLS-1$
                + lineSeperator;
        doc.addComment(comment);

        // write out name and description as comment
        String description = lineSeperator + "    Checkstyle-Configuration: " //$NON-NLS-1$
                + checkConfig.getName() + lineSeperator + "    Description: " //$NON-NLS-1$
                + (StringUtils.trimToNull(checkConfig.getDescription()) != null
                        ? lineSeperator + checkConfig.getDescription() + lineSeperator
                        : "none" + lineSeperator); //$NON-NLS-1$
        doc.addComment(description);

        // find the root module (Checker)
        // the root module is the only module that has no parent
        List<Module> rootModules = getChildModules(null, modules);
        if (rootModules.size() < 1) {
            throw new CheckstylePluginException(Messages.errorNoRootModule);
        }

        if (rootModules.size() > 1) {
            throw new CheckstylePluginException(Messages.errorMoreThanOneRootModule);
        }

        writeModule(rootModules.get(0), doc, null, modules);

        out.write(XMLUtil.toByteArray(doc));
    } catch (IOException e) {
        CheckstylePluginException.rethrow(e);
    }
}

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

License:Open Source License

/**
 * Transforms the check configurations to a document.
 *///from   ww w  .j  a v  a2s  .  c o  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.
 * //from  w  w  w . java  2 s. co m
 * @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.ginp.config.Configuration.java

License:Open Source License

/**
 * @throws java.io.IOException/*  w w  w  .  ja  v a 2  s .c om*/
 * @throws net.sf.ginp.setup.SetupException
 */
private static void readConfig() {
    try {
        //Parse Ginp Config File
        File confFile = new File(configfilelocation);

        if (confFile.exists()) {
            FileInputStream fis = new FileInputStream(confFile);
            SetupManager service = ModelUtil.getSetupManager();
            document = service.testValidConfig(fis);
            configOK = true;
        } else {
            // log that we have no config
            log.warn("No configuration at: " + configfilelocation);
            log.warn("Setting up standard configuration document.");
            configOK = false;

            // Make new default config.
            DefaultDocumentType docType = new DefaultDocumentType("ginp", "-//GINP//DTD ginp XML//EN",
                    "ginp.dtd");

            document = DocumentHelper.createDocument();
            document.setDocType(docType);

            Element root = document.addElement("ginp");
            root.addAttribute("characterencoding", "UTF-8");
            root.addAttribute("thumbsize", "200");
            root.addAttribute("filmstripthumbsize", "100");
            root.addAttribute("picturepagename", "picture.jsp");
            root.addAttribute("collectionpagename", "collection.jsp");

            // TODO: Add Admin
            Element user = root.addElement("user").addAttribute("fullname", "Administrator")
                    .addAttribute("username", "admin").addAttribute("userpass", "");
        }

        // set static vars once.
        forcelocale = document.valueOf("/ginp/@forcelocale");
        thumbSize = document.numberValueOf("/ginp/@thumbsize").intValue();
        filmStripThumbSize = document.numberValueOf("/ginp/@filmstripthumbsize").intValue();
        picturePageName = document.valueOf("/ginp/@picturepagename");
        collectionPageName = document.valueOf("/ginp/@collectionpagename");
        characterEncoding = document.valueOf("/ginp/@characterencoding");

        // wrtie to debug output.
        if (log.isDebugEnabled()) {
            log.debug("Setting Configuation: forcelocale=" + forcelocale);
            log.debug("Setting Configuation: thumbSize=" + thumbSize);
            log.debug("Setting Configuation: filmStripThumbSize=" + filmStripThumbSize);
            log.debug("Setting Configuation: getPicturePageName=" + picturePageName);
            log.debug("Setting Configuation: getCollectionPageName=" + collectionPageName);
            log.debug("Setting Configuation: characterEncoding=" + characterEncoding);
        }

        log.info("Read configuration at: " + configfilelocation);
    } catch (Exception ex) {
        configOK = false;
        log.error("Error reading configuration file located at: " + configfilelocation, ex);
    }
}

From source file:net.sf.jguard.core.util.XMLUtils.java

License:Open Source License

/**
 * read the xml data storage file for users and associated principals.
 *
 * @param xml    file location to read/* w  ww  .  ja va 2 s . c  o  m*/
 * @param schema
 * @return xml content
 */
public static Document read(URL xml, InputSource schema) {

    SAXReader reader = new SAXReader(true);
    Document document;

    try {
        //activate schema validation
        reader.setFeature(XML_VALIDATION, true);
        reader.setFeature(APACHE_VALIDATION, true);
        reader.setProperty(JAXP_SCHEMA_LANGUAGE, JAXP_XML_SCHEMA_LANGUAGE);
        reader.setProperty(JAXP_SCHEMA_SOURCE, schema);

    } catch (SAXException ex) {
        logger.error("read(String) : " + ex.getMessage(), ex);
        throw new IllegalArgumentException(ex.getMessage(), ex);
    }

    try {
        document = reader.read(xml);
    } catch (DocumentException e1) {
        logger.error("read(String) : " + e1, e1);
        throw new IllegalArgumentException(e1.getMessage(), e1);
    }

    if (document == null) {
        logger.warn("we create a default document");
        document = DocumentHelper.createDocument();
    }
    return document;
}

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

License:Open Source License

public static boolean writeAppStatus() {

    try {/*  w  ww  . ja va  2 s .c  o m*/

        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 {// w ww  .j a  va 2  s. c  om

        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  ww w. j  a  v a 2 s .  c  om
        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();
    }

}