Example usage for org.dom4j Element attribute

List of usage examples for org.dom4j Element attribute

Introduction

In this page you can find the example usage for org.dom4j Element attribute.

Prototype

Attribute attribute(QName qName);

Source Link

Document

DOCUMENT ME!

Usage

From source file:net.nikr.eve.jeveasset.io.local.update.updates.Update1To2.java

License:Open Source License

private String convertFlag(final Document doc) {
    XPath flagSelector = DocumentHelper.createXPath("/settings/flags/flag");
    List<?> flagResults = flagSelector.selectNodes(doc);
    boolean text = false;
    boolean window = false;
    for (Iterator<?> iter = flagResults.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        Attribute key = element.attribute("key");
        Attribute visible = element.attribute("enabled");
        if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_TEXT")) {
            text = visible.getText().equals("true");
            element.detach();/*w w w. ja v  a 2  s. c om*/
        }
        if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_WINDOW")) {
            window = visible.getText().equals("true");
            element.detach();
        }
    }
    if (text) {
        return "TEXT";
    }
    if (window) {
        return "WINDOW";
    }
    return "NONE";
}

From source file:net.osxx.util.SettingUtils.java

License:Open Source License

/**
 * //  ww w  .  j  a v  a  2 s. co  m
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File osxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(osxxXmlFile);
        List<Element> elements = document.selectNodes("/osxx/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(osxxXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sf.cpsolver.coursett.TimetableXMLLoader.java

License:Open Source License

public void load(Solution<Lecture, Placement> currentSolution) throws Exception {
    sLogger.debug("Reading XML data from " + iInputFile);
    iProgress.setPhase("Reading " + iInputFile.getName() + " ...");

    Document document = (new SAXReader()).read(iInputFile);
    Element root = document.getRootElement();
    sLogger.debug("Root element: " + root.getName());
    if (!"llrt".equals(root.getName()) && !"timetable".equals(root.getName())) {
        sLogger.error("Given XML file is not large lecture room timetabling problem.");
        return;/*from   ww w .j a v a2  s.co m*/
    }

    iProgress.load(root, true);
    iProgress.message(Progress.MSGLEVEL_STAGE, "Restoring from backup ...");

    if (root.element("input") != null)
        root = root.element("input");

    if (root.attributeValue("term") != null)
        getModel().getProperties().setProperty("Data.Term", root.attributeValue("term"));
    if (root.attributeValue("year") != null)
        getModel().setYear(Integer.parseInt(root.attributeValue("year")));
    else if (root.attributeValue("term") != null)
        getModel().setYear(Integer.parseInt(root.attributeValue("term").substring(0, 4)));
    if (root.attributeValue("initiative") != null)
        getModel().getProperties().setProperty("Data.Initiative", root.attributeValue("initiative"));
    if (root.attributeValue("semester") != null && root.attributeValue("year") != null)
        getModel().getProperties().setProperty("Data.Term",
                root.attributeValue("semester") + root.attributeValue("year"));
    if (root.attributeValue("session") != null)
        getModel().getProperties().setProperty("General.SessionId", root.attributeValue("session"));
    if (root.attributeValue("solverGroup") != null)
        getModel().getProperties().setProperty("General.SolverGroupId", root.attributeValue("solverGroup"));
    String version = root.attributeValue("version");

    // Student sectioning considers the whole course (including committed classes), since 2.5
    boolean sectionWholeCourse = true;

    if (version != null && version.indexOf('.') >= 0) {
        int majorVersion = Integer.parseInt(version.substring(0, version.indexOf('.')));
        int minorVersion = Integer.parseInt(version.substring(1 + version.indexOf('.')));

        sectionWholeCourse = (majorVersion == 2 && minorVersion >= 5) || majorVersion > 2;
    }

    HashMap<Long, TimeLocation> perts = new HashMap<Long, TimeLocation>();
    if (getModel().getProperties().getPropertyInt("MPP.TimePert", 0) > 0) {
        int nrChanges = getModel().getProperties().getPropertyInt("MPP.TimePert", 0);
        int idx = 0;
        for (Iterator<?> i = root.element("perturbations").elementIterator("class"); i.hasNext()
                && idx < nrChanges; idx++) {
            Element pertEl = (Element) i.next();
            Long classId = Long.valueOf(pertEl.attributeValue("id"));
            TimeLocation tl = new TimeLocation(Integer.parseInt(pertEl.attributeValue("days"), 2),
                    Integer.parseInt(pertEl.attributeValue("start")),
                    Integer.parseInt(pertEl.attributeValue("length")), 0, 0.0, null, null, null, 0);
            perts.put(classId, tl);
        }
    }

    iProgress.setPhase("Creating rooms ...", root.element("rooms").elements("room").size());
    HashMap<String, Element> roomElements = new HashMap<String, Element>();
    HashMap<String, RoomConstraint> roomConstraints = new HashMap<String, RoomConstraint>();
    HashMap<Long, List<Lecture>> sameLectures = new HashMap<Long, List<Lecture>>();
    for (Iterator<?> i = root.element("rooms").elementIterator("room"); i.hasNext();) {
        Element roomEl = (Element) i.next();
        iProgress.incProgress();
        roomElements.put(roomEl.attributeValue("id"), roomEl);
        if ("false".equals(roomEl.attributeValue("constraint")))
            continue;
        RoomSharingModel sharingModel = null;
        Element sharingEl = roomEl.element("sharing");
        if (sharingEl != null) {
            String pattern = sharingEl.element("pattern").getText();
            java.util.List<?> depts = sharingEl.elements("department");
            Long departmentIds[] = new Long[depts.size()];
            for (int j = 0; j < departmentIds.length; j++)
                departmentIds[j] = Long.valueOf(((Element) depts.get(j)).attributeValue("id"));
            sharingModel = new RoomSharingModel(departmentIds, pattern);
        }
        boolean ignoreTooFar = false;
        if ("true".equals(roomEl.attributeValue("ignoreTooFar")))
            ignoreTooFar = true;
        boolean fake = false;
        if ("true".equals(roomEl.attributeValue("fake")))
            fake = true;
        Double posX = null, posY = null;
        if (roomEl.attributeValue("location") != null) {
            String loc = roomEl.attributeValue("location");
            posX = Double.valueOf(loc.substring(0, loc.indexOf(',')));
            posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1));
        }
        boolean discouraged = "true".equals(roomEl.attributeValue("discouraged"));
        RoomConstraint constraint = (discouraged
                ? new DiscouragedRoomConstraint(getModel().getProperties(),
                        Long.valueOf(roomEl.attributeValue("id")),
                        (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name")
                                : "r" + roomEl.attributeValue("id")),
                        (roomEl.attributeValue("building") == null ? null
                                : Long.valueOf(roomEl.attributeValue("building"))),
                        Integer.parseInt(roomEl.attributeValue("capacity")), sharingModel, posX, posY,
                        ignoreTooFar, !fake)
                : new RoomConstraint(Long.valueOf(roomEl.attributeValue("id")),
                        (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name")
                                : "r" + roomEl.attributeValue("id")),
                        (roomEl.attributeValue("building") == null ? null
                                : Long.valueOf(roomEl.attributeValue("building"))),
                        Integer.parseInt(roomEl.attributeValue("capacity")), sharingModel, posX, posY,
                        ignoreTooFar, !fake));
        if (roomEl.attributeValue("type") != null)
            constraint.setType(Long.valueOf(roomEl.attributeValue("type")));
        getModel().addConstraint(constraint);
        roomConstraints.put(roomEl.attributeValue("id"), constraint);
    }

    HashMap<String, InstructorConstraint> instructorConstraints = new HashMap<String, InstructorConstraint>();
    if (root.element("instructors") != null) {
        for (Iterator<?> i = root.element("instructors").elementIterator("instructor"); i.hasNext();) {
            Element instructorEl = (Element) i.next();
            InstructorConstraint instructorConstraint = new InstructorConstraint(
                    Long.valueOf(instructorEl.attributeValue("id")), instructorEl.attributeValue("puid"),
                    (instructorEl.attributeValue("name") != null ? instructorEl.attributeValue("name")
                            : "i" + instructorEl.attributeValue("id")),
                    "true".equals(instructorEl.attributeValue("ignDist")));
            if (instructorEl.attributeValue("type") != null)
                instructorConstraint.setType(Long.valueOf(instructorEl.attributeValue("type")));
            instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint);

            getModel().addConstraint(instructorConstraint);
        }
    }
    HashMap<Long, String> depts = new HashMap<Long, String>();
    if (root.element("departments") != null) {
        for (Iterator<?> i = root.element("departments").elementIterator("department"); i.hasNext();) {
            Element deptEl = (Element) i.next();
            depts.put(Long.valueOf(deptEl.attributeValue("id")),
                    (deptEl.attributeValue("name") != null ? deptEl.attributeValue("name")
                            : "d" + deptEl.attributeValue("id")));
        }
    }

    HashMap<Long, Configuration> configs = new HashMap<Long, Configuration>();
    HashMap<Long, List<Configuration>> alternativeConfigurations = new HashMap<Long, List<Configuration>>();
    if (root.element("configurations") != null) {
        for (Iterator<?> i = root.element("configurations").elementIterator("config"); i.hasNext();) {
            Element configEl = (Element) i.next();
            Long configId = Long.valueOf(configEl.attributeValue("id"));
            int limit = Integer.parseInt(configEl.attributeValue("limit"));
            Long offeringId = Long.valueOf(configEl.attributeValue("offering"));
            Configuration config = new Configuration(offeringId, configId, limit);
            configs.put(configId, config);
            List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
            if (altConfigs == null) {
                altConfigs = new ArrayList<Configuration>();
                alternativeConfigurations.put(offeringId, altConfigs);
            }
            altConfigs.add(config);
            config.setAltConfigurations(altConfigs);
        }
    }

    iProgress.setPhase("Creating variables ...", root.element("classes").elements("class").size());

    HashMap<String, Element> classElements = new HashMap<String, Element>();
    HashMap<String, Lecture> lectures = new HashMap<String, Lecture>();
    HashMap<Lecture, Placement> assignedPlacements = new HashMap<Lecture, Placement>();
    HashMap<Lecture, String> parents = new HashMap<Lecture, String>();
    int ord = 0;
    for (Iterator<?> i1 = root.element("classes").elementIterator("class"); i1.hasNext();) {
        Element classEl = (Element) i1.next();

        Configuration config = null;
        if (classEl.attributeValue("config") != null) {
            config = configs.get(Long.valueOf(classEl.attributeValue("config")));
        }
        if (config == null && classEl.attributeValue("offering") != null) {
            Long offeringId = Long.valueOf(classEl.attributeValue("offering"));
            Long configId = Long.valueOf(classEl.attributeValue("config"));
            List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
            if (altConfigs == null) {
                altConfigs = new ArrayList<Configuration>();
                alternativeConfigurations.put(offeringId, altConfigs);
            }
            for (Configuration c : altConfigs) {
                if (c.getConfigId().equals(configId)) {
                    config = c;
                    break;
                }
            }
            if (config == null) {
                config = new Configuration(offeringId, configId, -1);
                altConfigs.add(config);
                config.setAltConfigurations(altConfigs);
            }
        }

        Long datePatternId = null;
        String datePatternName = null;
        BitSet weekCode = null;
        if (classEl.attributeValue("dates") == null) {
            int startDay = Integer.parseInt(classEl.attributeValue("startDay", "0"));
            int endDay = Integer.parseInt(classEl.attributeValue("endDay", "1"));
            weekCode = new BitSet(366);
            for (int d = startDay; d <= endDay; d++)
                weekCode.set(d);
            datePatternName = sDF.format(getDate(getModel().getYear(), startDay)) + "-"
                    + sDF.format(getDate(getModel().getYear(), endDay));
        } else {
            datePatternId = (classEl.attributeValue("datePattern") == null ? null
                    : Long.valueOf(classEl.attributeValue("datePattern")));
            datePatternName = classEl.attributeValue("datePatternName");
            weekCode = createBitSet(classEl.attributeValue("dates"));
        }
        classElements.put(classEl.attributeValue("id"), classEl);
        List<InstructorConstraint> ics = new ArrayList<InstructorConstraint>();
        for (Iterator<?> i2 = classEl.elementIterator("instructor"); i2.hasNext();) {
            Element instructorEl = (Element) i2.next();
            InstructorConstraint instructorConstraint = instructorConstraints
                    .get(instructorEl.attributeValue("id"));
            if (instructorConstraint == null) {
                instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl.attributeValue("id")),
                        instructorEl.attributeValue("puid"),
                        (instructorEl.attributeValue("name") != null ? instructorEl.attributeValue("name")
                                : "i" + instructorEl.attributeValue("id")),
                        "true".equals(instructorEl.attributeValue("ignDist")));
                instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint);
                getModel().addConstraint(instructorConstraint);
            }
            ics.add(instructorConstraint);
        }
        List<RoomLocation> roomLocations = new ArrayList<RoomLocation>();
        List<RoomConstraint> roomConstraintsThisClass = new ArrayList<RoomConstraint>();
        List<RoomLocation> initialRoomLocations = new ArrayList<RoomLocation>();
        List<RoomLocation> assignedRoomLocations = new ArrayList<RoomLocation>();
        List<RoomLocation> bestRoomLocations = new ArrayList<RoomLocation>();
        for (Iterator<?> i2 = classEl.elementIterator("room"); i2.hasNext();) {
            Element roomLocationEl = (Element) i2.next();
            Element roomEl = roomElements.get(roomLocationEl.attributeValue("id"));
            RoomConstraint roomConstraint = roomConstraints.get(roomLocationEl.attributeValue("id"));

            Long roomId = null;
            String roomName = null;
            Long bldgId = null;

            if (roomConstraint != null) {
                roomConstraintsThisClass.add(roomConstraint);
                roomId = roomConstraint.getResourceId();
                roomName = roomConstraint.getRoomName();
                bldgId = roomConstraint.getBuildingId();
            } else {
                roomId = Long.valueOf(roomEl.attributeValue("id"));
                roomName = (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name")
                        : "r" + roomEl.attributeValue("id"));
                bldgId = (roomEl.attributeValue("building") == null ? null
                        : Long.valueOf(roomEl.attributeValue("building")));
            }

            boolean ignoreTooFar = false;
            if ("true".equals(roomEl.attributeValue("ignoreTooFar")))
                ignoreTooFar = true;
            Double posX = null, posY = null;
            if (roomEl.attributeValue("location") != null) {
                String loc = roomEl.attributeValue("location");
                posX = Double.valueOf(loc.substring(0, loc.indexOf(',')));
                posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1));
            }
            RoomLocation rl = new RoomLocation(roomId, roomName, bldgId,
                    Integer.parseInt(roomLocationEl.attributeValue("pref")),
                    Integer.parseInt(roomEl.attributeValue("capacity")), posX, posY, ignoreTooFar,
                    roomConstraint);
            if ("true".equals(roomLocationEl.attributeValue("initial")))
                initialRoomLocations.add(rl);
            if ("true".equals(roomLocationEl.attributeValue("solution")))
                assignedRoomLocations.add(rl);
            if ("true".equals(roomLocationEl.attributeValue("best")))
                bestRoomLocations.add(rl);
            roomLocations.add(rl);
        }
        List<TimeLocation> timeLocations = new ArrayList<TimeLocation>();
        TimeLocation initialTimeLocation = null;
        TimeLocation assignedTimeLocation = null;
        TimeLocation bestTimeLocation = null;
        TimeLocation prohibitedTime = perts.get(Long.valueOf(classEl.attributeValue("id")));
        for (Iterator<?> i2 = classEl.elementIterator("time"); i2.hasNext();) {
            Element timeLocationEl = (Element) i2.next();
            TimeLocation tl = new TimeLocation(Integer.parseInt(timeLocationEl.attributeValue("days"), 2),
                    Integer.parseInt(timeLocationEl.attributeValue("start")),
                    Integer.parseInt(timeLocationEl.attributeValue("length")),
                    (int) Double.parseDouble(timeLocationEl.attributeValue("pref")),
                    Double.parseDouble(
                            timeLocationEl.attributeValue("npref", timeLocationEl.attributeValue("pref"))),
                    datePatternId, datePatternName, weekCode,
                    Integer.parseInt(timeLocationEl.attributeValue("breakTime") == null ? "-1"
                            : timeLocationEl.attributeValue("breakTime")));
            if (tl.getBreakTime() < 0)
                tl.setBreakTime(tl.getLength() == 18 ? 15 : 10);
            if (timeLocationEl.attributeValue("pattern") != null)
                tl.setTimePatternId(Long.valueOf(timeLocationEl.attributeValue("pattern")));
            /*
             * if (timePatternTransform) tl =
             * transformTimePattern(Long.valueOf
             * (classEl.attributeValue("id")),tl);
             */
            if (prohibitedTime != null && prohibitedTime.getDayCode() == tl.getDayCode()
                    && prohibitedTime.getStartSlot() == tl.getStartSlot()
                    && prohibitedTime.getLength() == tl.getLength()) {
                sLogger.info("Time " + tl.getLongName() + " is prohibited for class "
                        + classEl.attributeValue("id"));
                continue;
            }
            if ("true".equals(timeLocationEl.attributeValue("solution")))
                assignedTimeLocation = tl;
            if ("true".equals(timeLocationEl.attributeValue("initial")))
                initialTimeLocation = tl;
            if ("true".equals(timeLocationEl.attributeValue("best")))
                bestTimeLocation = tl;
            timeLocations.add(tl);
        }
        if (timeLocations.isEmpty()) {
            sLogger.error("  ERROR: No time.");
            continue;
        }

        int minClassLimit = 0;
        int maxClassLimit = 0;
        double room2limitRatio = 1.0;
        if (!"true".equals(classEl.attributeValue("committed"))) {
            if (classEl.attributeValue("expectedCapacity") != null) {
                minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("expectedCapacity"));
                int roomCapacity = Integer.parseInt(
                        classEl.attributeValue("roomCapacity", classEl.attributeValue("expectedCapacity")));
                if (minClassLimit == 0)
                    minClassLimit = maxClassLimit = roomCapacity;
                room2limitRatio = (minClassLimit == 0 ? 1.0 : ((double) roomCapacity) / minClassLimit);
            } else {
                if (classEl.attribute("classLimit") != null) {
                    minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("classLimit"));
                } else {
                    minClassLimit = Integer.parseInt(classEl.attributeValue("minClassLimit"));
                    maxClassLimit = Integer.parseInt(classEl.attributeValue("maxClassLimit"));
                }
                room2limitRatio = Double.parseDouble(classEl.attributeValue("roomToLimitRatio", "1.0"));
            }
        }

        Lecture lecture = new Lecture(Long.valueOf(classEl.attributeValue("id")),
                (classEl.attributeValue("solverGroup") != null
                        ? Long.valueOf(classEl.attributeValue("solverGroup"))
                        : null),
                Long.valueOf(classEl.attributeValue("subpart", classEl.attributeValue("course", "-1"))),
                (classEl.attributeValue("name") != null ? classEl.attributeValue("name")
                        : "c" + classEl.attributeValue("id")),
                timeLocations, roomLocations, Integer.parseInt(classEl.attributeValue("nrRooms", "1")), null,
                minClassLimit, maxClassLimit, room2limitRatio);
        lecture.setNote(classEl.attributeValue("note"));

        if ("true".equals(classEl.attributeValue("committed")))
            lecture.setCommitted(true);

        if (!lecture.isCommitted() && classEl.attributeValue("ord") != null)
            lecture.setOrd(Integer.parseInt(classEl.attributeValue("ord")));
        else
            lecture.setOrd(ord++);

        if (config != null)
            lecture.setConfiguration(config);

        if (initialTimeLocation != null && initialRoomLocations.size() == lecture.getNrRooms()) {
            lecture.setInitialAssignment(new Placement(lecture, initialTimeLocation, initialRoomLocations));
        }
        if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) {
            assignedPlacements.put(lecture,
                    new Placement(lecture, assignedTimeLocation, assignedRoomLocations));
        } else if (lecture.getInitialAssignment() != null) {
            assignedPlacements.put(lecture, lecture.getInitialAssignment());
        }
        if (bestTimeLocation != null && bestRoomLocations.size() == lecture.getNrRooms()) {
            lecture.setBestAssignment(new Placement(lecture, bestTimeLocation, bestRoomLocations));
        } else if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) {
            lecture.setBestAssignment(assignedPlacements.get(lecture));
        }

        lectures.put(classEl.attributeValue("id"), lecture);
        if (classEl.attributeValue("department") != null)
            lecture.setDepartment(Long.valueOf(classEl.attributeValue("department")));
        if (classEl.attribute("scheduler") != null)
            lecture.setScheduler(Long.valueOf(classEl.attributeValue("scheduler")));
        if ((sectionWholeCourse || !lecture.isCommitted())
                && classEl.attributeValue("subpart", classEl.attributeValue("course")) != null) {
            Long subpartId = Long.valueOf(classEl.attributeValue("subpart", classEl.attributeValue("course")));
            List<Lecture> sames = sameLectures.get(subpartId);
            if (sames == null) {
                sames = new ArrayList<Lecture>();
                sameLectures.put(subpartId, sames);
            }
            sames.add(lecture);
        }
        String parent = classEl.attributeValue("parent");
        if (parent != null)
            parents.put(lecture, parent);

        getModel().addVariable(lecture);

        if (lecture.isCommitted()) {
            Placement placement = assignedPlacements.get(lecture);
            if (classEl.attribute("assignment") != null)
                placement.setAssignmentId(Long.valueOf(classEl.attributeValue("assignment")));
            for (InstructorConstraint ic : ics)
                ic.setNotAvailable(placement);
            for (RoomConstraint rc : roomConstraintsThisClass)
                rc.setNotAvailable(placement);
        } else {
            for (InstructorConstraint ic : ics)
                ic.addVariable(lecture);
            for (RoomConstraint rc : roomConstraintsThisClass)
                rc.addVariable(lecture);
        }

        iProgress.incProgress();
    }

    for (Map.Entry<Lecture, String> entry : parents.entrySet()) {
        Lecture lecture = entry.getKey();
        Lecture parent = lectures.get(entry.getValue());
        if (parent == null) {
            System.out.println("Unknown parent class: " + entry.getValue());
        }
        lecture.setParent(parent);
    }

    iProgress.setPhase("Creating constraints ...",
            root.element("groupConstraints").elements("constraint").size());
    HashMap<String, Element> grConstraintElements = new HashMap<String, Element>();
    HashMap<String, Constraint<Lecture, Placement>> groupConstraints = new HashMap<String, Constraint<Lecture, Placement>>();
    for (Iterator<?> i1 = root.element("groupConstraints").elementIterator("constraint"); i1.hasNext();) {
        Element grConstraintEl = (Element) i1.next();
        Constraint<Lecture, Placement> c = null;
        if ("SPREAD".equals(grConstraintEl.attributeValue("type"))) {
            c = new SpreadConstraint(getModel().getProperties(),
                    grConstraintEl.attributeValue("name", "spread"));
        } else if ("MIN_ROOM_USE".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedRoomsConstraint(getModel().getProperties());
        } else if ("CLASS_LIMIT".equals(grConstraintEl.attributeValue("type"))) {
            if (grConstraintEl.element("parentClass") == null) {
                c = new ClassLimitConstraint(Integer.parseInt(grConstraintEl.attributeValue("courseLimit")),
                        grConstraintEl.attributeValue("name", "class-limit"));
            } else {
                String classId = grConstraintEl.element("parentClass").attributeValue("id");
                c = new ClassLimitConstraint(lectures.get(classId),
                        grConstraintEl.attributeValue("name", "class-limit"));
            }
            if (grConstraintEl.attributeValue("delta") != null)
                ((ClassLimitConstraint) c)
                        .setClassLimitDelta(Integer.parseInt(grConstraintEl.attributeValue("delta")));
        } else if ("MIN_GRUSE(10x1h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "10x1h",
                    MinimizeNumberOfUsedGroupsOfTime.sGroups10of1h);
        } else if ("MIN_GRUSE(5x2h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "5x2h",
                    MinimizeNumberOfUsedGroupsOfTime.sGroups5of2h);
        } else if ("MIN_GRUSE(3x3h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "3x3h",
                    MinimizeNumberOfUsedGroupsOfTime.sGroups3of3h);
        } else if ("MIN_GRUSE(2x5h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "2x5h",
                    MinimizeNumberOfUsedGroupsOfTime.sGroups2of5h);
        } else {
            c = new GroupConstraint(Long.valueOf(grConstraintEl.attributeValue("id")),
                    GroupConstraint.ConstraintType.get(grConstraintEl.attributeValue("type")),
                    grConstraintEl.attributeValue("pref"));
        }
        getModel().addConstraint(c);
        for (Iterator<?> i2 = grConstraintEl.elementIterator("class"); i2.hasNext();) {
            String classId = ((Element) i2.next()).attributeValue("id");
            c.addVariable(lectures.get(classId));
        }
        grConstraintElements.put(grConstraintEl.attributeValue("id"), grConstraintEl);
        groupConstraints.put(grConstraintEl.attributeValue("id"), c);
        iProgress.incProgress();
    }

    iProgress.setPhase("Loading students ...", root.element("students").elements("student").size());
    boolean initialSectioning = true;
    HashMap<Long, Student> students = new HashMap<Long, Student>();
    HashMap<Long, Set<Student>> offering2students = new HashMap<Long, Set<Student>>();
    for (Iterator<?> i1 = root.element("students").elementIterator("student"); i1.hasNext();) {
        Element studentEl = (Element) i1.next();
        List<Lecture> lecturesThisStudent = new ArrayList<Lecture>();
        Long studentId = Long.valueOf(studentEl.attributeValue("id"));
        Student student = students.get(studentId);
        if (student == null) {
            student = new Student(studentId);
            students.put(studentId, student);
            getModel().addStudent(student);
        }
        student.setAcademicArea(studentEl.attributeValue("area"));
        student.setAcademicClassification(studentEl.attributeValue("classification"));
        student.setMajor(studentEl.attributeValue("major"));
        student.setCurriculum(studentEl.attributeValue("curriculum"));
        for (Iterator<?> i2 = studentEl.elementIterator("offering"); i2.hasNext();) {
            Element ofEl = (Element) i2.next();
            Long offeringId = Long.valueOf(ofEl.attributeValue("id"));
            student.addOffering(offeringId, Double.parseDouble(ofEl.attributeValue("weight", "1.0")));
            Set<Student> studentsThisOffering = offering2students.get(offeringId);
            if (studentsThisOffering == null) {
                studentsThisOffering = new HashSet<Student>();
                offering2students.put(offeringId, studentsThisOffering);
            }
            studentsThisOffering.add(student);
        }
        for (Iterator<?> i2 = studentEl.elementIterator("class"); i2.hasNext();) {
            String classId = ((Element) i2.next()).attributeValue("id");
            Lecture lecture = lectures.get(classId);
            if (lecture.isCommitted()) {
                if (sectionWholeCourse && (lecture.getParent() != null || lecture.getConfiguration() != null)) {
                    // committed, but with course structure -- sectioning can be used
                    student.addLecture(lecture);
                    lecture.addStudent(student);
                    lecturesThisStudent.add(lecture);
                    initialSectioning = false;
                } else {
                    Placement placement = assignedPlacements.get(lecture);
                    student.addCommitedPlacement(placement);
                }
            } else {
                student.addLecture(lecture);
                lecture.addStudent(student);
                lecturesThisStudent.add(lecture);
                initialSectioning = false;
            }
        }

        for (Iterator<?> i2 = studentEl.elementIterator("prohibited-class"); i2.hasNext();) {
            String classId = ((Element) i2.next()).attributeValue("id");
            Lecture lecture = lectures.get(classId);
            student.addCanNotEnroll(lecture);
        }

        iProgress.incProgress();
    }

    for (List<Lecture> sames : sameLectures.values()) {
        for (Lecture lect : sames) {
            lect.setSameSubpartLectures(sames);
        }
    }

    if (initialSectioning) {
        iProgress.setPhase("Initial sectioning ...", offering2students.size());
        for (Map.Entry<Long, Set<Student>> entry : offering2students.entrySet()) {
            Long offeringId = entry.getKey();
            Set<Student> studentsThisOffering = entry.getValue();
            List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
            InitialSectioning.initialSectioningCfg(iProgress, offeringId, String.valueOf(offeringId),
                    studentsThisOffering, altConfigs);
            iProgress.incProgress();
        }
        for (Student student : students.values())
            student.clearDistanceCache();
    }

    iProgress.setPhase("Computing jenrl ...", students.size());
    HashMap<Lecture, HashMap<Lecture, JenrlConstraint>> jenrls = new HashMap<Lecture, HashMap<Lecture, JenrlConstraint>>();
    for (Iterator<Student> i1 = students.values().iterator(); i1.hasNext();) {
        Student st = i1.next();
        for (Iterator<Lecture> i2 = st.getLectures().iterator(); i2.hasNext();) {
            Lecture l1 = i2.next();
            for (Iterator<Lecture> i3 = st.getLectures().iterator(); i3.hasNext();) {
                Lecture l2 = i3.next();
                if (l1.getId() >= l2.getId())
                    continue;
                HashMap<Lecture, JenrlConstraint> x = jenrls.get(l1);
                if (x == null) {
                    x = new HashMap<Lecture, JenrlConstraint>();
                    jenrls.put(l1, x);
                }
                JenrlConstraint jenrl = x.get(l2);
                if (jenrl == null) {
                    jenrl = new JenrlConstraint();
                    jenrl.addVariable(l1);
                    jenrl.addVariable(l2);
                    getModel().addConstraint(jenrl);
                    x.put(l2, jenrl);
                }
                jenrl.incJenrl(st);
            }
        }
        iProgress.incProgress();
    }

    if (iDeptBalancing) {
        iProgress.setPhase("Creating dept. spread constraints ...", getModel().variables().size());
        HashMap<Long, DepartmentSpreadConstraint> depSpreadConstraints = new HashMap<Long, DepartmentSpreadConstraint>();
        for (Lecture lecture : getModel().variables()) {
            if (lecture.getDepartment() == null)
                continue;
            DepartmentSpreadConstraint deptConstr = depSpreadConstraints.get(lecture.getDepartment());
            if (deptConstr == null) {
                String name = depts.get(lecture.getDepartment());
                deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(), lecture.getDepartment(),
                        (name != null ? name : "d" + lecture.getDepartment()));
                depSpreadConstraints.put(lecture.getDepartment(), deptConstr);
                getModel().addConstraint(deptConstr);
            }
            deptConstr.addVariable(lecture);
            iProgress.incProgress();
        }
    }

    iProgress.setPhase("Purging invalid placements ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        lecture.purgeInvalidValues(iInteractiveMode);
        iProgress.incProgress();
    }

    if (getModel().hasConstantVariables() && getModel().constantVariables().size() > 0) {
        iProgress.setPhase("Assigning committed classes ...", assignedPlacements.size());
        for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) {
            Lecture lecture = entry.getKey();
            Placement placement = entry.getValue();
            if (!lecture.isCommitted()) {
                iProgress.incProgress();
                continue;
            }
            Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel()
                    .conflictConstraints(placement);
            if (conflictConstraints.isEmpty()) {
                lecture.assign(0, placement);
            } else {
                sLogger.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName());
                sLogger.debug("  Reason:");
                for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
                    Set<Placement> vals = conflictConstraints.get(c);
                    for (Placement v : vals) {
                        sLogger.debug("    " + v.variable().getName() + " = " + v.getName());
                    }
                    sLogger.debug("    in constraint " + c);
                }
            }
            iProgress.incProgress();
        }
    }

    if (currentSolution != null) {
        iProgress.setPhase("Creating best assignment ...", 2 * getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            iProgress.incProgress();
            Placement placement = lecture.getBestAssignment();
            if (placement == null)
                continue;
            lecture.assign(0, placement);
        }

        currentSolution.saveBest();
        for (Lecture lecture : getModel().variables()) {
            iProgress.incProgress();
            if (lecture.getAssignment() != null)
                lecture.unassign(0);
        }
    }

    iProgress.setPhase("Creating initial assignment ...", assignedPlacements.size());
    for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) {
        Lecture lecture = entry.getKey();
        Placement placement = entry.getValue();
        if (lecture.isCommitted()) {
            iProgress.incProgress();
            continue;
        }
        Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel()
                .conflictConstraints(placement);
        if (conflictConstraints.isEmpty()) {
            if (!placement.isValid()) {
                sLogger.warn("WARNING: Lecture " + lecture.getName() + " does not contain assignment "
                        + placement.getLongName() + " in its domain (" + placement.getNotValidReason() + ").");
            } else
                lecture.assign(0, placement);
        } else {
            sLogger.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName());
            sLogger.debug("  Reason:");
            for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
                Set<Placement> vals = conflictConstraints.get(c);
                for (Placement v : vals) {
                    sLogger.debug("    " + v.variable().getName() + " = " + v.getName());
                }
                sLogger.debug("    in constraint " + c);
            }
        }
        iProgress.incProgress();
    }

    if (initialSectioning && !getModel().assignedVariables().isEmpty()
            && !getModel().getProperties().getPropertyBoolean("Global.LoadStudentEnrlsFromSolution", false))
        getModel().switchStudents();

    if (iForcedPerturbances > 0) {
        iProgress.setPhase("Forcing perturbances", iForcedPerturbances);
        for (int i = 0; i < iForcedPerturbances; i++) {
            iProgress.setProgress(i);
            Lecture var = null;
            do {
                var = ToolBox.random(getModel().variables());
            } while (var.getInitialAssignment() == null || var.values().size() <= 1);
            var.removeInitialValue();
        }
    }

    for (Constraint<Lecture, Placement> c : getModel().constraints()) {
        if (c instanceof SpreadConstraint)
            ((SpreadConstraint) c).init();
        if (c instanceof DiscouragedRoomConstraint)
            ((DiscouragedRoomConstraint) c).setEnabled(true);
        if (c instanceof MinimizeNumberOfUsedRoomsConstraint)
            ((MinimizeNumberOfUsedRoomsConstraint) c).setEnabled(true);
        if (c instanceof MinimizeNumberOfUsedGroupsOfTime)
            ((MinimizeNumberOfUsedGroupsOfTime) c).setEnabled(true);
    }

    try {
        getSolver().getClass().getMethod("load", new Class[] { Element.class }).invoke(getSolver(),
                new Object[] { root });
    } catch (Exception e) {
    }

    iProgress.setPhase("Done", 1);
    iProgress.incProgress();

    sLogger.debug("Model successfully loaded.");
    iProgress.info("Model successfully loaded.");
}

From source file:net.sf.cpsolver.exam.model.ExamModel.java

License:Open Source License

/**
 * Load model (including its solution) from XML.
 *//*  www  .j av a 2s. c  o m*/
public boolean load(Document document, Callback saveBest) {
    boolean loadInitial = getProperties().getPropertyBoolean("Xml.LoadInitial", true);
    boolean loadBest = getProperties().getPropertyBoolean("Xml.LoadBest", true);
    boolean loadSolution = getProperties().getPropertyBoolean("Xml.LoadSolution", true);
    boolean loadParams = getProperties().getPropertyBoolean("Xml.LoadParameters", false);
    Element root = document.getRootElement();
    if (!"examtt".equals(root.getName()))
        return false;
    if (root.attribute("campus") != null)
        getProperties().setProperty("Data.Initiative", root.attributeValue("campus"));
    else if (root.attribute("initiative") != null)
        getProperties().setProperty("Data.Initiative", root.attributeValue("initiative"));
    if (root.attribute("term") != null)
        getProperties().setProperty("Data.Term", root.attributeValue("term"));
    if (root.attribute("year") != null)
        getProperties().setProperty("Data.Year", root.attributeValue("year"));
    if (loadParams && root.element("parameters") != null)
        for (Iterator<?> i = root.element("parameters").elementIterator("property"); i.hasNext();) {
            Element e = (Element) i.next();
            String name = e.attributeValue("name");
            String value = e.attributeValue("value");
            if ("isDayBreakBackToBack".equals(name))
                setDayBreakBackToBack("true".equals(value));
            else if ("directConflictWeight".equals(name))
                setDirectConflictWeight(Double.parseDouble(value));
            else if ("moreThanTwoADayWeight".equals(name))
                setMoreThanTwoADayWeight(Double.parseDouble(value));
            else if ("backToBackConflictWeight".equals(name))
                setBackToBackConflictWeight(Double.parseDouble(value));
            else if ("distanceBackToBackConflictWeight".equals(name))
                setDistanceBackToBackConflictWeight(Double.parseDouble(value));
            else if ("backToBackDistance".equals(name))
                setBackToBackDistance(Double.parseDouble(value));
            else if ("maxRooms".equals(name))
                setMaxRooms(Integer.parseInt(value));
            else if ("periodWeight".equals(name))
                setPeriodWeight(Double.parseDouble(value));
            else if ("periodSizeWeight".equals(name))
                setPeriodSizeWeight(Double.parseDouble(value));
            else if ("periodIndexWeight".equals(name))
                setPeriodIndexWeight(Double.parseDouble(value));
            else if ("examRotationWeight".equals(name))
                setExamRotationWeight(Double.parseDouble(value));
            else if ("roomSizeWeight".equals(name))
                setRoomSizeWeight(Double.parseDouble(value));
            else if ("roomSplitWeight".equals(name))
                setRoomSplitWeight(Double.parseDouble(value));
            else if ("roomWeight".equals(name))
                setRoomWeight(Double.parseDouble(value));
            else if ("distributionWeight".equals(name))
                setDistributionWeight(Double.parseDouble(value));
            else if ("instructorDirectConflictWeight".equals(name))
                setInstructorDirectConflictWeight(Double.parseDouble(value));
            else if ("instructorMoreThanTwoADayWeight".equals(name))
                setInstructorMoreThanTwoADayWeight(Double.parseDouble(value));
            else if ("instructorBackToBackConflictWeight".equals(name))
                setInstructorBackToBackConflictWeight(Double.parseDouble(value));
            else if ("instructorDistanceBackToBackConflictWeight".equals(name))
                setInstructorDistanceBackToBackConflictWeight(Double.parseDouble(value));
            else if ("perturbationWeight".equals(name))
                setPerturbationWeight(Double.parseDouble(value));
            else if ("roomPerturbationWeight".equals(name))
                setRoomPerturbationWeight(Double.parseDouble(value));
            else if ("roomSplitDistanceWeight".equals(name))
                setRoomSplitDistanceWeight(Double.parseDouble(value));
            else if ("largeSize".equals(name))
                setLargeSize(Integer.parseInt(value));
            else if ("largePeriod".equals(name))
                setLargePeriod(Double.parseDouble(value));
            else if ("largeWeight".equals(name))
                setLargeWeight(Double.parseDouble(value));
            else
                getProperties().setProperty(name, value);
        }
    for (Iterator<?> i = root.element("periods").elementIterator("period"); i.hasNext();) {
        Element e = (Element) i.next();
        addPeriod(Long.valueOf(e.attributeValue("id")), e.attributeValue("day"), e.attributeValue("time"),
                Integer.parseInt(e.attributeValue("length")),
                Integer.parseInt(e.attributeValue("penalty") == null ? e.attributeValue("weight", "0")
                        : e.attributeValue("penalty")));
    }
    HashMap<Long, ExamRoom> rooms = new HashMap<Long, ExamRoom>();
    HashMap<String, ArrayList<ExamRoom>> roomGroups = new HashMap<String, ArrayList<ExamRoom>>();
    for (Iterator<?> i = root.element("rooms").elementIterator("room"); i.hasNext();) {
        Element e = (Element) i.next();
        String coords = e.attributeValue("coordinates");
        ExamRoom room = new ExamRoom(this, Long.parseLong(e.attributeValue("id")), e.attributeValue("name"),
                Integer.parseInt(e.attributeValue("size")), Integer.parseInt(e.attributeValue("alt")),
                (coords == null ? null : Double.valueOf(coords.substring(0, coords.indexOf(',')))),
                (coords == null ? null : Double.valueOf(coords.substring(coords.indexOf(',') + 1))));
        addConstraint(room);
        getRooms().add(room);
        rooms.put(new Long(room.getId()), room);
        for (Iterator<?> j = e.elementIterator("period"); j.hasNext();) {
            Element pe = (Element) j.next();
            ExamPeriod period = getPeriod(Long.valueOf(pe.attributeValue("id")));
            if ("false".equals(pe.attributeValue("available")))
                room.setAvailable(period, false);
            else
                room.setPenalty(period, Integer.parseInt(pe.attributeValue("penalty")));
        }
        String av = e.attributeValue("available");
        if (av != null) {
            for (int j = 0; j < getPeriods().size(); j++)
                if ('0' == av.charAt(j))
                    room.setAvailable(getPeriods().get(j), false);
        }
        String g = e.attributeValue("groups");
        if (g != null) {
            for (StringTokenizer s = new StringTokenizer(g, ","); s.hasMoreTokens();) {
                String gr = s.nextToken();
                ArrayList<ExamRoom> roomsThisGrop = roomGroups.get(gr);
                if (roomsThisGrop == null) {
                    roomsThisGrop = new ArrayList<ExamRoom>();
                    roomGroups.put(gr, roomsThisGrop);
                }
                roomsThisGrop.add(room);
            }
        }
    }
    ArrayList<ExamPlacement> assignments = new ArrayList<ExamPlacement>();
    HashMap<Long, Exam> exams = new HashMap<Long, Exam>();
    HashMap<Long, ExamOwner> courseSections = new HashMap<Long, ExamOwner>();
    for (Iterator<?> i = root.element("exams").elementIterator("exam"); i.hasNext();) {
        Element e = (Element) i.next();
        ArrayList<ExamPeriodPlacement> periodPlacements = new ArrayList<ExamPeriodPlacement>();
        for (ExamPeriod p : getPeriods()) {
            periodPlacements.add(new ExamPeriodPlacement(p, 0));
        }
        /*
        for (Iterator<?> j = e.elementIterator("period"); j.hasNext();) {
        Element pe = (Element) j.next();
        periodPlacements.add(new ExamPeriodPlacement(getPeriod(Long.valueOf(pe.attributeValue("id"))), Integer
                .parseInt(pe.attributeValue("penalty", "0"))));
        }*/
        ArrayList<ExamRoomPlacement> roomPlacements = new ArrayList<ExamRoomPlacement>();
        for (Iterator<?> j = e.elementIterator("room"); j.hasNext();) {
            Element re = (Element) j.next();
            ExamRoomPlacement room = new ExamRoomPlacement(rooms.get(Long.valueOf(re.attributeValue("id"))),
                    Integer.parseInt(re.attributeValue("penalty", "0")),
                    Integer.parseInt(re.attributeValue("maxPenalty", "100")));
            roomPlacements.add(room);
        }
        String g = e.attributeValue("groups");
        if (g != null) {
            HashMap<ExamRoom, Integer> allRooms = new HashMap<ExamRoom, Integer>();
            for (StringTokenizer s = new StringTokenizer(g, ","); s.hasMoreTokens();) {
                String gr = s.nextToken();
                ArrayList<ExamRoom> roomsThisGrop = roomGroups.get(gr);
                if (roomsThisGrop != null)
                    for (ExamRoom r : roomsThisGrop)
                        allRooms.put(r, 0);
            }
            for (Iterator<?> j = e.elementIterator("original-room"); j.hasNext();) {
                allRooms.put((rooms.get(Long.valueOf(((Element) j.next()).attributeValue("id")))),
                        new Integer(-1));
            }
            for (Map.Entry<ExamRoom, Integer> entry : allRooms.entrySet()) {
                ExamRoomPlacement room = new ExamRoomPlacement(entry.getKey(), entry.getValue(), 100);
                roomPlacements.add(room);
            }
            if (periodPlacements.isEmpty()) {
                for (ExamPeriod p : getPeriods()) {
                    periodPlacements.add(new ExamPeriodPlacement(p, 0));
                }
            }
        }
        Exam exam = new Exam(Long.parseLong(e.attributeValue("id")), e.attributeValue("name"),
                Integer.parseInt(e.attributeValue("length")), "true".equals(e.attributeValue("alt")),
                (e.attribute("maxRooms") == null ? getMaxRooms()
                        : Integer.parseInt(e.attributeValue("maxRooms"))),
                Integer.parseInt(e.attributeValue("minSize", "0")), periodPlacements, roomPlacements);
        if (e.attributeValue("size") != null)
            exam.setSizeOverride(Integer.valueOf(e.attributeValue("size")));
        if (e.attributeValue("printOffset") != null)
            exam.setPrintOffset(Integer.valueOf(e.attributeValue("printOffset")));
        exams.put(new Long(exam.getId()), exam);
        addVariable(exam);
        if (e.attribute("average") != null)
            exam.setAveragePeriod(Integer.parseInt(e.attributeValue("average")));
        Element asg = e.element("assignment");
        if (asg != null && loadSolution) {
            Element per = asg.element("period");
            if (per != null) {
                HashSet<ExamRoomPlacement> rp = new HashSet<ExamRoomPlacement>();
                for (Iterator<?> j = asg.elementIterator("room"); j.hasNext();)
                    rp.add(exam.getRoomPlacement(Long.parseLong(((Element) j.next()).attributeValue("id"))));
                ExamPlacement p = new ExamPlacement(exam,
                        exam.getPeriodPlacement(Long.valueOf(per.attributeValue("id"))), rp);
                assignments.add(p);
            }
        }
        Element ini = e.element("initial");
        if (ini != null && loadInitial) {
            Element per = ini.element("period");
            if (per != null) {
                HashSet<ExamRoomPlacement> rp = new HashSet<ExamRoomPlacement>();
                for (Iterator<?> j = ini.elementIterator("room"); j.hasNext();)
                    rp.add(exam.getRoomPlacement(Long.parseLong(((Element) j.next()).attributeValue("id"))));
                ExamPlacement p = new ExamPlacement(exam,
                        exam.getPeriodPlacement(Long.valueOf(per.attributeValue("id"))), rp);
                exam.setInitialAssignment(p);
            }
        }
        Element best = e.element("best");
        if (best != null && loadBest) {
            Element per = best.element("period");
            if (per != null) {
                HashSet<ExamRoomPlacement> rp = new HashSet<ExamRoomPlacement>();
                for (Iterator<?> j = best.elementIterator("room"); j.hasNext();)
                    rp.add(exam.getRoomPlacement(Long.parseLong(((Element) j.next()).attributeValue("id"))));
                ExamPlacement p = new ExamPlacement(exam,
                        exam.getPeriodPlacement(Long.valueOf(per.attributeValue("id"))), rp);
                exam.setBestAssignment(p);
            }
        }
        for (Iterator<?> j = e.elementIterator("owner"); j.hasNext();) {
            Element f = (Element) j.next();
            ExamOwner owner = new ExamOwner(exam, Long.parseLong(f.attributeValue("id")),
                    f.attributeValue("name"));
            exam.getOwners().add(owner);
            courseSections.put(new Long(owner.getId()), owner);
        }
    }
    for (Iterator<?> i = root.element("students").elementIterator("student"); i.hasNext();) {
        Element e = (Element) i.next();
        ExamStudent student = new ExamStudent(this, Long.parseLong(e.attributeValue("id")));
        for (Iterator<?> j = e.elementIterator("exam"); j.hasNext();) {
            Element x = (Element) j.next();
            Exam ex = exams.get(Long.valueOf(x.attributeValue("id")));
            student.addVariable(ex);
            for (Iterator<?> k = x.elementIterator("owner"); k.hasNext();) {
                Element f = (Element) k.next();
                ExamOwner owner = courseSections.get(Long.valueOf(f.attributeValue("id")));
                student.getOwners().add(owner);
                owner.getStudents().add(student);
            }
        }
        String available = e.attributeValue("available");
        if (available != null)
            for (ExamPeriod period : getPeriods()) {
                if (available.charAt(period.getIndex()) == '0')
                    student.setAvailable(period.getIndex(), false);
            }
        for (Iterator<?> j = e.elementIterator("period"); j.hasNext();) {
            Element pe = (Element) j.next();
            ExamPeriod period = getPeriod(Long.valueOf(pe.attributeValue("id")));
            if ("false".equals(pe.attributeValue("available")))
                student.setAvailable(period.getIndex(), false);
        }
        addConstraint(student);
        getStudents().add(student);
    }
    if (root.element("instructors") != null)
        for (Iterator<?> i = root.element("instructors").elementIterator("instructor"); i.hasNext();) {
            Element e = (Element) i.next();
            ExamInstructor instructor = new ExamInstructor(this, Long.parseLong(e.attributeValue("id")),
                    e.attributeValue("name"));
            for (Iterator<?> j = e.elementIterator("exam"); j.hasNext();) {
                Element x = (Element) j.next();
                Exam ex = exams.get(Long.valueOf(x.attributeValue("id")));
                instructor.addVariable(ex);
                for (Iterator<?> k = x.elementIterator("owner"); k.hasNext();) {
                    Element f = (Element) k.next();
                    ExamOwner owner = courseSections.get(Long.valueOf(f.attributeValue("id")));
                    instructor.getOwners().add(owner);
                    owner.getIntructors().add(instructor);
                }
            }
            String available = e.attributeValue("available");
            if (available != null)
                for (ExamPeriod period : getPeriods()) {
                    if (available.charAt(period.getIndex()) == '0')
                        instructor.setAvailable(period.getIndex(), false);
                }
            for (Iterator<?> j = e.elementIterator("period"); j.hasNext();) {
                Element pe = (Element) j.next();
                ExamPeriod period = getPeriod(Long.valueOf(pe.attributeValue("id")));
                if ("false".equals(pe.attributeValue("available")))
                    instructor.setAvailable(period.getIndex(), false);
            }
            addConstraint(instructor);
            getInstructors().add(instructor);
        }
    if (root.element("constraints") != null)
        for (Iterator<?> i = root.element("constraints").elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            ExamDistributionConstraint dc = new ExamDistributionConstraint(
                    Long.parseLong(e.attributeValue("id")), e.getName(),
                    "true".equals(e.attributeValue("hard", "true")),
                    Integer.parseInt(e.attributeValue("weight", "0")));
            for (Iterator<?> j = e.elementIterator("exam"); j.hasNext();) {
                dc.addVariable(exams.get(Long.valueOf(((Element) j.next()).attributeValue("id"))));
            }
            addConstraint(dc);
            getDistributionConstraints().add(dc);
        }
    init();
    if (loadBest && saveBest != null) {
        for (Exam exam : variables()) {
            ExamPlacement placement = exam.getBestAssignment();
            if (placement == null)
                continue;
            exam.assign(0, placement);
        }
        saveBest.execute();
        for (Exam exam : variables()) {
            if (exam.getAssignment() != null)
                exam.unassign(0);
        }
    }
    for (ExamPlacement placement : assignments) {
        Exam exam = placement.variable();
        Set<ExamPlacement> conf = conflictValues(placement);
        if (!conf.isEmpty()) {
            for (Map.Entry<Constraint<Exam, ExamPlacement>, Set<ExamPlacement>> entry : conflictConstraints(
                    placement).entrySet()) {
                Constraint<Exam, ExamPlacement> constraint = entry.getKey();
                Set<ExamPlacement> values = entry.getValue();
                if (constraint instanceof ExamStudent) {
                    ((ExamStudent) constraint).setAllowDirectConflicts(true);
                    exam.setAllowDirectConflicts(true);
                    for (ExamPlacement p : values)
                        p.variable().setAllowDirectConflicts(true);
                }
            }
            conf = conflictValues(placement);
        }
        if (conf.isEmpty()) {
            exam.assign(0, placement);
        } else {
            sLog.error(
                    "Unable to assign " + exam.getInitialAssignment().getName() + " to exam " + exam.getName());
            sLog.error("Conflicts:" + ToolBox.dict2string(conflictConstraints(exam.getInitialAssignment()), 2));
        }
    }
    return true;
}

From source file:net.sf.jguard.ext.authentication.manager.XmlAuthenticationManager.java

License:Open Source License

private Set getCredentialsSet(Element credentialsElement) {
    List credentialsElements = credentialsElement.elements(XmlAuthenticationManager.CREDENTIAL);
    Iterator itCred = credentialsElements.iterator();
    Set<JGuardCredential> credentials = new HashSet<JGuardCredential>();
    while (itCred.hasNext()) {
        Element credentialElement = (Element) itCred.next();

        String id = credentialElement.attribute(XmlAuthenticationManager.ID).getStringValue();
        String value = credentialElement.attribute(XmlAuthenticationManager.VALUE).getStringValue();
        JGuardCredential credential = new JGuardCredential(id, value);
        credentials.add(credential);/*from  w  ww . j a v  a  2 s. co m*/
    }
    return credentials;
}

From source file:net.sf.jguard.ext.authentication.manager.XmlAuthenticationManager.java

License:Open Source License

/**
 * return a Set of Principals referenced in a <i>principalsRef<i/>
 * element./* w  w  w. j a  v  a 2s .co m*/
 *
 * @param principalElements
 * @return
 */
private Set getPrincipals(List principalElements) {
    Set ppals = new HashSet();
    for (Object principalElement : principalElements) {
        Element ppalElement = (Element) principalElement;
        Principal ppal = principals.get(ppalElement.attribute(APPLICATION_NAME).getData() + "#"
                + ppalElement.attribute(NAME).getData());
        if (ppal != null) {
            ppals.add(ppal);
        }
    }

    return ppals;
}

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

License:Open Source License

/**
 * Intercepts disco items packets to filter out users who aren't allowed to register.
 *
 * @see org.jivesoftware.openfire.interceptor.PacketInterceptor#interceptPacket(org.xmpp.packet.Packet, org.jivesoftware.openfire.session.Session, boolean, boolean)
 *//*from ww  w .  ja  va  2  s. c om*/
@SuppressWarnings("unchecked")
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) {
    // If not IQ, return immediately.
    if (!(packet instanceof IQ)) {
        return;
    }

    // If it's a result IQ, process for possible filtering.
    if (((IQ) packet).getType().equals(IQ.Type.result)) {

        // If the packet is not outgoing back to the user or not processed yet, we don't care.
        if (processed || incoming) {
            return;
        }

        // If not query, return immediately.
        Element child = packet.getElement().element("query");
        if (child == null) {
            return;
        }

        // If no namespace uri, return immediately.
        if (child.getNamespaceURI() == null) {
            return;
        }

        // If not disco#items, return immediately.
        if (!child.getNamespaceURI().equals(NameSpace.DISCO_ITEMS)) {
            return;
        }

        // If the node is null, we don't care, not directly related to a user.
        JID to = packet.getTo();
        if (to.getNode() == null) {
            return;
        }

        JID from = packet.getFrom();
        // If not from server itself, return immediately.
        if (!XMPPServer.getInstance().isLocal(from)) {
            return;
        }

        // If user registered, return immediately.
        if (RegistrationManager.getInstance().isRegistered(to, transportType)) {
            return;
        }

        // Check if allowed, if so return immediately.
        if (permissionManager.hasAccess(to)) {
            return;
        }

        // Filter out item associated with transport.
        Iterator iter = child.elementIterator();
        while (iter.hasNext()) {
            Element elem = (Element) iter.next();
            try {
                if (elem.attribute("jid").getText().equals(this.jid.toString())) {
                    child.remove(elem);
                }
            } catch (Exception e) {
                // No worries.  Wasn't what we were looking for.
            }
        }

        //TODO: should filter conference as well at some point.

        return;
    }

    // If it's a set IQ, process for possible roster activity.
    if (((IQ) packet).getType().equals(IQ.Type.set)) {

        // If the packet is not coming from the user, we don't care.
        if (!incoming) {
            return;
        }

        // If not query, return immediately.
        Element child = packet.getElement().element("query");
        if (child == null) {
            return;
        }

        // If not jabber:iq:roster, return immediately.
        if (!child.getNamespaceURI().equals(NameSpace.IQ_ROSTER)) {
            return;
        }

        // Example items in roster modification.
        Iterator iter = child.elementIterator();
        while (iter.hasNext()) {
            Element elem = (Element) iter.next();
            if (!elem.getName().equals("item")) {
                continue;
            }
            String jidStr;
            String nickname = null;
            String sub = null;
            ArrayList<String> groups = new ArrayList<String>();
            try {
                jidStr = elem.attributeValue("jid");
            } catch (Exception e) {
                // No JID found, we don't want this then.
                continue;
            }
            JID jid = new JID(jidStr);
            if (!jid.getDomain().equals(this.getJID().toString())) {
                // Not for our domain, moving on.
                continue;
            }
            if (jid.getNode() == null) {
                // Gateway itself, don't care.
                return;
            }
            try {
                nickname = elem.attributeValue("name");
            } catch (Exception e) {
                // No nickname, ok then.
            }
            try {
                sub = elem.attributeValue("subscription");
            } catch (Exception e) {
                // No subscription, no worries.
            }
            Iterator groupIter = elem.elementIterator();
            while (groupIter.hasNext()) {
                Element groupElem = (Element) groupIter.next();
                if (!groupElem.getName().equals("group")) {
                    continue;
                }
                groups.add(groupElem.getText());
            }
            if (sub != null && sub.equals("remove")) {
                try {
                    TransportSession trSession = sessionManager.getSession(session.getAddress().getNode());
                    if (!trSession.isRosterLocked(jid.toString())) {
                        Log.debug(getType().toString() + ": contact delete " + session.getAddress().getNode()
                                + ":" + jid);
                        trSession.getBuddyManager().removeBuddy(convertJIDToID(jid));
                    }
                } catch (NotFoundException e) {
                    // Well we just don't care then.
                }
            } else {
                try {
                    TransportSession trSession = sessionManager.getSession(session.getAddress().getNode());
                    if (!trSession.isRosterLocked(jid.toString())) {
                        try {
                            TransportBuddy buddy = trSession.getBuddyManager().getBuddy(jid);
                            Log.debug(
                                    getType().toString() + ": contact update " + session.getAddress().getNode()
                                            + ":" + jid + ":" + nickname + ":" + groups);
                            buddy.setNicknameAndGroups(nickname, groups);
                        } catch (NotFoundException e) {
                            Log.debug(getType().toString() + ": contact add " + session.getAddress().getNode()
                                    + ":" + jid + ":" + nickname + ":" + groups);
                            trSession.addContact(jid, nickname, groups);
                        }
                    }
                } catch (NotFoundException e) {
                    // Well we just don't care then.
                }
            }
        }
    }
}

From source file:net.sf.kraken.muc.BaseMUCTransport.java

License:Open Source License

/**
 * Handle MUC admin requests.//from   w w  w .j a  v a 2  s .co m
 *
 * @param packet An IQ packet in the MUC admin namespace.
 * @return A list of IQ packets to be returned to the user.
 */
private List<Packet> handleMUCAdmin(IQ packet) {
    List<Packet> reply = new ArrayList<Packet>();
    JID from = packet.getFrom();
    JID to = packet.getTo();

    Element query = (packet).getChildElement();
    Element item = query.element("item");
    String nick = item.attribute("nick").getText();
    String role = item.attribute("role").getText();

    try {
        TransportSession<B> session = getTransport().getSessionManager().getSession(from);
        if (session.isLoggedIn()) {
            try {
                MUCTransportSession mucSession = session.getMUCSessionManager().getSession(to.getNode());
                if (packet.getTo().getNode() == null) {
                    // Targeted at a room.
                } else {
                    // Targeted at a specific user.
                    if (nick != null && role != null) {
                        if (role.equals("none")) {
                            // This is a kick
                            String reason = "";
                            Element reasonElem = item.element("reason");
                            if (reasonElem != null) {
                                reason = reasonElem.getText();
                            }
                            mucSession.kickUser(nick, reason);
                        }
                    }
                }
            } catch (NotFoundException e) {
                // Not found?  No active session then.
            }
        }
    } catch (NotFoundException e) {
        // Not found?  No active session then.
    }

    return reply;
}

From source file:net.sf.kraken.web.ConfigManager.java

License:Open Source License

/**
 * Helper function designed to handle saving option type.
 *
 * @param node Node describing the configuration item.
 * @param options Options passed from form.
 *//*from  w  ww.  j  ava  2 s. co m*/
private void saveOptionSetting(Element node, HashMap<String, String> options) {
    Attribute type = node.attribute("type");
    if (type.getText().equals("text")) {
        // Required fields
        Attribute desckey = node.attribute("desckey");
        Attribute var = node.attribute("var");
        Attribute sysprop = node.attribute("sysprop");

        if (desckey == null || var == null || sysprop == null) {
            Log.error("Missing variable from options config.");
            return;
        }

        // Process any variables that we are setting.
        JiveGlobals.setProperty(sysprop.getText(), options.get(var.getText()));
    } else if (type.getText().equals("toggle")) {
        // Required fields
        Attribute desckey = node.attribute("desckey");
        Attribute var = node.attribute("var");
        Attribute sysprop = node.attribute("sysprop");

        if (desckey == null || var == null || sysprop == null) {
            Log.error("Missing variable from options config.");
            return;
        }

        // Process any variables that we are setting.
        JiveGlobals.setProperty(sysprop.getText(), options.get(var.getText()));

        // Process any sub-fields.
        for (Object itemObj : node.elements("item")) {
            Element item = (Element) itemObj;
            Log.debug("Found web item " + item);
            saveOptionSetting(item, options);
        }
    }
}

From source file:net.skillupjapan.openfire.plugin.SUJMessageHandlerPlugin.java

License:Open Source License

public void interceptPacket(Packet packet, Session session, boolean read, boolean processed)
        throws PacketRejectedException {

    if ((packet instanceof Message)) {
        Log.warn("Got message: " + packet.toString());
    }/*  w ww.  j a  v  a  2s.  c om*/

    /**
     * Ignore forwarded messages
     */
    if ((packet instanceof Message) && (((Message) packet).getElement().attributeValue("forwarded") != null)) {
        if (Log.isDebugEnabled()) {
            Log.warn("Ignoring forwarded message: " + packet.toString());
        }
        return;
    }

    /**
     * Adds date to all conversation packets, in the same fashion
     * as an offline packet, as described below.
     *
     * Returned message:
     * <message from='romeo@montague.net/orchard' to='juliet@capulet.com' type='chat'>
     *    <body>
     *        O blessed, blessed night! I am afeard.
     *        Being in night, all this is but a dream,
     *        Too flattering-sweet to be substantial.
     *    </body>
     *    <delay xmlns='urn:xmpp:delay' from='capulet.com' stamp='2002-09-10T23:08:25Z'/>
     * </message>
     */
    if (isValidAddDataPacket(packet, read, processed)) {
        Packet original = packet;

        // Add date to message packets
        Packet dated_packet = sujMessageHandler.addDate(packet);
        original = dated_packet;

        if (Log.isDebugEnabled()) {
            Log.debug("SUJ Message Handler: modified packet:" + original.toString());
        }
    }

    /**
    * An IQ packet can send a query for the count of messages for the given rooms
    *
    * Example query:
    * <iq type='get' id='xdfw-1'>
    *   <query xmlns='xmpp:join:msgq'>
    *      <room room_jid='rm_015551123@conference.mediline-jabber01' since='CCYY-MM-DDThh:mm:ss[.sss]TZD' />
    *      <room room_jid='rm_515156520@conference.mediline-jabber01' since='2014-04-11T09:10:59.303+0000' />
    *      <room room_jid='pc_845169551@conference.mediline-jabber01' since='1970-01-01T00:00:00Z' />
    *      ...
    *   </query>
    * </iq>
    *
    * Replied query:
    * <iq type='result' id='xdfw-1'>
    *    <query xmlns='xmpp:join:msgq'>
    *       <room room_jid='rm_015551123@conference.mediline-jabber01'>
    *           <msg_count>3</msg_count>
    *       </room>
    *       <room room_jid='rm_515156520@conference.mediline-jabber01'>
    *           <msg_count>0</msg_count>
    *       </room>
    *       ...
    *    </query>
    * </iq>
    */
    if (isValidMsgQueryPacket(packet, read, processed)) {
        Element child = ((IQ) packet).getChildElement();
        if (child != null) {
            String uri = ((Element) child).getNamespaceURI().toString();
            String qualifiedname = ((Element) child).getQualifiedName().toString();

            if (uri.equals("xmpp:join:msgq") && qualifiedname.equals("query")) {
                Log.warn("MSGQ packet: " + packet.toString());

                JID from = new JID(((IQ) packet).getElement().attribute("from").getValue());
                //Get the fields we are interested in (all the "room" requests)
                List children = ((IQ) packet).getChildElement().elements("room");
                if (!children.isEmpty()) {
                    Iterator fieldElems = children.iterator();
                    int rescount = 0;

                    // Create reply
                    IQ reply = ((IQ) packet).createResultIQ(((IQ) packet)).createCopy();
                    reply.setChildElement("query", "xmpp:join:msgq");

                    Element cur;
                    String qroom;
                    String qdate;
                    while (fieldElems.hasNext()) {
                        cur = (Element) fieldElems.next();
                        qroom = cur.attribute("room_jid").getValue();
                        qdate = cur.attribute("since").getValue();
                        rescount = sujMessageHandler.getArchivedMessageCount(qroom, qdate, from.toBareJID());

                        // Choo choo, makes the train
                        ((IQ) reply).getChildElement().addElement("room").addAttribute("room_jid", qroom)
                                .addElement("msg_count").addText(Integer.toString(rescount));

                        if (Log.isDebugEnabled()) {
                            Log.warn("I got the query token! Search for messages in " + qroom + " older than "
                                    + qdate + ": " + rescount + " messages ");
                        }
                    }

                    if (Log.isDebugEnabled()) {
                        Log.warn("Sending IQ reply: " + reply.toString());
                    }
                    // Send packet
                    try {
                        iqRouter.route(reply);
                    } catch (Exception rf) {
                        Log.error("Routing failed for IQ packet: " + reply.toString());
                    }

                } else {
                    Log.warn("Empty MsgQueryPacket!");
                }
            }
        }
    }

    /**
    * Hijack the registration request and parse information related to the JOIN service
    * This information is sent in the body of the register query.
    *
    * Example registration packet:
    * <iq type="set" id="purple343f3f96" from="mediline-jabber01/68b64d0a">
    *   <query xmlns="xmpp:iq:register">
    *     <x xmlns="xmpp:x:data" type="submit">
    *       <field var="FORM_TYPE">
    *         <value>xmpp:iq:register</value>
    *       </field>
    *       ...
    *     </x>
    *   </query>
    * </iq>
    */
    if (isValidRegisterPacket(packet, read, processed)) {
        String uri = ((IQ) packet).getChildElement().getNamespaceURI().toString();
        String qualifiedname = ((IQ) packet).getChildElement().getQualifiedName().toString();

        if (uri.equals("xmpp:iq:register") && qualifiedname.equals("query")) {
            String innerUri = ((IQ) packet).getChildElement().element("x").getNamespaceURI().toString();
            String innerQualifiedname = ((IQ) packet).getChildElement().element("x").getQualifiedName()
                    .toString();
            String innerType = ((IQ) packet).getChildElement().element("x").attribute("type").getValue()
                    .toString();
            if (Log.isDebugEnabled()) {
                Log.warn("Possible register packet... ");
            }

            if (innerUri.equals("xmpp:x:data") && innerQualifiedname.equals("x")
                    && innerType.equals("submit")) {
                if (Log.isDebugEnabled()) {
                    Log.warn("We got a registration submission!!");
                    Log.warn("packet:" + packet.toString());
                }

                //Get the field we are interested in, in this example we use the "email" attribute as the token
                Iterator fieldElems = ((IQ) packet).getChildElement().element("x").elementIterator();
                Element cur;
                while (fieldElems.hasNext()) {
                    cur = (Element) fieldElems.next();
                    if (("email").equals(cur.attribute("var").getValue())) {
                        Log.warn("I got the token! It's " + cur.getStringValue());
                    }
                }

                try {
                    if (Log.isDebugEnabled()) {
                        Log.warn("Sleeping ...");
                    }

                    //Thread.sleep(1000);
                    sujMessageHandler.googleReq();

                    if (Log.isDebugEnabled()) {
                        Log.warn("Slept");
                    }
                } catch (Exception ie) {
                    if (Log.isDebugEnabled()) {
                        Log.warn("Problem sleeping: " + ie.toString());
                    }
                }
            }
        }
    }

    /**
    * Hijack the MUC requests and check if notifications should be sent when:
    * - user is online but there's ongoing activity on a MUC the user belongs to (live notifications/IQ messages)
    * - user if offline and there are unread messages (push notifications)
    *
    * Example MUC activity packet:
    * <message content="text" to="gc_930f3e070d7@conference.mediline" type="groupchat" from="test2@mediline/7e3">
    *   <body>Message</body>
    *   <delay xmlns="urn:xmpp:delay" from="test2@mediline/7e3" stamp="2010-02-12T13:36:22.715Z"/>
    * </message>
    */
    if (isValidOutOfMUCPacket(packet, read, processed)) {
        //Log.warn("We got a MUC packet!" + packet.toString());

        // This needs to be improved!!!
        // Right now, I'm only remaking the map if new chat messages from an unknown (new) room appear
        // A listener for new MUC rooms should be handling this
        MUCRoom room = rooms.get(new JID(packet.getElement().attribute("to").getValue()));
        if (room == null) {
            makeHashByJID();
            room = rooms.get(new JID(packet.getElement().attribute("to").getValue()));
        }

        if (room != null) {
            if (room.getMembers() != null) {
                if (!room.getMembers().isEmpty()) {
                    Iterator room_users = room.getMembers().iterator();
                    JID user;
                    while (room_users.hasNext()) {
                        user = (JID) room_users.next();
                        MUCRole role = room.getOccupantByFullJID(user);

                        // User not in chatroom
                        if (role == null) {
                            if (Log.isDebugEnabled()) {
                                Log.warn("User " + user.toString() + " not in chatroom!");
                            }
                            try {
                                // If user is online still send the message (soft-forward)
                                if (presenceManager.isAvailable(userManager.getUser(user.getNode()))) {
                                    if (Log.isDebugEnabled()) {
                                        Log.warn("Forwarding message to user " + user.toString());
                                    }
                                    Message forwardMsg = (Message) packet.createCopy();
                                    forwardMsg.setFrom(new JID(packet.getElement().attribute("to").getValue()));
                                    forwardMsg.setTo(user);
                                    forwardMsg.getElement().addAttribute("forwarded", "1");
                                    messageRouter.route(forwardMsg);
                                } else {
                                    // If push notifications are enabled
                                    if (offlineMucHandlerEnabled) {
                                        // Send push notification to user, call you favouritest APN
                                        // ... Good luck! :D
                                        if (Log.isDebugEnabled()) {
                                            Log.warn("Sending push notification to user " + user.toString());
                                        }
                                    }

                                }
                            } catch (Exception e) {
                                Log.warn("User " + user.getNode() + " not found: " + e);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Handles the second device check requests. This request is received
     * without the client being authenticated with the server.
     *
     * Received message:
     * <iq type="get" id="purple3436">
     *   <query xmlns="xmpp:join:2nd_device">
     *     <id>username</id>
     *     <password>drowssap</password>
     *   </query>
     * </iq>
     * 
     * A successful reply is:
     * <iq type="result" id="purple343f3f96">
     *   <query xmlns="xmpp:join:2nd_device">
     *     <jid>test2@mediline</jid>
     *   </query>
     * </iq>
     *
     * A failed password reply is:
     * <iq type="error" id="purple343f3f96">
     *   <error type="cancel">
     *     <not-allowed xmlns="xmpp:join:2nd_device"/>
     *   </error>
     * </iq>
     *
     * An empty JID and secondID matchs reply is:
     * <iq type="error" id="purple343f3f96">
     *   <error type="cancel">
     *     <not-acceptable xmlns="xmpp:join:2nd_device"/>
     *   </error>
     * </iq>
     */
    if (isValidCheck2ndDevicePacket(packet, read, processed)) {
        String uri = ((IQ) packet).getChildElement().getNamespaceURI().toString();
        String qualifiedname = ((IQ) packet).getChildElement().getQualifiedName().toString();
        String jid = null;

        if (uri.equals("xmpp:join:2nd_device") && qualifiedname.equals("query")) {

            //Get the id and password fields
            String id = ((IQ) packet).getChildElement().element("id").getStringValue();
            String password = ((IQ) packet).getChildElement().element("password").getStringValue();

            Log.warn("Just got a 2nd device check IQ with username " + id + " and password " + password);
            Log.warn("Reply: " + packet.toString());

            try {
                jid = sujMessageHandler.getSecondDeviceJID(id, password);
            } catch (Exception ie) {
                if (Log.isDebugEnabled()) {
                    Log.warn("Problem on request: " + ie.toString());
                }
            }

            // Build reply
            IQ replyPacket = ((IQ) packet).createResultIQ(((IQ) packet)).createCopy();
            //replyPacket.setTo((JID)null);

            if (jid == null) {
                ((IQ) replyPacket).setType(IQ.Type.error);
                ((IQ) replyPacket).getElement().addElement("error").addAttribute("type", "cancel")
                        .addElement("not-acceptable").addNamespace("", "urn:ietf:params:xml:ns:xmpp-stanzas");
            } else if (jid == "invalid username or password") {
                ((IQ) replyPacket).setType(IQ.Type.error);
                ((IQ) replyPacket).getElement().addElement("error").addAttribute("type", "cancel")
                        .addElement("not-allowed").addNamespace("", "urn:ietf:params:xml:ns:xmpp-stanzas");
            } else {
                ((IQ) replyPacket).setChildElement("query", "xmpp:join:2nd_device");
                ((IQ) replyPacket).getChildElement().addElement("jid").addText(jid);
            }

            Log.warn("Reply: " + replyPacket.toString());

            // Send packet
            try {
                //iqRouter.route(replyPacket);
                session.process(replyPacket);
            } catch (Exception rf) {
                Log.error("Routing failed for IQ getting 2nd device packet");
            }
        }
    }

    /**
     * Handles the second device setup requests.
     *
     * Received message:
     * <iq type="set" id="purple3436">
     *   <query xmlns="xmpp:join:2nd_device">
     *     <id>username</id>
     *     <password>drowssap</password>
     *     <jid>aa@bbb.com<jid>
     *   </query>
     * </iq>
     *
     * On ok, send:
     * <iq type="result" id="purple343f3f96">
     *   <query xmlns="xmpp:join:2nd_device"/>
     * </iq>    
     *
     * On error, the reply is:
     * <iq type="error" id="purple343f3f96">
     *   <error type="cancel">
     *     <not-acceptable xmlns="xmpp:join:2nd_device"/>
     *   </error>
     * </iq>         
     */
    if (isValidCreate2ndDevicePacket(packet, read, processed)) {
        Log.warn("Inside 2nd device SET");
        Log.warn("WHO? " + packet.toString());
        String uri = ((IQ) packet).getChildElement().getNamespaceURI().toString();
        String qualifiedname = ((IQ) packet).getChildElement().getQualifiedName().toString();

        if (uri.equals("xmpp:join:2nd_device") && qualifiedname.equals("query") && session.getStatus() == 3) {

            //Get the id and password fields
            String id = ((IQ) packet).getChildElement().element("id").getStringValue();
            String password = ((IQ) packet).getChildElement().element("password").getStringValue();
            String jid = ((IQ) packet).getElement().attribute("from").getValue();
            int queryRes = 0;

            Log.warn("Just got a 2nd device registration IQ with username " + id + " password " + password
                    + " and jid " + jid);

            try {
                queryRes = sujMessageHandler.setSecondDeviceJID(id, password, jid);

                // Build reply
                IQ replyPacket = ((IQ) packet).createResultIQ(((IQ) packet)).createCopy();

                if (queryRes == 0) {
                    ((IQ) replyPacket).setType(IQ.Type.error);
                    ((IQ) replyPacket).getElement().addElement("error").addAttribute("type", "cancel")
                            .addElement("conflict").addNamespace("", "urn:ietf:params:xml:ns:xmpp-stanzas");
                } else {
                    ((IQ) replyPacket).setChildElement("query", "xmpp:join:2nd_device");
                }

                Log.warn("Reply: " + replyPacket.toString());

                if (replyPacket != null) {
                    iqRouter.route(replyPacket);
                } else {
                    Log.error("Routing failed for IQ setting 2nd device packet: ");
                }

            } catch (Exception ie) {
                if (Log.isDebugEnabled()) {
                    Log.warn("Problem on request: " + ie.toString());
                }
            }
        }
    }
}