Search in sources :

Example 81 with Document

use of org.dom4j.Document in project tesb-studio-se by Talend.

the class KarafJavaScriptForESBWithMavenManager method getOsgiWithMavenManager.

/**
     * DOC ggu Comment method "getOsgiWithMavenManager".
     *
     * @param contextgGroup
     * @return
     */
private OSGIJavaScriptForESBWithMavenManager getOsgiWithMavenManager(final List<ExportFileResource> list, final String talendJobLabel, String contextgGroup) {
    OSGIJavaScriptForESBWithMavenManager osgiWithMavenManager = new OSGIJavaScriptForESBWithMavenManager(new EnumMap<ExportChoice, Object>(this.exportChoice), contextgGroup, JobScriptsManager.LAUNCHER_ALL, IProcessor.NO_STATISTICS, IProcessor.NO_TRACES) {

        @Override
        protected Map<String, String> getMainMavenProperties(Item item) {
            Map<String, String> mavenPropertiesMap = super.getMainMavenProperties(item);
            // same group id with karaf
            mavenPropertiesMap.put(EMavenBuildScriptProperties.ItemGroupName.getVarScript(), getGroupId());
            return mavenPropertiesMap;
        }

        @Override
        protected void setMavenBuildScriptProperties(Document pomDocument, Map<String, String> mavenPropertiesMap) {
            super.setMavenBuildScriptProperties(pomDocument, mavenPropertiesMap);
            String itemName = mavenPropertiesMap.get(EMavenBuildScriptProperties.ItemName.getVarScript());
            if (itemName != null && pomDocument != null) {
                Element rootElement = pomDocument.getRootElement();
                // Because re-use the osgi bundle for service, but for artifactId, there is no "-bundle"
                // suffix. TDI-23491
                Element artifactIdEle = rootElement.element(IMavenProperties.ELE_ARTIFACT_ID);
                if (artifactIdEle != null) {
                    artifactIdEle.setText(itemName);
                }
            }
        }

        @Override
        protected String getTmpFolder() {
            return getSystemTempFolder().getAbsolutePath();
        }

        @Override
        public void setTopFolder(List<ExportFileResource> resourcesToExport) {
            super.setTopFolder(resourcesToExport);
            // TDI-23377, need reset the path and add it in for route exporting.
            for (ExportFileResource fileResource : resourcesToExport) {
                String directory = fileResource.getDirectoryName();
                fileResource.setDirectoryName(TALEND_JOBS_PATH + talendJobLabel + PATH_SEPARATOR + directory);
                // add to current route to export
                list.add(fileResource);
            }
        }
    };
    return osgiWithMavenManager;
}
Also used : CamelProcessItem(org.talend.camel.core.model.camelProperties.CamelProcessItem) Item(org.talend.core.model.properties.Item) ProcessItem(org.talend.core.model.properties.ProcessItem) OSGIJavaScriptForESBWithMavenManager(org.talend.repository.ui.wizards.exportjob.scriptsmanager.esb.OSGIJavaScriptForESBWithMavenManager) ExportFileResource(org.talend.repository.documentation.ExportFileResource) Element(org.dom4j.Element) IRepositoryViewObject(org.talend.core.model.repository.IRepositoryViewObject) List(java.util.List) EList(org.eclipse.emf.common.util.EList) Document(org.dom4j.Document) Map(java.util.Map) EnumMap(java.util.EnumMap) HashMap(java.util.HashMap)

Example 82 with Document

use of org.dom4j.Document in project tesb-studio-se by Talend.

the class ExportServiceWithMavenAction method addJobFilesToExport.

private void addJobFilesToExport(IProgressMonitor monitor) throws Exception {
    String directoryName = serviceManager.getRootFolderName(tempFolder);
    exportChoiceMap.put(ExportChoice.needJobItem, false);
    for (IRepositoryViewObject node : nodes) {
        JobScriptsManager osgiManager = new OSGIJavaScriptForESBWithMavenManager(exportChoiceMap, IContext.DEFAULT, JobScriptsManager.LAUNCHER_ALL, IProcessor.NO_STATISTICS, IProcessor.NO_TRACES) {

            @Override
            protected Map<String, String> getMainMavenProperties(Item item) {
                Map<String, String> mavenPropertiesMap = super.getMainMavenProperties(item);
                mavenPropertiesMap.put(EMavenBuildScriptProperties.ItemGroupName.getVarScript(), getGroupId());
                return mavenPropertiesMap;
            }

            @Override
            protected void setMavenBuildScriptProperties(Document pomDocument, Map<String, String> mavenPropertiesMap) {
                super.setMavenBuildScriptProperties(pomDocument, mavenPropertiesMap);
                String itemName = mavenPropertiesMap.get(EMavenBuildScriptProperties.ItemName.getVarScript());
                if (itemName != null && pomDocument != null) {
                    Element rootElement = pomDocument.getRootElement();
                    // Because re-use the osgi bundle for service, but for artifactId, there is no "-bundle"
                    // suffix. TDI-23491
                    //$NON-NLS-1$
                    Element artifactIdEle = rootElement.element("artifactId");
                    if (artifactIdEle != null) {
                        artifactIdEle.setText(itemName);
                    }
                }
            }
        };
        String artefactName = serviceManager.getNodeLabel(node);
        String version = node.getVersion();
        // String fileName = artefactName + "-" + version;
        File destFile = new File(tempFolder + PATH_SEPERATOR + artefactName + osgiManager.getOutputSuffix());
        String destinationPath = destFile.getAbsolutePath();
        osgiManager.setDestinationPath(destinationPath);
        JobExportAction job = new JobExportAction(Collections.singletonList(new RepositoryNode(node, null, ENodeType.REPOSITORY_ELEMENT)), version, osgiManager, directoryName);
        job.run(monitor);
        ZipToFile.unZipFile(destinationPath, tempFolder + PATH_SEPERATOR + ServiceExportWithMavenManager.OPERATIONS_PATH + artefactName);
        FilesUtils.removeFile(destFile);
    }
}
Also used : ServiceItem(org.talend.repository.services.model.services.ServiceItem) Item(org.talend.core.model.properties.Item) OSGIJavaScriptForESBWithMavenManager(org.talend.repository.ui.wizards.exportjob.scriptsmanager.esb.OSGIJavaScriptForESBWithMavenManager) JobScriptsManager(org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobScriptsManager) Element(org.dom4j.Element) IRepositoryViewObject(org.talend.core.model.repository.IRepositoryViewObject) JobExportAction(org.talend.repository.ui.wizards.exportjob.action.JobExportAction) Document(org.dom4j.Document) RepositoryNode(org.talend.repository.model.RepositoryNode) Map(java.util.Map) ZipToFile(org.talend.repository.ui.utils.ZipToFile) File(java.io.File)

Example 83 with Document

use of org.dom4j.Document in project cpsolver by UniTime.

the class Test method main.

/**
     * Main program
     * 
     * @param args
     *            problem property file, input file (optional, may be set by
     *            General.Input property), output file (optional, may be set by
     *            General.OutputFile property)
     */
public static void main(String[] args) {
    try {
        DataProperties cfg = new DataProperties();
        cfg.setProperty("Termination.StopWhenComplete", "false");
        cfg.setProperty("Termination.TimeOut", "1800");
        cfg.setProperty("General.SaveBestUnassigned", "-1");
        cfg.setProperty("Neighbour.Class", "org.cpsolver.exam.heuristics.ExamNeighbourSelection");
        if (args.length >= 1) {
            cfg.load(new FileInputStream(args[0]));
            cfg.setProperty("General.Config", new File(args[0]).getName());
        }
        cfg.putAll(System.getProperties());
        File inputFile = new File("c:\\test\\exam\\exam1070.xml");
        if (args.length >= 2) {
            inputFile = new File(args[1]);
        }
        ToolBox.setSeed(cfg.getPropertyLong("General.Seed", Math.round(Long.MAX_VALUE * Math.random())));
        cfg.setProperty("General.Input", inputFile.toString());
        String outName = inputFile.getName();
        if (outName.indexOf('.') >= 0)
            outName = outName.substring(0, outName.lastIndexOf('.')) + "s.xml";
        File outFile = new File(inputFile.getParentFile(), outName);
        if (args.length >= 3) {
            outFile = new File(args[2]);
            if (outFile.exists() && outFile.isDirectory())
                outFile = new File(outFile, outName);
            if (!outFile.exists() && !outFile.getName().endsWith(".xml"))
                outFile = new File(outFile, outName);
        }
        if (outFile.getParentFile() != null)
            outFile.getParentFile().mkdirs();
        cfg.setProperty("General.OutputFile", outFile.toString());
        cfg.setProperty("General.Output", outFile.getParent());
        String logName = outFile.getName();
        if (logName.indexOf('.') >= 0)
            logName = logName.substring(0, logName.lastIndexOf('.')) + ".log";
        setupLogging(new File(outFile.getParent(), logName), "true".equals(System.getProperty("debug", "false")));
        ExamModel model = new ExamModel(cfg);
        Document document = (new SAXReader()).read(new File(cfg.getProperty("General.Input")));
        int nrSolvers = cfg.getPropertyInt("Parallel.NrSolvers", 1);
        Assignment<Exam, ExamPlacement> assignment = (nrSolvers <= 1 ? new DefaultSingleAssignment<Exam, ExamPlacement>() : new DefaultParallelAssignment<Exam, ExamPlacement>());
        model.load(document, assignment);
        Solver<Exam, ExamPlacement> solver = (nrSolvers == 1 ? new Solver<Exam, ExamPlacement>(cfg) : new ParallelSolver<Exam, ExamPlacement>(cfg));
        solver.setInitalSolution(new Solution<Exam, ExamPlacement>(model, assignment));
        solver.currentSolution().addSolutionListener(new SolutionListener<Exam, ExamPlacement>() {

            @Override
            public void solutionUpdated(Solution<Exam, ExamPlacement> solution) {
            }

            @Override
            public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info) {
            }

            @Override
            public void getInfo(Solution<Exam, ExamPlacement> solution, Map<String, String> info, Collection<Exam> variables) {
            }

            @Override
            public void bestCleared(Solution<Exam, ExamPlacement> solution) {
            }

            @Override
            public void bestSaved(Solution<Exam, ExamPlacement> solution) {
                ExamModel m = (ExamModel) solution.getModel();
                Assignment<Exam, ExamPlacement> a = solution.getAssignment();
                if (sLog.isInfoEnabled()) {
                    sLog.info("**BEST[" + solution.getIteration() + "]** " + (m.variables().size() > a.nrAssignedVariables() ? "V:" + a.nrAssignedVariables() + "/" + m.variables().size() + " - " : "") + "T:" + new DecimalFormat("0.00").format(m.getTotalValue(a)) + " " + m.toString(a) + (solution.getFailedIterations() > 0 ? ", F:" + sDoubleFormat.format(100.0 * solution.getFailedIterations() / solution.getIteration()) + "%" : ""));
                }
            }

            @Override
            public void bestRestored(Solution<Exam, ExamPlacement> solution) {
            }
        });
        Runtime.getRuntime().addShutdownHook(new ShutdownHook(solver));
        solver.start();
        try {
            solver.getSolverThread().join();
        } catch (InterruptedException e) {
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Solver(org.cpsolver.ifs.solver.Solver) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) DefaultParallelAssignment(org.cpsolver.ifs.assignment.DefaultParallelAssignment) ExamModel(org.cpsolver.exam.model.ExamModel) SAXReader(org.dom4j.io.SAXReader) DecimalFormat(java.text.DecimalFormat) DataProperties(org.cpsolver.ifs.util.DataProperties) Document(org.dom4j.Document) DefaultParallelAssignment(org.cpsolver.ifs.assignment.DefaultParallelAssignment) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) Assignment(org.cpsolver.ifs.assignment.Assignment) ExamStudentConflictsPerExam(org.cpsolver.exam.reports.ExamStudentConflictsPerExam) Exam(org.cpsolver.exam.model.Exam) ParallelSolver(org.cpsolver.ifs.solver.ParallelSolver) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ExamPlacement(org.cpsolver.exam.model.ExamPlacement) DefaultSingleAssignment(org.cpsolver.ifs.assignment.DefaultSingleAssignment) File(java.io.File)

Example 84 with Document

use of org.dom4j.Document in project cpsolver by UniTime.

the class InstructorSchedulingModel method save.

/**
     * Store the problem (together with its solution) in an XML format
     * @param assignment current assignment
     * @return XML document with the problem
     */
public Document save(Assignment<TeachingRequest.Variable, TeachingAssignment> assignment) {
    DecimalFormat sDF7 = new DecimalFormat("0000000");
    boolean saveInitial = getProperties().getPropertyBoolean("Xml.SaveInitial", false);
    boolean saveBest = getProperties().getPropertyBoolean("Xml.SaveBest", false);
    boolean saveSolution = getProperties().getPropertyBoolean("Xml.SaveSolution", true);
    Document document = DocumentHelper.createDocument();
    if (assignment != null && assignment.nrAssignedVariables() > 0) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getProperties().getPropertyBoolean("Xml.ExtendedInfo", true) ? getExtendedInfo(assignment) : getInfo(assignment));
        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("instructor-schedule");
    root.addAttribute("version", "1.0");
    root.addAttribute("created", String.valueOf(new Date()));
    Element typesEl = root.addElement("attributes");
    for (Attribute.Type type : getAttributeTypes()) {
        Element typeEl = typesEl.addElement("type");
        if (type.getTypeId() != null)
            typeEl.addAttribute("id", String.valueOf(type.getTypeId()));
        typeEl.addAttribute("name", type.getTypeName());
        typeEl.addAttribute("conjunctive", type.isConjunctive() ? "true" : "false");
        typeEl.addAttribute("required", type.isRequired() ? "true" : "false");
        Set<Attribute> attributes = new HashSet<Attribute>();
        for (TeachingRequest request : getRequests()) {
            for (Preference<Attribute> pref : request.getAttributePreferences()) {
                Attribute attribute = pref.getTarget();
                if (type.equals(attribute.getType()) && attributes.add(attribute)) {
                    Element attributeEl = typeEl.addElement("attribute");
                    if (attribute.getAttributeId() != null)
                        attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
                    attributeEl.addAttribute("name", attribute.getAttributeName());
                    if (attribute.getParentAttribute() != null && attribute.getParentAttribute().getAttributeId() != null)
                        attributeEl.addAttribute("parent", String.valueOf(attribute.getParentAttribute().getAttributeId()));
                }
            }
            for (Instructor instructor : getInstructors()) {
                for (Attribute attribute : instructor.getAttributes()) {
                    if (type.equals(attribute.getType()) && attributes.add(attribute)) {
                        Element attributeEl = typeEl.addElement("attribute");
                        if (attribute.getAttributeId() != null)
                            attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
                        attributeEl.addAttribute("name", attribute.getAttributeName());
                        if (attribute.getParentAttribute() != null && attribute.getParentAttribute().getAttributeId() != null)
                            attributeEl.addAttribute("parent", String.valueOf(attribute.getParentAttribute().getAttributeId()));
                    }
                }
            }
        }
    }
    Element requestsEl = root.addElement("teaching-requests");
    for (TeachingRequest request : getRequests()) {
        Element requestEl = requestsEl.addElement("request");
        requestEl.addAttribute("id", String.valueOf(request.getRequestId()));
        if (request.getNrInstructors() != 1)
            requestEl.addAttribute("nrInstructors", String.valueOf(request.getNrInstructors()));
        Course course = request.getCourse();
        Element courseEl = requestEl.addElement("course");
        if (course.getCourseId() != null)
            courseEl.addAttribute("id", String.valueOf(course.getCourseId()));
        if (course.getCourseName() != null)
            courseEl.addAttribute("name", String.valueOf(course.getCourseName()));
        for (Section section : request.getSections()) {
            Element sectionEl = requestEl.addElement("section");
            sectionEl.addAttribute("id", String.valueOf(section.getSectionId()));
            if (section.getExternalId() != null && !section.getExternalId().isEmpty())
                sectionEl.addAttribute("externalId", section.getExternalId());
            if (section.getSectionType() != null && !section.getSectionType().isEmpty())
                sectionEl.addAttribute("type", section.getSectionType());
            if (section.getSectionName() != null && !section.getSectionName().isEmpty())
                sectionEl.addAttribute("name", section.getSectionName());
            if (section.hasTime()) {
                TimeLocation tl = section.getTime();
                Element timeEl = sectionEl.addElement("time");
                timeEl.addAttribute("days", sDF7.format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                timeEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                timeEl.addAttribute("length", String.valueOf(tl.getLength()));
                if (tl.getBreakTime() != 0)
                    timeEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
                if (tl.getTimePatternId() != null)
                    timeEl.addAttribute("pattern", tl.getTimePatternId().toString());
                if (tl.getDatePatternId() != null)
                    timeEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                if (tl.getDatePatternName() != null && !tl.getDatePatternName().isEmpty())
                    timeEl.addAttribute("datePatternName", tl.getDatePatternName());
                if (tl.getWeekCode() != null)
                    timeEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                timeEl.setText(tl.getLongName(false));
            }
            if (section.hasRoom())
                sectionEl.addAttribute("room", section.getRoom());
            if (section.isAllowOverlap())
                sectionEl.addAttribute("canOverlap", "true");
            if (section.isCommon())
                sectionEl.addAttribute("common", "true");
        }
        requestEl.addAttribute("load", sDoubleFormat.format(request.getLoad()));
        requestEl.addAttribute("sameCourse", Constants.preferenceLevel2preference(request.getSameCoursePreference()));
        requestEl.addAttribute("sameCommon", Constants.preferenceLevel2preference(request.getSameCommonPreference()));
        for (Preference<Attribute> pref : request.getAttributePreferences()) {
            Element attributeEl = requestEl.addElement("attribute");
            if (pref.getTarget().getAttributeId() != null)
                attributeEl.addAttribute("id", String.valueOf(pref.getTarget().getAttributeId()));
            attributeEl.addAttribute("name", pref.getTarget().getAttributeName());
            attributeEl.addAttribute("type", pref.getTarget().getType().getTypeName());
            attributeEl.addAttribute("preference", (pref.isRequired() ? "R" : pref.isProhibited() ? "P" : String.valueOf(pref.getPreference())));
            if (pref.getTarget().getParentAttribute() != null && pref.getTarget().getParentAttribute().getAttributeId() != null)
                attributeEl.addAttribute("parent", String.valueOf(pref.getTarget().getParentAttribute().getAttributeId()));
        }
        for (Preference<Instructor> pref : request.getInstructorPreferences()) {
            Element instructorEl = requestEl.addElement("instructor");
            instructorEl.addAttribute("id", String.valueOf(pref.getTarget().getInstructorId()));
            if (pref.getTarget().hasExternalId())
                instructorEl.addAttribute("externalId", pref.getTarget().getExternalId());
            if (pref.getTarget().hasName())
                instructorEl.addAttribute("name", pref.getTarget().getName());
            instructorEl.addAttribute("preference", (pref.isRequired() ? "R" : pref.isProhibited() ? "P" : String.valueOf(pref.getPreference())));
        }
        if (saveBest)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                if (variable.getBestAssignment() != null) {
                    Instructor instructor = variable.getBestAssignment().getInstructor();
                    Element instructorEl = requestEl.addElement("best-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
        if (saveInitial)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                if (variable.getInitialAssignment() != null) {
                    Instructor instructor = variable.getInitialAssignment().getInstructor();
                    Element instructorEl = requestEl.addElement("initial-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
        if (saveSolution)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                TeachingAssignment ta = assignment.getValue(variable);
                if (ta != null) {
                    Instructor instructor = ta.getInstructor();
                    Element instructorEl = requestEl.addElement("assigned-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
    }
    Element instructorsEl = root.addElement("instructors");
    for (Instructor instructor : getInstructors()) {
        Element instructorEl = instructorsEl.addElement("instructor");
        instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
        if (instructor.hasExternalId())
            instructorEl.addAttribute("externalId", instructor.getExternalId());
        if (instructor.hasName())
            instructorEl.addAttribute("name", instructor.getName());
        if (instructor.getPreference() != 0)
            instructorEl.addAttribute("preference", String.valueOf(instructor.getPreference()));
        if (instructor.getBackToBackPreference() != 0)
            instructorEl.addAttribute("btb", String.valueOf(instructor.getBackToBackPreference()));
        if (instructor.getSameDaysPreference() != 0)
            instructorEl.addAttribute("same-days", String.valueOf(instructor.getSameDaysPreference()));
        if (instructor.getSameRoomPreference() != 0)
            instructorEl.addAttribute("same-room", String.valueOf(instructor.getSameRoomPreference()));
        for (Attribute attribute : instructor.getAttributes()) {
            Element attributeEl = instructorEl.addElement("attribute");
            if (attribute.getAttributeId() != null)
                attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
            attributeEl.addAttribute("name", attribute.getAttributeName());
            attributeEl.addAttribute("type", attribute.getType().getTypeName());
            if (attribute.getParentAttribute() != null && attribute.getParentAttribute().getAttributeId() != null)
                attributeEl.addAttribute("parent", String.valueOf(attribute.getParentAttribute().getAttributeId()));
        }
        instructorEl.addAttribute("maxLoad", sDoubleFormat.format(instructor.getMaxLoad()));
        for (Preference<TimeLocation> tp : instructor.getTimePreferences()) {
            Element timeEl = instructorEl.addElement("time");
            TimeLocation tl = tp.getTarget();
            timeEl.addAttribute("days", sDF7.format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
            timeEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
            timeEl.addAttribute("length", String.valueOf(tl.getLength()));
            if (tl.getBreakTime() != 0)
                timeEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
            if (tl.getTimePatternId() != null)
                timeEl.addAttribute("pattern", tl.getTimePatternId().toString());
            if (tl.getDatePatternId() != null)
                timeEl.addAttribute("datePattern", tl.getDatePatternId().toString());
            if (tl.getDatePatternName() != null && !tl.getDatePatternName().isEmpty())
                timeEl.addAttribute("datePatternName", tl.getDatePatternName());
            if (tl.getWeekCode() != null)
                timeEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
            timeEl.addAttribute("preference", tp.isProhibited() ? "P" : tp.isRequired() ? "R" : String.valueOf(tp.getPreference()));
            if (tp.getTarget() instanceof EnrolledClass) {
                Element classEl = timeEl.addElement("section");
                Element courseEl = null;
                EnrolledClass ec = (EnrolledClass) tp.getTarget();
                if (ec.getCourseId() != null || ec.getCourse() != null) {
                    courseEl = timeEl.addElement("course");
                    if (ec.getCourseId() != null)
                        courseEl.addAttribute("id", String.valueOf(ec.getCourseId()));
                    if (ec.getCourse() != null)
                        courseEl.addAttribute("name", ec.getCourse());
                }
                if (ec.getClassId() != null)
                    classEl.addAttribute("id", String.valueOf(ec.getClassId()));
                if (ec.getType() != null)
                    classEl.addAttribute("type", ec.getType());
                if (ec.getSection() != null)
                    classEl.addAttribute("name", ec.getSection());
                if (ec.getExternalId() != null)
                    classEl.addAttribute("externalId", ec.getExternalId());
                if (ec.getRoom() != null)
                    classEl.addAttribute("room", ec.getRoom());
                classEl.addAttribute("role", ec.isInstructor() ? "instructor" : "student");
            } else {
                timeEl.setText(tl.getLongName(false));
            }
        }
        for (Preference<Course> cp : instructor.getCoursePreferences()) {
            Element courseEl = instructorEl.addElement("course");
            Course course = cp.getTarget();
            if (course.getCourseId() != null)
                courseEl.addAttribute("id", String.valueOf(course.getCourseId()));
            if (course.getCourseName() != null)
                courseEl.addAttribute("name", String.valueOf(course.getCourseName()));
            courseEl.addAttribute("preference", cp.isProhibited() ? "P" : cp.isRequired() ? "R" : String.valueOf(cp.getPreference()));
        }
    }
    Element constraintsEl = root.addElement("constraints");
    for (Constraint<TeachingRequest.Variable, TeachingAssignment> c : constraints()) {
        if (c instanceof SameInstructorConstraint) {
            SameInstructorConstraint si = (SameInstructorConstraint) c;
            Element sameInstEl = constraintsEl.addElement("same-instructor");
            if (si.getConstraintId() != null)
                sameInstEl.addAttribute("id", String.valueOf(si.getConstraintId()));
            if (si.getName() != null)
                sameInstEl.addAttribute("name", si.getName());
            sameInstEl.addAttribute("preference", Constants.preferenceLevel2preference(si.getPreference()));
            for (TeachingRequest.Variable request : c.variables()) {
                Element assignmentEl = sameInstEl.addElement("request");
                assignmentEl.addAttribute("id", String.valueOf(request.getRequest().getRequestId()));
                if (request.getRequest().getNrInstructors() != 1)
                    assignmentEl.addAttribute("index", String.valueOf(request.getInstructorIndex()));
            }
        } else if (c instanceof SameLinkConstraint) {
            SameLinkConstraint si = (SameLinkConstraint) c;
            Element sameInstEl = constraintsEl.addElement("same-link");
            if (si.getConstraintId() != null)
                sameInstEl.addAttribute("id", String.valueOf(si.getConstraintId()));
            if (si.getName() != null)
                sameInstEl.addAttribute("name", si.getName());
            sameInstEl.addAttribute("preference", Constants.preferenceLevel2preference(si.getPreference()));
            for (TeachingRequest.Variable request : c.variables()) {
                Element assignmentEl = sameInstEl.addElement("request");
                assignmentEl.addAttribute("id", String.valueOf(request.getRequest().getRequestId()));
                if (request.getRequest().getNrInstructors() != 1)
                    assignmentEl.addAttribute("index", String.valueOf(request.getInstructorIndex()));
            }
        }
    }
    return document;
}
Also used : TimeLocation(org.cpsolver.coursett.model.TimeLocation) DecimalFormat(java.text.DecimalFormat) Element(org.dom4j.Element) SameInstructor(org.cpsolver.instructor.criteria.SameInstructor) OriginalInstructor(org.cpsolver.instructor.criteria.OriginalInstructor) Document(org.dom4j.Document) SameLinkConstraint(org.cpsolver.instructor.constraints.SameLinkConstraint) TreeSet(java.util.TreeSet) SameCourse(org.cpsolver.instructor.criteria.SameCourse) HashSet(java.util.HashSet) SameInstructorConstraint(org.cpsolver.instructor.constraints.SameInstructorConstraint) Date(java.util.Date)

Example 85 with Document

use of org.dom4j.Document in project cpsolver by UniTime.

the class StudentRequestXml method exportModel.

public static Document exportModel(Assignment<Request, Enrollment> assignment, 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
            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 (assignment.getValue(request) != 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 = assignment.getValue(crReq);
                    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;
}
Also used : FreeTimeRequest(org.cpsolver.studentsct.model.FreeTimeRequest) Element(org.dom4j.Element) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) FreeTimeRequest(org.cpsolver.studentsct.model.FreeTimeRequest) Request(org.cpsolver.studentsct.model.Request) Document(org.dom4j.Document) Student(org.cpsolver.studentsct.model.Student) Section(org.cpsolver.studentsct.model.Section) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) Enrollment(org.cpsolver.studentsct.model.Enrollment) Course(org.cpsolver.studentsct.model.Course)

Aggregations

Document (org.dom4j.Document)288 Element (org.dom4j.Element)192 SAXReader (org.dom4j.io.SAXReader)143 Test (org.junit.Test)102 StringReader (java.io.StringReader)88 File (java.io.File)57 ArrayList (java.util.ArrayList)47 List (java.util.List)40 IOException (java.io.IOException)27 DocumentException (org.dom4j.DocumentException)25 XMLWriter (org.dom4j.io.XMLWriter)22 HashMap (java.util.HashMap)19 Map (java.util.Map)18 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)17 LinkedList (java.util.LinkedList)16 Attribute (org.dom4j.Attribute)15 Node (org.dom4j.Node)14 FileOutputStream (java.io.FileOutputStream)11 DavException (com.zimbra.cs.dav.DavException)10 OutputFormat (org.dom4j.io.OutputFormat)9