Java Code Examples for org.dom4j.Document#addDocType()

The following examples show how to use org.dom4j.Document#addDocType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StudentExport.java    From unitime with Apache License 2.0 6 votes vote down vote up
@Override
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();
		
		Element root = document.addElement("students");
        root.addAttribute("campus", session.getAcademicInitiative());
        root.addAttribute("year", session.getAcademicYear());
        root.addAttribute("term", session.getAcademicTerm());
        
        document.addDocType("students", "-//UniTime//UniTime Students DTD/EN", "http://www.unitime.org/interface/Student.dtd");
        
        for (Student student: (List<Student>)getHibSession().createQuery(
        		"select s from Student s where s.session.uniqueId = :sessionId")
        		.setLong("sessionId", session.getUniqueId()).list()) {
        	
        	Element studentEl = root.addElement("student");
        	exportStudent(studentEl, student);
        }
        
           commitTransaction();
       } catch (Exception e) {
           fatal("Exception: "+e.getMessage(),e);
           rollbackTransaction();
	}
}
 
Example 2
Source File: PermissionsExport.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();

        Element root = document.addElement("permissions");
        root.addAttribute("created", new Date().toString());

        document.addDocType("permissions", "-//UniTime//DTD University Course Timetabling/EN", "http://www.unitime.org/interface/Permissions.dtd");
        
		for (Roles role: RolesDAO.getInstance().findAll(getHibSession(), Order.asc("abbv"))) {
			Element r = root.addElement("role");
			r.addAttribute("reference", role.getReference());
			r.addAttribute("name", role.getAbbv());
			r.addAttribute("manager", role.isManager() ? "true" : "false");
			r.addAttribute("enabled", role.isEnabled() ? "true" : "false");
			r.addAttribute("instructor", role.isInstructor() ? "true" : "false");
			for (Right right: Right.values()) {
				if (role.hasRight(right))
					r.addElement("right").setText(right.name());
			}
		}

        commitTransaction();
    } catch (Exception e) {
        fatal("Exception: "+e.getMessage(),e);
        rollbackTransaction();
    }
}
 
Example 3
Source File: ConfigurationWriter.java    From eclipse-cs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Writes the modules of the configuration to the output stream.
 *
 * @param out
 *          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, "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN",
            "https://checkstyle.org/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$
            + (Strings.emptyToNull(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);
  }
}
 
Example 4
Source File: XmlExport.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
public static Element createRoot(Document document) {
	document.addDocType("properties", null, "http://java.sun.com/dtd/properties.dtd");
	return document.addElement("properties");
}
 
Example 5
Source File: HQLExportXML.java    From unitime with Apache License 2.0 4 votes vote down vote up
@Override
public void export(ExportHelper helper) throws IOException {
	String s = helper.getParameter("id");
	if (s == null)
		throw new IllegalArgumentException("No report provided, please set the id parameter.");
	SavedHQL report = SavedHQLDAO.getInstance().get(Long.valueOf(s));
	if (report == null)
		throw new IllegalArgumentException("Report " + s + " does not exist.");

	helper.getSessionContext().checkPermission(report, Right.HQLReportEdit);

	helper.setup("text/xml", report.getName().replace('/', '-').replace('\\', '-').replace(':', '-') + ".xml",
			false);

	Document document = DocumentHelper.createDocument();
	document.addDocType("report", "-//UniTime//UniTime HQL Reports DTD/EN",
			"http://www.unitime.org/interface/Reports.dtd");
	Element reportEl = document.addElement("report");
	reportEl.addAttribute("name", report.getName());
	for (SavedHQL.Flag flag : SavedHQL.Flag.values()) {
		if (report.isSet(flag))
			reportEl.addElement("flag").setText(flag.name());
	}
	if (report.getDescription() != null)
		reportEl.addElement("description").add(new DOMCDATA(report.getDescription()));
	if (report.getQuery() != null)
		reportEl.addElement("query").add(new DOMCDATA(report.getQuery()));
       for (SavedHQLParameter parameter: report.getParameters()) {
       	Element paramEl = reportEl.addElement("parameter");
       	paramEl.addAttribute("name", parameter.getName());
       	if (parameter.getLabel() != null)
       		paramEl.addAttribute("label", parameter.getLabel());
       	paramEl.addAttribute("type", parameter.getType());
       	if (parameter.getDefaultValue() != null)
       		paramEl.addAttribute("default", parameter.getDefaultValue());
       }
	reportEl.addAttribute("created", new Date().toString());

	OutputStream out = helper.getOutputStream();
	new XMLWriter(out, OutputFormat.createPrettyPrint()).write(document);
}
 
Example 6
Source File: StudentAdvisorsExport.java    From unitime with Apache License 2.0 4 votes vote down vote up
@Override
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();
		
		Element root = document.addElement("studentAdvisors");
        root.addAttribute("campus", session.getAcademicInitiative());
        root.addAttribute("year", session.getAcademicYear());
        root.addAttribute("term", session.getAcademicTerm());
        root.addAttribute("created", new Date().toString());
        
        document.addDocType("studentAdvisors", "-//UniTime//UniTime Student Advisors DTD/EN", "http://www.unitime.org/interface/StudentAdvisors.dtd");
        
        for (Advisor advisor: (List<Advisor>)getHibSession().createQuery(
        		"from Advisor a where a.session.uniqueId = :sessionId order by a.lastName, a.firstName, a.externalUniqueId").setLong("sessionId", session.getUniqueId()).list()) {
        	Element advisorEl = root.addElement("studentAdvisor");
        	advisorEl.addAttribute("externalId", advisor.getExternalUniqueId());
        	if (advisor.getFirstName() != null)
        		advisorEl.addAttribute("firstName", advisor.getFirstName());
        	if (advisor.getMiddleName() != null)
        		advisorEl.addAttribute("middleName", advisor.getMiddleName());
        	if (advisor.getLastName() != null)
        		advisorEl.addAttribute("lastName", advisor.getLastName());
        	if (advisor.getAcademicTitle() != null)
        		advisorEl.addAttribute("acadTitle", advisor.getAcademicTitle());
        	if (advisor.getEmail() != null)
        		advisorEl.addAttribute("email", advisor.getEmail());
        	if (advisor.getRole() != null)
        		advisorEl.addAttribute("role", advisor.getRole().getReference());

        	Element updateStudentsEl = advisorEl.addElement("updateStudents");
        	if (advisor.getStudents() != null)
        		for (Student student: advisor.getStudents())
        			if (student.getExternalUniqueId() != null)
        				updateStudentsEl.addElement("student").addAttribute("externalId", student.getExternalUniqueId());
        }
        
           commitTransaction();
       } catch (Exception e) {
           fatal("Exception: "+e.getMessage(),e);
           rollbackTransaction();
	}
}
 
Example 7
Source File: RoomSharingExport.java    From unitime with Apache License 2.0 4 votes vote down vote up
@Override
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();

		Element root = document.addElement("roomSharing");
		root.addAttribute("campus", session.getAcademicInitiative());
		root.addAttribute("year", session.getAcademicYear());
		root.addAttribute("term", session.getAcademicTerm());
		root.addAttribute("created", new Date().toString());
		root.addAttribute("timeFormat", "HHmm");
		

		document.addDocType("roomSharing", "-//UniTime//UniTime Room Sharing DTD/EN", "http://www.unitime.org/interface/RoomSharing.dtd");

		List<Location> locations = Location.findAll(session.getUniqueId());
		Collections.sort(locations);

		for (Location location : locations) {
			Element locEl = root.addElement("location");
			fillLocationData(location, locEl);
			if (location.getShareNote() != null)
				locEl.addAttribute("note", location.getShareNote());
			Map<Long, Department> id2dept = new HashMap<Long, Department>();
			for (RoomDept rd : location.getRoomDepts()) {
				Element deptEl = locEl.addElement("department");
				fillDepartmentData(rd, deptEl);
				id2dept.put(rd.getDepartment().getUniqueId(), rd.getDepartment());
			}
			RoomSharingModel model = location.getRoomSharingModel();
			if (model != null && !model.allAvailable(null)) {
				Element sharingEl = locEl.addElement("sharing");
				boolean out[][] = new boolean[model.getNrDays()][model.getNrTimes()];
				for (int i = 0; i < model.getNrDays(); i++)
					for (int j = 0; j < model.getNrTimes(); j++)
						out[i][j] = false;
				for (int i = 0; i < model.getNrDays(); i++)
					for (int j = 0; j < model.getNrTimes(); j++) {
						if (out[i][j])
							continue;
						out[i][j] = true;
						if (model.isFreeForAll(i, j))
							continue;
						int endDay = i, endTime = j;
						String p = model.getPreference(i, j);
						while (endTime + 1 < model.getNrTimes() && !out[i][endTime + 1] && model.getPreference(i, endTime + 1).equals(p))
							endTime++;
						while (endDay + 1 < model.getNrDays()) {
							boolean same = true;
							for (int x = j; x <= endTime; x++)
								if (!out[endDay + 1][x] && !model.getPreference(endDay + 1, x).equals(p)) {
									same = false;
									break;
								}
							if (!same)
								break;
							endDay++;
						}
						for (int a = i; a <= endDay; a++)
							for (int b = j; b <= endTime; b++)
								out[a][b] = true;
						Element el = null;
						Department dept = null;
						if (model.isNotAvailable(i, j)) {
							el = sharingEl.addElement("unavailable");
						} else {
							dept = id2dept.get(model.getDepartmentId(i, j));
							if (dept == null)
								continue;
							el = sharingEl.addElement("assigned");
						}
						if (i == 0 && endDay + 1 == model.getNrDays()) {
							// all week
						} else {
							String day = "";
							for (int a = i; a <= endDay; a++)
								day += Constants.DAY_NAMES_SHORT[a];
							el.addAttribute("days", day);
						}
						if (j == 0 && endTime + 1 == model.getNrTimes()) {
							// all day
						} else {
							el.addAttribute("start", slot2time(j));
							el.addAttribute("end", slot2time(endTime + 1));
						}
						if (dept != null)
							fillDepartmentData(dept, el);
					}
			}
		}

		commitTransaction();
	} catch (Exception e) {
		fatal("Exception: " + e.getMessage(), e);
		rollbackTransaction();
	}
}
 
Example 8
Source File: PointInTimeDataExport.java    From unitime with Apache License 2.0 4 votes vote down vote up
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
    try {
        beginTransaction();
        Date timestamp = new Date();
        info("Data extract for Point in Time Data started at:  " + timestamp.toString());
        Element root = document.addElement(sRootElementName);
        root.addAttribute(sAcademicSessionUniqueIdAttribute, session.getUniqueId().toString());
        root.addAttribute(sAcademicInitiativeAttribute, session.getAcademicInitiative());
        root.addAttribute(sAcademicYearAttribute, session.getAcademicYear());
        root.addAttribute(sAcademicTermAttribute, session.getAcademicTerm());
        root.addAttribute(sDateFormatAttribute, sDateFormat.toPattern());
        root.addAttribute(sTimeFormatAttribute, sTimeFormat.toPattern());
        root.addAttribute(sCreatedAttribute, (sDateFormat.format(timestamp) + " " + sTimeFormat.format(timestamp)));
        root.addAttribute(sSessionBeginDateAttribute, sDateFormat.format(session.getSessionBeginDateTime()));
        root.addAttribute(sSessionEndDateAttribute, sDateFormat.format(session.getSessionEndDateTime()));
        root.addAttribute(sClassesEndDateAttribute, sDateFormat.format(session.getClassesEndDateTime()));
        if (session.getDefaultClassDurationType() != null) {
        	root.addAttribute(sDurationTypeAttribute, session.getDefaultClassDurationType().getReference());
        }
        String name = session.getAcademicInitiative()+session.getAcademicYear()+session.getAcademicTerm()+timestamp.getTime();
        String note = "This is a point in time data snapshot for session:  " + session.getLabel() + ", taken on:  " + timestamp.toString();
        root.addAttribute(sPointInTimeNameAttribute, name);
        root.addAttribute(sPointInTimeNoteAttribute, note);
                   
        document.addDocType(sRootElementName, "-//UniTime//DTD University Course Timetabling/EN", "http://www.unitime.org/interface/PointInTimeData.dtd");
        
        info("Loading Data...");
        TreeSet<InstructionalOffering> offerings = findOfferingsWithClasses(session);
        info("Loaded " + offerings.size() + " Instructional Offerings");
        ArrayList<AcademicArea> academicAreas = findAcademicAreas(session);
        info("Loaded " + academicAreas.size() + " Academic Areas");
        ArrayList<StudentClassEnrollment> studentClassEnrollments = findStudentClassEnrollments(session);
        info("Loaded " + studentClassEnrollments.size() + " Student Class Enrollments");
        ArrayList<Location> locations = findLocations(session);
        info("Loaded " + locations.size() + " Locations");
        ArrayList<TimePattern> timePatterns = findTimePatterns(session);
        info("Loaded " + timePatterns.size() + " Time Patterns");
        ArrayList<Object[]> eventMeetings = findClassEvents(session);
        info("Loaded " + eventMeetings.size() + " Class Events");
        info("Default Date Pattern:  " + session.getDefaultDatePatternNotNull());
        timePatterns.size();
        locations.size();
        Date endTransTimestamp = new Date();
        info("Data extract for Point in Time Data ended at:  " + endTransTimestamp.toString());
        info("Milliseconds elapsed = " + (endTransTimestamp.getTime() - timestamp.getTime()));
                
        departmentsElement = root.addElement(sDepartmentsElementName);
        roomTypesElement = root.addElement(sRoomTypesElementName);
        creditTypesElement = root.addElement(sCreditTypesElementName);
        creditUnitTypesElement = root.addElement(sCreditUnitTypesElementName);
        positionTypesElement = root.addElement(sPositionTypesElementName);
        teachingResponsibilitiesElement = root.addElement(sTeachingResponsibilitiesElementName);
        locationsElement = root.addElement(sLocationsElementName);
        studentsElement = root.addElement(sStudentsElementName);
        courseTypesElement = root.addElement(sCourseTypesElementName);
        classDurationTypesElement = root.addElement(sClassDurationTypesElementName);
        instructionalMethodsElement = root.addElement(sInstructionalMethodsElementName);
        timePatternsElement = root.addElement(sTimePatternsElementName);
        datePatternsElement = root.addElement(sDatePatternsElementName);
        academicAreasElement = root.addElement(sAcademicAreasElementName);
        academicClassificationsElement = root.addElement(sAcademicClassificationsElementName);
        majorsElement = root.addElement(sMajorsElementName);
        minorsElement = root.addElement(sMinorsElementName);
        offeringsElement = root.addElement(sOfferingsElementName);

        
        info("Exporting "+offerings.size()+" offerings ...");
        for (InstructionalOffering io : offerings) {
        	info("Exporting offering: " + io.getControllingCourseOffering().getCourseNameWithTitle());
            exportInstructionalOffering(offeringsElement, io, session);
        }
        int numMeetings = eventMeetings.size();
        info("Exporting student class enrollments ...");
        for(StudentClassEnrollment sce : studentClassEnrollments){
        	exportStudentClassEnrollment(sce);
        }
        info("Exporting "+  numMeetings +" class event meetings ...");
        int count = 0;
        for (Object[] objs : eventMeetings) {
        	count++;
        	ClassEvent classEvent = (ClassEvent)objs[0];
        	Meeting meeting = (Meeting)objs[1];
        	Location location = (Location)objs[2];
            exportClassEvent(classEvent, meeting, location);
            if (count % 10000 == 0){
            	info("Exported " + count + " of " + numMeetings + " class event meetings, " + 100 * count / numMeetings + "% complete.");
            }
        }
        info("Export of class event meetings complete.");
        Date endProcessingTimestamp = new Date();
        info("XML creation for Point in Time Data ended at:  " + endProcessingTimestamp.toString());
        info("Milliseconds elapsed since data extract = " + (endProcessingTimestamp.getTime() - endTransTimestamp.getTime()));

        commitTransaction();

    } catch (Exception e) {
        fatal("Exception: "+e.getMessage(),e);
        rollbackTransaction();
    }
}
 
Example 9
Source File: StudentEnrollmentExport.java    From unitime with Apache License 2.0 4 votes vote down vote up
@Override
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();
		
		Element root = document.addElement("studentEnrollments");
        root.addAttribute("campus", session.getAcademicInitiative());
        root.addAttribute("year", session.getAcademicYear());
        root.addAttribute("term", session.getAcademicTerm());
        document.addDocType("studentEnrollments", "-//UniTime//UniTime Student Enrollments DTD/EN", "http://www.unitime.org/interface/StudentEnrollment.dtd");
        
        for (Student student: (List<Student>)getHibSession().createQuery(
        		"select s from Student s where s.session.uniqueId = :sessionId")
        		.setLong("sessionId", session.getUniqueId()).list()) {
        	if (student.getClassEnrollments().isEmpty()) continue;
        	Element studentEl = root.addElement("student");
        	studentEl.addAttribute("externalId",
        			student.getExternalUniqueId() == null || student.getExternalUniqueId().isEmpty() ? student.getUniqueId().toString() : student.getExternalUniqueId());
        	for (StudentClassEnrollment enrollment: student.getClassEnrollments()) {
        		Element classEl = studentEl.addElement("class");
        		Class_ clazz = enrollment.getClazz();
        		CourseOffering course = enrollment.getCourseOffering();
        		String extId = (course == null ? clazz.getExternalUniqueId() : clazz.getExternalId(course));
        		if (extId != null && !extId.isEmpty())
        			classEl.addAttribute("externalId", extId);
        		classEl.addAttribute("id", clazz.getUniqueId().toString());
        		if (course != null) {
        			if (course.getExternalUniqueId() != null && !course.getExternalUniqueId().isEmpty())
        				classEl.addAttribute("courseId", course.getExternalUniqueId());
        			classEl.addAttribute("subject", course.getSubjectAreaAbbv());
        			classEl.addAttribute("courseNbr", course.getCourseNbr());
        		}
        		classEl.addAttribute("type", clazz.getSchedulingSubpart().getItypeDesc().trim());
        		classEl.addAttribute("suffix", getClassSuffix(clazz));
        	}
        }
        
           commitTransaction();
       } catch (Exception e) {
           fatal("Exception: "+e.getMessage(),e);
           rollbackTransaction();
	}
}