Example usage for java.util Vector iterator

List of usage examples for java.util Vector iterator

Introduction

In this page you can find the example usage for java.util Vector iterator.

Prototype

public synchronized Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:org.kepler.objectmanager.ActorMetadata.java

/**
 * adds any kepler ports to the actor//from w  w w.  j a v  a 2s.co  m
 */
private NamedObj addPorts(NamedObj obj, Vector<PortMetadata> portVector)
        throws IllegalActionException, NameDuplicationException {
    boolean found = false;

    for (int i = 0; i < portVector.size(); i++) {

        // if there are any ports in the port vector that are not in the
        // port iterator, add them

        Entity ent = (Entity) obj;
        List<?> pList = ent.portList();
        Iterator<?> portIterator = pList.iterator();
        PortMetadata pm = (PortMetadata) portVector.elementAt(i);
        Vector<NamedObj> pmAtts = pm.attributes;

        if (isDebugging)
            log.debug("**********pm: " + pm.toString());

        while (portIterator.hasNext()) {

            TypedIOPort p = (TypedIOPort) portIterator.next();
            found = addPort(p, pm);
            if (found)
                break;

        }

        if (!found) {
            TypedIOPort port = null;

            if (obj instanceof TypedAtomicActor) {
                TypedAtomicActor taa = (TypedAtomicActor) obj;
                List<?> taaPL = taa.portList();
                Iterator<?> portList = taaPL.iterator();

                boolean flag = true;
                while (portList.hasNext()) {

                    TypedIOPort oldport = (TypedIOPort) portList.next();
                    String oldportName = oldport.getName();

                    if (oldportName.equals(pm.name))
                        flag = false;

                    List<?> opAttList = oldport.attributeList();

                    if (isDebugging) {
                        log.debug("old port atts: " + opAttList.size());
                        log.debug("pm att size: " + pmAtts.size());
                    }

                    if (opAttList.size() != pmAtts.size())
                        flag = true;
                }

                if (flag) {

                    if (isDebugging)
                        log.debug("adding port " + pm.name + " to obj");

                    String cpName = cleansePortName(pm.name);
                    port = new TypedIOPort(taa, cpName);

                } else {

                    if (isDebugging) {
                        log.debug("not adding port " + pm.name + " to obj");
                    }

                }
            } else {

                TypedCompositeActor tca = (TypedCompositeActor) obj;
                List<?> tcaPList = tca.portList();
                Iterator<?> portList = tcaPList.iterator();

                boolean flag = true;
                while (portList.hasNext()) {

                    TypedIOPort oldport = (TypedIOPort) portList.next();
                    String oldportName = oldport.getName();

                    if (oldportName.equals(pm.name))
                        flag = false;
                }

                if (flag) {
                    String cpName = cleansePortName(pm.name);
                    port = new TypedIOPort(tca, cpName);
                }
            }

            if (port == null) {
                continue;
            }

            if (pm.direction.equals("input")) {
                port.setInput(true);
            } else if (pm.direction.equals("output")) {
                port.setOutput(true);
            } else if (pm.direction.equals("inputoutput")) {
                port.setInput(true);
                port.setOutput(true);
            }

            if (pm.multiport) {
                port.setMultiport(true);
            }

            Iterator<?> attItt = pmAtts.iterator();
            while (attItt.hasNext()) {

                Attribute a = (Attribute) attItt.next();
                try {
                    Workspace pws = port.workspace();
                    Attribute attClone = (Attribute) a.clone(pws);
                    attClone.setContainer(port);

                } catch (CloneNotSupportedException cnse) {
                    System.out.println(
                            "Cloning the attribute " + a.getName() + " is not supported: " + cnse.getMessage());
                }
            }
        } else {
            found = false;
        }
    }

    return obj;
}

From source file:com.isencia.passerelle.hmi.generic.GenericHMI.java

@SuppressWarnings("unchecked")
@Override// w w  w.ja va  2s .  c o  m
protected void showModelForm(final String modelKey) {
    clearModelForms();

    if (this.getParentFrame() != null) {
        final URL modelURL = getModelURL();
        if (modelURL != null) {
            this.getParentFrame().setTitle("Passerelle - " + modelURL);
            modelNameLabel = new JLabel(modelURL.toString(), JLabel.CENTER);

            parameterScrollPane.getParent().add(modelNameLabel, BorderLayout.NORTH);
            parameterScrollPane.getParent().validate();
        }
    }

    if (getCurrentModel() != null) {

        final LayoutPreferences layoutPrefs = hmiDef.getLayoutPrefs(getCurrentModel().getName());

        if (layoutPrefs != null) {
            nrColumns = layoutPrefs.getNrColumns();
        }
        // sizeAndPlaceFrame();

        configPanel.setLayout(new GridLayout(1, nrColumns));
        final JPanel[] boxes = new JPanel[nrColumns];
        for (int i = 0; i < nrColumns; ++i) {
            boxes[i] = new JPanel(new VerticalLayout());
            configPanel.add(boxes[i]);
        }
        final List entities = getCurrentModel().entityList();
        if (entities != null) {
            final Vector<JPanel> actorPanels = new Vector<JPanel>();
            // render model
            if (layoutPrefs == null || layoutPrefs.getActorNames() == null
                    || layoutPrefs.getActorNames().size() == 0) {

                // render model for model parameters
                renderModelComponent(false, getCurrentModel(), boxes[0]);

                // render model for director
                if (getCurrentModel().getDirector() != null) {
                    final JPanel b = new JPanel(new VerticalLayout());
                    final boolean added = renderModelComponent(false, getCurrentModel().getDirector(), b);
                    if (added) {
                        actorPanels.add(b);
                    }
                }

                // build the vector of panels with only visible actors
                for (int i = 0; i < entities.size(); ++i) {
                    final NamedObj e = (NamedObj) entities.get(i);
                    final JPanel b = new JPanel(new VerticalLayout());
                    // JPanel b = boxes[(i+1) / nrEntriesPerColumn];
                    // Box b = boxes[(i+1) / nrEntriesPerColumn];
                    final boolean added = renderModelComponent(true, e, b);
                    if (added) {
                        actorPanels.add(b);
                    }
                }
            } else {// an actor order has been defined
                final List<String> actorNames = layoutPrefs.getActorNames();
                boolean modelParamsRendered = false;
                for (final String actorName : actorNames) {
                    final Entity e = getCurrentModel().getEntity(actorName);
                    final Attribute param = getCurrentModel().getAttribute(actorName);
                    if (getCurrentModel().getDirector().getName().equals(actorName)) {
                        // render model for director
                        if (getCurrentModel().getDirector() != null) {
                            final JPanel b = new JPanel(new VerticalLayout());
                            final boolean added = renderModelComponent(false, getCurrentModel().getDirector(),
                                    b);
                            if (added) {
                                actorPanels.add(b);
                            }
                        }
                    } else if (e != null) {
                        // render model actors
                        final JPanel b = new JPanel(new VerticalLayout());
                        final boolean added = renderModelComponent(true, e, b);
                        if (added) {
                            actorPanels.add(b);
                        }
                    } else if (param != null) {
                        // render model for model parameters
                        if (!modelParamsRendered) {
                            // since all model' params are rendered at the
                            // same time
                            // and it is possible to have several params in
                            // the layoutPrefs, make sure that is called
                            // only once
                            final JPanel b = new JPanel(new VerticalLayout());
                            final boolean added = renderModelComponent(false, getCurrentModel(), b);
                            if (added) {
                                actorPanels.add(b);
                            }
                            modelParamsRendered = true;
                        }
                    } else {
                        // it's an invalid layoutPrefs definition, e.g.
                        // defined for another model
                        // with same name or...
                        layoutPrefs.getActorNames().clear();
                        showModelForm(modelKey);
                        break;
                    }
                }
            }
            // display actors in fonction of layout prefs.
            final int nrEntriesPerColumn = actorPanels.size() / nrColumns;
            final int more = actorPanels.size() % nrColumns;
            final Iterator it = actorPanels.iterator();
            for (int i = 0; i < nrColumns; i++) {
                final JPanel column = boxes[i];
                if (i < more) {
                    if (it.hasNext()) {
                        final JPanel actor = (JPanel) it.next();
                        column.add(actor);
                    }
                }
                for (int j = 0; j < nrEntriesPerColumn; j++) {
                    if (it.hasNext()) {
                        final JPanel actor = (JPanel) it.next();
                        column.add(actor);
                    }
                }
            }
        }
        paremeterFormPanel.add("Center", configPanel);

        parameterScrollPane.validate();
    }
}

From source file:xtremweb.dispatcher.HTTPHandler.java

/**
 * This handles incoming connections. This is inherited from
 * org.mortbay.jetty.Handler. This expects a POST parameter :
 * XWPostParams.COMMAND/*from  www. j  av a 2 s . c o m*/
 * @see xtremweb.communications.XWPostParams
 */
@Override
public synchronized void handle(final String target, final Request baseRequest,
        final HttpServletRequest _request, final HttpServletResponse _response)
        throws IOException, ServletException {

    XMLRPCCommand command = null;
    final Logger logger = getLogger();
    Table obj = null;
    dataUpload = null;

    request = _request;
    response = _response;
    response.setHeader("Access-Control-Allow-Origin", "*");

    String reqUri = baseRequest.getRequestURI();

    if (request.getUserPrincipal() == null) {
        logger.debug("Handling user principal = null");
    } else {
        logger.debug("Handling user principal = " + request.getUserPrincipal().getName());
    }
    logger.debug("Handling target         = " + target);
    logger.finest("Handling request        = " + request.getContentLength() + " " + request.getContentType());
    logger.debug("Handling request auth   = " + request.getAuthType());
    logger.debug("Handling request user   = " + request.getRemoteUser());
    logger.debug("Handling parameter size = " + request.getParameterMap().size());
    logger.debug("Handling query string   = " + request.getQueryString());
    logger.debug("Handling method         = " + request.getMethod());
    logger.debug("Request URI             = " + reqUri);
    // logger.debug("Request server = " + request.getServerName());
    // logger.debug("Request port = " + request.getServerPort());
    // logger.debug("Authorization = " +
    // request.getHeader(HttpHeaders.AUTHORIZATION));
    for (final Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
        logger.finest("parameter " + e.nextElement());
    }
    for (final Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
        final String headerName = e.nextElement();
        logger.finest("header " + headerName + " : " + request.getHeader(headerName));
    }

    final Cookie[] cookies = request.getCookies();
    logger.debug("cookies.length = " + (cookies == null ? "0" : cookies.length));
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            final Cookie cookie = cookies[c];
            logger.finest("cookie " + cookie.getName() + " : " + cookie.getValue());
        }
    }
    if (request.getParameterMap().size() <= 0) {

        if (target.equals(PATH)) {
            logger.debug("redirecting to dashboard");
            redirectPage(baseRequest, Resources.DASHBOARDHTML);
            return;
        }

        for (final Resources r : Resources.values()) {
            if (r.getName().compareToIgnoreCase(target) == 0) {
                logger.debug("redirecting to " + r);
                sendResource(r);
                return;
            }
        }
    }

    final HttpSession session = request.getSession(true);
    final String mandatingLogin = (request.getParameter(XWPostParams.XWMANDATINGLOGIN.toString()) != null
            ? request.getParameter(XWPostParams.XWMANDATINGLOGIN.toString())
            : (String) session.getAttribute(XWPostParams.XWMANDATINGLOGIN.toString()));
    final String authState = (request.getParameter(XWPostParams.AUTH_STATE.toString()) != null
            ? request.getParameter(XWPostParams.AUTH_STATE.toString())
            : (String) session.getAttribute(XWPostParams.AUTH_STATE.toString()));
    final String authEmail = (request.getParameter(XWPostParams.AUTH_EMAIL.toString()) != null
            ? request.getParameter(XWPostParams.AUTH_EMAIL.toString())
            : (String) session.getAttribute(XWPostParams.AUTH_EMAIL.toString()));
    final String authId = (request.getParameter(XWPostParams.AUTH_IDENTITY.toString()) != null
            ? request.getParameter(XWPostParams.AUTH_IDENTITY.toString())
            : (String) session.getAttribute(XWPostParams.AUTH_IDENTITY.toString()));

    getLogger().debug("oauthState = " + authState);
    getLogger().debug("oauthEmail= " + authEmail);
    getLogger().debug("oauthId= " + authId);

    final UserInterface user = getUser();

    final Vector<String> paths = (Vector<String>) XWTools.split(target, "/");
    logger.debug("paths.size() = " + paths.size());

    URI baseUri = null;
    try {
        baseUri = new URI(Connection.httpsScheme() + "://" + XWTools.getHostName(request.getServerName()) + ":"
                + request.getServerPort());
    } catch (final URISyntaxException e) {
        resetIdRpc();
        throw new IOException(e);
    }

    if (target.compareToIgnoreCase(APIPATH) == 0) {
        resetIdRpc();
        writeApi(user, baseUri);
        baseRequest.setHandled(true);
        return;
    }

    if (!target.equals(PATH)) {
        try {
            final IdRpc i = IdRpc.valueOf(paths.elementAt(0).toUpperCase());
            waitIdRpc(i);
        } catch (final Exception e) {
            // let other handlers manage this (e.g. /stats, /openid)
            logger.debug("not handling " + reqUri);
            return;
        }
    }

    if (user == null) {
        resetIdRpc();
        logger.debug("no credential found");
        redirectPage(baseRequest, Resources.DASHBOARDHTML);
        return;
    }

    logger.debug("User    = " + user.toString());
    try {

        final boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        logger.debug("Handling ismultipart    = " + isMultipart);

        //
        // HTML form
        //
        if (isMultipart) {
            final List parts = servletUpload.parseRequest(request);
            logger.debug("parts.size = " + parts.size());
            if (parts != null) {
                for (final Iterator it = parts.iterator(); it.hasNext();) {
                    final FileItem item = (FileItem) it.next();

                    logger.debug("multipart item = " + item.getFieldName().toUpperCase());

                    try {
                        logger.debug("XWPostParams.valueOf(" + item.getFieldName().toUpperCase() + ") = "
                                + XWPostParams.valueOf(item.getFieldName().toUpperCase()));

                        switch (XWPostParams.valueOf(item.getFieldName().toUpperCase())) {
                        case DATAUID:
                            reqUri += "/" + item.getString();
                            break;
                        case DATAFILE:
                            dataUpload = item;
                            break;
                        case DATASHASUM:
                            dataUploadshasum = item.getString();
                            break;
                        }
                    } catch (final Exception e) {
                        logger.exception(e);
                    }
                }
            }
        }

        for (final Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
            logger.debug("parameter " + e.nextElement());
        }
        for (final Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
            logger.debug("header " + e.nextElement());
        }

        if (target.equals(PATH)) {
            sendDashboard(user);
            baseRequest.setHandled(true);
            return;
        }

        if (dataUpload != null) {
            final String value = request.getParameter(XWPostParams.DATASHASUM.toString());
            if (value != null) {
                if (dataUploadshasum == null) {
                    dataUploadshasum = value;
                }
            }
            logger.debug("Parameters upload size = " + dataUpload.getSize() + " dataUploadshasum = "
                    + dataUploadshasum);
        }

        final Iterator<String> it = paths.iterator();
        final StringBuilder uriWithoutCmd = new StringBuilder();
        int i = 0;
        while (it.hasNext()) {
            final String st = it.next();
            logger.debug("Parsing path path = " + st);
            if (i++ > 0) {
                uriWithoutCmd.append("/" + st);
            }
        }

        final URI uri = new URI(Connection.httpsScheme() + "://" + XWTools.getHostName(request.getServerName())
                + ":" + request.getServerPort() + uriWithoutCmd.toString());
        logger.debug("URI = " + uri);

        final String objXmlDesc = request.getParameter(XWPostParams.XMLDESC.toString());
        logger.finest("objXmlDesc = " + objXmlDesc);

        if (objXmlDesc != null) {
            final ByteArrayInputStream in = new ByteArrayInputStream(objXmlDesc.getBytes());
            try {
                obj = Table.newInterface(in);
            } finally {
                in.close();
            }
        }

        if (obj != null) {
            logger.debug("obj = " + obj.toXml());
            if (obj.getUID() == null) {
                obj.setUID(new UID());
            }
        } else {
            logger.debug("obj = null");
        }
        command = getIdRpc().newCommand(uri, user, obj);
        command.setMandatingLogin(mandatingLogin);

        final String parameter = request.getParameter(XWPostParams.PARAMETER.toString());
        logger.debug("parameter = " + parameter);

        if (parameter != null) {
            switch (getIdRpc()) {
            case CHMOD: {
                final XWAccessRights ar = new XWAccessRights(parameter);
                ((XMLRPCCommandChmod) command).setModifier(ar);
                break;
            }
            case ACTIVATEHOST: {
                final Boolean b = new Boolean(parameter);
                ((XMLRPCCommandActivateHost) command).setActivation(b);
                break;
            }
            case WORKALIVE: {
                final XMLHashtable p = new XMLHashtable(StreamIO.stream(parameter));
                logger.debug("XMLHastable = " + (p == null ? "null" : p.toXml()));
                ((XMLRPCCommandWorkAlive) command).setParameter(p);
                break;
            }
            default:
                break;
            }
        }
        command.getUser().setLogin(user.getLogin());
        command.getUser().setPassword(user.getPassword());
        command.getUser().setUID(user.getUID());
    } catch (final Exception e) {
        command = null;
        logger.exception(e);
        logger.error(e.toString());
    }

    try {
        if (command != null) {
            command.setRemoteName(request.getRemoteHost());
            command.setRemoteIP(request.getRemoteAddr());
            command.setRemotePort(request.getRemotePort());

            logger.debug("cmd = " + command.toXml());

            if (command.getIdRpc() == IdRpc.DOWNLOADDATA) {
                final UID uid = command.getURI().getUID();
                String contentTypeValue = CONTENTTYPEVALUE;

                try {
                    final DataInterface theData = DBInterface.getInstance().getData(command);
                    final DataTypeEnum dataType = theData != null ? theData.getType() : null;
                    final Date lastModified = theData != null ? theData.getMTime() : null;
                    if (theData != null) {
                        if (lastModified != null) {
                            response.setHeader(LASTMODIFIEDLABEL, lastModified.toString());
                        }
                        response.setHeader(CONTENTLENGTHLABEL, "" + theData.getSize());
                        response.setHeader(CONTENTSHASUMLABEL, theData.getShasum());
                        response.setHeader(CONTENTDISPOSITIONLABEL,
                                "attachment; filename=\"" + theData.getName() + "\"");
                    }
                    if (dataType != null) {
                        contentTypeValue = dataType.getMimeType();
                    }
                } catch (final Exception e) {
                    if (logger.debug()) {
                        logger.exception(e);
                    }
                }

                logger.debug("set " + CONTENTTYPELABEL + " : " + contentTypeValue);
                response.setHeader(CONTENTTYPELABEL, contentTypeValue);
            }

            super.run(command);
        } else {
            write((XMLable) null);
        }
    } finally {
        command = null;
        obj = null;
        baseRequest.setHandled(true);
        notifyAll();
    }
}

From source file:org.unitime.timetable.model.Solution.java

public void createDivSecNumbers(org.hibernate.Session hibSession, Vector messages) {
    Vector assignments = new Vector(getAssignments());
    assignments.addAll(new SolutionDAO().getSession()
            .createQuery("select distinct c from Class_ c, Solution s inner join s.owner.departments d "
                    + "where s.uniqueId = :solutionId and c.managingDept=d and "
                    + "c.uniqueId not in (select a.clazz.uniqueId from s.assignments a)")
            .setLong("solutionId", getUniqueId().longValue()).list());
    HashSet relatedOfferings = new HashSet();
    for (Enumeration e = assignments.elements(); e.hasMoreElements();) {
        Object o = e.nextElement();
        Assignment assignment = (o instanceof Assignment ? (Assignment) o : null);
        Class_ clazz = (assignment == null ? (Class_) o : assignment.getClazz());
        relatedOfferings.add(clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering());
    }/*from   w ww.j a  va 2  s  .  c o m*/
    for (Iterator i = relatedOfferings.iterator(); i.hasNext();) {
        InstructionalOffering io = (InstructionalOffering) i.next();
        for (Iterator j = io.getInstrOfferingConfigs().iterator(); j.hasNext();) {
            InstrOfferingConfig ioc = (InstrOfferingConfig) j.next();
            for (Iterator k = ioc.getSchedulingSubparts().iterator(); k.hasNext();) {
                SchedulingSubpart subpart = (SchedulingSubpart) k.next();
                for (Iterator l = subpart.getClasses().iterator(); l.hasNext();) {
                    Class_ clazz = (Class_) l.next();
                    if (clazz.getClassSuffix() != null
                            && !getOwner().getDepartments().contains(clazz.getManagingDept())) {
                        Assignment assignment = clazz.getCommittedAssignment();
                        assignments.add(assignment == null ? (Object) clazz : (Object) assignment);
                        clazz.setClassSuffix(null);
                    }
                }
            }
        }
    }
    DivSecAssignmentComparator cmp = new DivSecAssignmentComparator(this, true, false);
    Collections.sort(assignments, cmp);

    Assignment lastAssignment = null;
    SchedulingSubpart lastSubpart = null;
    Class_ lastClazz = null;
    int divNum = 1, secNum = 0;
    HashSet takenDivNums = null;

    HashSet recompute = new HashSet();

    for (Enumeration e = assignments.elements(); e.hasMoreElements();) {
        Object o = e.nextElement();
        Assignment assignment = (o instanceof Assignment ? (Assignment) o : null);
        Class_ clazz = (assignment == null ? (Class_) o : assignment.getClazz());

        if (clazz.getParentClass() != null && clazz.getSchedulingSubpart().getItype()
                .equals(clazz.getParentClass().getSchedulingSubpart().getItype()))
            continue;

        if (lastSubpart == null || !lastSubpart.equals(clazz.getSchedulingSubpart())) {
            takenDivNums = takenDivisionNumbers(clazz.getSchedulingSubpart());
            lastAssignment = null;
            lastSubpart = null;
            lastClazz = null;
        }

        int nrClasses = clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering()
                .getNrClasses(clazz.getSchedulingSubpart().getItype());

        if (lastAssignment != null && assignment != null) {
            if (nrClasses >= 100 && cmp.compareTimeLocations(lastAssignment.getClazz(), assignment.getClazz(),
                    lastAssignment.getTimeLocation(), assignment.getTimeLocation()) == 0) {
                if (lastClazz != null && clazz.getParentClass() != null
                        && !clazz.getParentClass().equals(lastClazz.getParentClass())
                        && clazz.getParentClass().getDivSecNumber() != null
                        && lastClazz.getParentClass().getDivSecNumber() != null) {
                    if (cmp.compareTimeLocations(lastAssignment.getClazz(), assignment.getClazz(),
                            lastAssignment.getTimeLocation(), assignment.getTimeLocation()) == 0
                            && clazz.getParentClass().getDivSecNumber().substring(0, 3)
                                    .equals(lastClazz.getParentClass().getDivSecNumber().substring(0, 3))) {
                        secNum++;
                    } else {
                        divNum++;
                        secNum = 1;
                        while (takenDivNums.contains(new Integer(divNum)))
                            divNum++;
                    }
                } else {
                    secNum++;
                }
            } else {
                divNum++;
                secNum = 1;
                while (takenDivNums.contains(new Integer(divNum)))
                    divNum++;
            }
        } else if (lastClazz != null) {
            divNum++;
            secNum = 1;
            while (takenDivNums.contains(new Integer(divNum)))
                divNum++;
        } else {
            divNum = 1;
            secNum = 1;
            while (takenDivNums.contains(new Integer(divNum)))
                divNum++;
        }

        if (divNum == 100 && secNum == 1) {
            sLog.warn("Division number exceeded 99 for scheduling subpart "
                    + clazz.getSchedulingSubpart().getSchedulingSubpartLabel() + ".");
            for (Iterator i = clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering()
                    .getInstrOfferingConfigs().iterator(); i.hasNext();) {
                InstrOfferingConfig cfg = (InstrOfferingConfig) i.next();
                for (Iterator j = cfg.getSchedulingSubparts().iterator(); j.hasNext();) {
                    SchedulingSubpart subpart = (SchedulingSubpart) j.next();
                    if (subpart.getItype().equals(clazz.getSchedulingSubpart().getItype()))
                        recompute.add(subpart);
                }
            }
        }

        clazz.setClassSuffix(sSufixFormat.format(divNum) + sSufixFormat.format(secNum));
        hibSession.update(clazz);

        lastAssignment = assignment;
        lastSubpart = clazz.getSchedulingSubpart();
        lastClazz = clazz;
    }

    if (!recompute.isEmpty()) {
        HashSet recompute2 = new HashSet();
        for (Iterator i = assignments.iterator(); i.hasNext();) {
            Object o = i.next();
            Assignment assignment = (o instanceof Assignment ? (Assignment) o : null);
            Class_ clazz = (assignment == null ? (Class_) o : assignment.getClazz());
            if (recompute.contains(clazz.getSchedulingSubpart())) {
                clazz.setClassSuffix(null);
                hibSession.update(clazz);
            } else {
                i.remove();
            }
        }
        cmp = new DivSecAssignmentComparator(this, false, false);
        Collections.sort(assignments, cmp);
        lastAssignment = null;
        lastSubpart = null;
        lastClazz = null;
        for (Enumeration e = assignments.elements(); e.hasMoreElements();) {
            Object o = e.nextElement();
            Assignment assignment = (o instanceof Assignment ? (Assignment) o : null);
            Class_ clazz = (assignment == null ? (Class_) o : assignment.getClazz());

            if (lastSubpart == null || !lastSubpart.equals(clazz.getSchedulingSubpart())) {
                takenDivNums = takenDivisionNumbers(clazz.getSchedulingSubpart());
                lastAssignment = null;
                lastSubpart = null;
                lastClazz = null;
            }

            if (lastAssignment != null && assignment != null) {
                if (cmp.compareTimeLocations(lastAssignment.getClazz(), assignment.getClazz(),
                        lastAssignment.getTimeLocation(), assignment.getTimeLocation()) == 0) {
                    secNum++;
                } else {
                    divNum++;
                    secNum = 1;
                    while (takenDivNums.contains(new Integer(divNum)))
                        divNum++;
                }
            } else if (lastClazz != null) {
                divNum++;
                secNum = 1;
                while (takenDivNums.contains(new Integer(divNum)))
                    divNum++;
            } else {
                divNum = 1;
                secNum = 1;
                while (takenDivNums.contains(new Integer(divNum)))
                    divNum++;
            }

            if (divNum == 100 && secNum == 1) {
                sLog.warn("Division number still (fallback) exceeded 99 for scheduling subpart "
                        + clazz.getSchedulingSubpart().getSchedulingSubpartLabel() + ".");
                for (Iterator i = clazz.getSchedulingSubpart().getInstrOfferingConfig()
                        .getInstructionalOffering().getInstrOfferingConfigs().iterator(); i.hasNext();) {
                    InstrOfferingConfig cfg = (InstrOfferingConfig) i.next();
                    for (Iterator j = cfg.getSchedulingSubparts().iterator(); j.hasNext();) {
                        SchedulingSubpart subpart = (SchedulingSubpart) j.next();
                        if (subpart.getItype().equals(clazz.getSchedulingSubpart().getItype()))
                            recompute2.add(subpart);
                    }
                }
            }

            clazz.setClassSuffix(sSufixFormat.format(divNum) + sSufixFormat.format(secNum));
            hibSession.update(clazz);

            lastAssignment = assignment;
            lastSubpart = clazz.getSchedulingSubpart();
            lastClazz = clazz;
        }

        if (!recompute2.isEmpty()) {
            for (Iterator i = assignments.iterator(); i.hasNext();) {
                Object o = i.next();
                Assignment assignment = (o instanceof Assignment ? (Assignment) o : null);
                Class_ clazz = (assignment == null ? (Class_) o : assignment.getClazz());
                if (recompute2.contains(clazz.getSchedulingSubpart())) {
                    clazz.setClassSuffix(null);
                    hibSession.update(clazz);
                } else {
                    i.remove();
                }
            }
            cmp = new DivSecAssignmentComparator(this, false, true);
            Collections.sort(assignments, cmp);
            lastAssignment = null;
            lastSubpart = null;
            lastClazz = null;
            for (Enumeration e = assignments.elements(); e.hasMoreElements();) {
                Object o = e.nextElement();
                Assignment assignment = (o instanceof Assignment ? (Assignment) o : null);
                Class_ clazz = (assignment == null ? (Class_) o : assignment.getClazz());

                if (lastSubpart == null
                        || cmp.compareSchedulingSubparts(lastSubpart, clazz.getSchedulingSubpart()) != 0) {
                    takenDivNums = takenDivisionNumbers(clazz.getSchedulingSubpart());
                    lastAssignment = null;
                    lastSubpart = null;
                    lastClazz = null;
                }

                if (lastAssignment != null && assignment != null) {
                    if (cmp.compareTimeLocations(lastAssignment.getClazz(), assignment.getClazz(),
                            lastAssignment.getTimeLocation(), assignment.getTimeLocation()) == 0) {
                        secNum++;
                    } else {
                        divNum++;
                        secNum = 1;
                        while (takenDivNums.contains(new Integer(divNum)))
                            divNum++;
                    }
                } else if (lastClazz != null) {
                    divNum++;
                    secNum = 1;
                    while (takenDivNums.contains(new Integer(divNum)))
                        divNum++;
                } else {
                    divNum = 1;
                    secNum = 1;
                    while (takenDivNums.contains(new Integer(divNum)))
                        divNum++;
                }

                if (divNum == 100 && secNum == 1) {
                    messages.add("Division number exceeded 99 for scheduling subpart "
                            + clazz.getSchedulingSubpart().getSchedulingSubpartLabel() + ".");
                    sLog.warn("Division number still (fallback2) exceeded 99 for scheduling subpart "
                            + clazz.getSchedulingSubpart().getSchedulingSubpartLabel() + ".");
                }

                clazz.setClassSuffix(sSufixFormat.format(divNum) + sSufixFormat.format(secNum));
                hibSession.update(clazz);

                lastAssignment = assignment;
                lastSubpart = clazz.getSchedulingSubpart();
                lastClazz = clazz;
            }
        }
    }

    /*
    lastSubpart = null;
    TreeSet otherClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY));
    otherClasses.addAll(new SolutionDAO().getSession().createQuery(
        "select distinct c from Class_ c, Solution s inner join s.owner.departments d "+
        "where s.uniqueId = :solutionId and c.managingDept=d and "+
        "c.uniqueId not in (select a.clazz.uniqueId from s.assignments a) order by c.schedulingSubpart.uniqueId, c.sectionNumberCache").
        setLong("solutionId", getUniqueId().longValue()).
        list());
            
    for (Iterator i=otherClasses.iterator();i.hasNext();) {
    Class_ clazz = (Class_)i.next();
            
    if (clazz.getParentClass()!=null && clazz.getSchedulingSubpart().getItype().equals(clazz.getParentClass().getSchedulingSubpart().getItype()))
        continue;
            
    if (clazz.getClassSuffix()!=null) {
        sLog.warn("This is odd, class "+clazz.getClassLabel()+" already has a div-sec number "+clazz.getClassSuffix()+".");
        continue;
    }
            
    if (lastSubpart==null || !lastSubpart.equals(clazz.getSchedulingSubpart())) {
        takenDivNums = takenDivisionNumbers(clazz.getSchedulingSubpart());
    }
    divNum = 1;
    while (takenDivNums.contains(new Integer(divNum)))
        divNum++;
    if (divNum==100) {
        messages.add("Division number exceeded 99 for scheduling subpart "+clazz.getSchedulingSubpart().getSchedulingSubpartLabel()+".");
    }
    clazz.setClassSuffix(sSufixFormat.format(divNum)+sSufixFormat.format(1));
    takenDivNums.add(new Integer(divNum));
    lastSubpart = clazz.getSchedulingSubpart();
    hibSession.update(clazz);
    }
    */
}

From source file:org.unitime.timetable.test.StudentSectioningTest.java

public static void saveStudent(Session session, Student student, Vector messages) {
    org.unitime.timetable.model.Student s = org.unitime.timetable.model.Student
            .findByExternalId(session.getUniqueId(), String.valueOf(student.getId()));
    if (s == null) {
        sLog.warn("  Student " + student + " not found.");
        return;//w  ww  .  j a  va2  s.c  om
    }
    org.hibernate.Session hibSession = new StudentDAO().getSession();
    Transaction tx = hibSession.beginTransaction();
    try {
        for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
            Request request = (Request) e.next();
            if (request instanceof CourseRequest)
                updateSectioningInfos(hibSession, s, (CourseRequest) request);
        }
        for (Iterator i = s.getClassEnrollments().iterator(); i.hasNext();) {
            StudentClassEnrollment sce = (StudentClassEnrollment) i.next();
            sce.getClazz().getStudentEnrollments().remove(sce);
            // sce.getClazz().setEnrollment(sce.getClazz().getEnrollment()-1);
            hibSession.delete(sce);
            i.remove();
        }
        for (Iterator i = s.getWaitlists().iterator(); i.hasNext();) {
            WaitList wl = (WaitList) i.next();
            hibSession.delete(wl);
            i.remove();
        }
        for (Iterator i = s.getCourseDemands().iterator(); i.hasNext();) {
            CourseDemand cd = (CourseDemand) i.next();
            if (cd.getFreeTime() != null)
                hibSession.delete(cd.getFreeTime());
            hibSession.delete(cd);
            i.remove();
        }
        hibSession.flush();
        for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
            Request request = (Request) e.next();
            CourseDemand cd = null;
            if (request instanceof FreeTimeRequest) {
                FreeTimeRequest freeTime = (FreeTimeRequest) request;
                FreeTime ft = new FreeTime();
                ft.setCategory(new Integer(freeTime.getTime().getBreakTime()));
                ft.setDayCode(new Integer(freeTime.getTime().getDayCode()));
                ft.setLength(new Integer(freeTime.getTime().getLength()));
                ft.setName(freeTime.getTime().getLongName());
                ft.setSession(session);
                ft.setStartSlot(new Integer(freeTime.getTime().getStartSlot()));
                hibSession.save(ft);
                cd = new CourseDemand();
                cd.setStudent(s);
                cd.setPriority(new Integer(request.getPriority()));
                cd.setAlternative(new Boolean(request.isAlternative()));
                cd.setWaitlist(Boolean.FALSE);
                cd.setTimestamp(new Date());
                cd.setFreeTime(ft);
                hibSession.save(cd);
            } else if (request instanceof CourseRequest) {
                CourseRequest courseRequest = (CourseRequest) request;
                cd = new CourseDemand();
                cd.setStudent(s);
                cd.setPriority(new Integer(request.getPriority()));
                cd.setAlternative(new Boolean(request.isAlternative()));
                cd.setWaitlist(new Boolean(courseRequest.isWaitlist()));
                cd.setTimestamp(new Date());
                hibSession.save(cd);
                int ord = 0;
                Enrollment enrollment = (Enrollment) request.getAssignment();
                org.unitime.timetable.model.CourseRequest crq = null;
                for (Iterator f = courseRequest.getCourses().iterator(); f.hasNext(); ord++) {
                    Course course = (Course) f.next();
                    org.unitime.timetable.model.CourseRequest cr = new org.unitime.timetable.model.CourseRequest();
                    cr.setOrder(new Integer(ord));
                    cr.setAllowOverlap(Boolean.FALSE);
                    cr.setCourseDemand(cd);
                    cr.setCourseOffering(new CourseOfferingDAO().get(new Long(course.getId())));
                    cr.setCredit(new Integer(-1));
                    hibSession.save(cr);
                    if (enrollment != null && course.getOffering().equals(enrollment.getOffering()))
                        crq = cr;
                    for (Iterator i = courseRequest.getSelectedChoices().iterator(); i.hasNext();) {
                        Choice choice = (Choice) i.next();
                        if (!choice.getOffering().equals(course.getOffering()))
                            continue;
                        for (Iterator j = choice.getSections().iterator(); j.hasNext();) {
                            Section section = (Section) j.next();
                            ClassWaitList cwl = new ClassWaitList();
                            cwl.setClazz(new Class_DAO().get(new Long(section.getId())));
                            cwl.setCourseRequest(cr);
                            cwl.setStudent(s);
                            cwl.setTimestamp(new Date());
                            cwl.setType(ClassWaitList.TYPE_SELECTION);
                            hibSession.save(cwl);
                        }
                    }
                    for (Iterator i = courseRequest.getWaitlistedChoices().iterator(); i.hasNext();) {
                        Choice choice = (Choice) i.next();
                        if (!choice.getOffering().equals(course.getOffering()))
                            continue;
                        for (Iterator j = choice.getSections().iterator(); j.hasNext();) {
                            Section section = (Section) j.next();
                            ClassWaitList cwl = new ClassWaitList();
                            cwl.setClazz(new Class_DAO().get(new Long(section.getId())));
                            cwl.setCourseRequest(cr);
                            cwl.setStudent(s);
                            cwl.setTimestamp(new Date());
                            cwl.setType(ClassWaitList.TYPE_WAITLIST);
                            hibSession.save(cwl);
                        }
                    }
                }
                if (enrollment == null) {
                    if (courseRequest.isWaitlist() && student.canAssign(courseRequest)) {
                        WaitList wl = new WaitList();
                        wl.setStudent(s);
                        wl.setCourseOffering(new CourseOfferingDAO()
                                .get(new Long(((Course) courseRequest.getCourses().get(0)).getId())));
                        wl.setTimestamp(new Date());
                        wl.setType(new Integer(0));
                        hibSession.save(wl);
                    }
                } else {
                    for (Iterator i = enrollment.getAssignments().iterator(); i.hasNext();) {
                        Section section = (Section) i.next();
                        StudentClassEnrollment sce = new StudentClassEnrollment();
                        sce.setStudent(s);
                        Class_ clazz = new Class_DAO().get(new Long(section.getId()));
                        sce.setClazz(clazz);
                        s.getClassEnrollments().add(sce);
                        clazz.getStudentEnrollments().add(sce);
                        sce.setCourseRequest(crq);
                        sce.setCourseOffering(crq.getCourseOffering());
                        sce.setTimestamp(new Date());
                        clazz.setEnrollment(clazz.getEnrollment() == null ? 1 : clazz.getEnrollment() + 1);
                        hibSession.save(sce);
                    }
                }
            }
            if (cd != null && messages != null) {
                int ord = 0;
                for (Iterator f = messages.iterator(); f.hasNext();) {
                    StudentSctBBTest.Message message = (StudentSctBBTest.Message) f.next();
                    if (request.equals(message.getRequest())) {
                        StudentEnrollmentMessage m = new StudentEnrollmentMessage();
                        m.setCourseDemand(cd);
                        m.setLevel(new Integer(message.getLevel()));
                        m.setType(new Integer(0));
                        m.setTimestamp(new Date());
                        m.setMessage(message.getMessage());
                        m.setOrder(new Integer(ord++));
                        hibSession.save(m);
                    }
                }
            }
        }
        hibSession.saveOrUpdate(s);

        StudentSectioningQueue.studentChanged(hibSession, null, s.getSession().getUniqueId(), s.getUniqueId());

        hibSession.flush();
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw new RuntimeException(e);
    }
    hibSession.refresh(s);
}

From source file:org.sakaiproject.calendar.tool.CalendarAction.java

/**
 * Build the context for showing list view
 *//*from ww w  . j  ava  2s . co  m*/
protected void buildListContext(VelocityPortlet portlet, Context context, RunData runData,
        CalendarActionState state) {
    // to get the content Type Image Service
    context.put("contentTypeImageService", ContentTypeImageService.getInstance());
    context.put("tlang", rb);
    context.put("config", configProps);
    MyMonth monthObj2 = null;
    MyDate dateObj1 = new MyDate();
    CalendarEventVector calendarEventVectorObj = null;
    boolean allowed = false;
    LinkedHashMap yearMap = new LinkedHashMap();

    // Initialize month format object      
    if (monthFormat == null) {
        monthFormat = NumberFormat.getInstance(new ResourceLoader().getLocale());
        monthFormat.setMinimumIntegerDigits(2);
    }

    String peid = ((JetspeedRunData) runData).getJs_peid();
    SessionState sstate = ((JetspeedRunData) runData).getPortletSessionState(peid);

    Time m_time = TimeService.newTime();
    TimeBreakdown b = m_time.breakdownLocal();
    int stateYear = b.getYear();
    int stateMonth = b.getMonth();
    int stateDay = b.getDay();
    if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null)
            && (sstate.getAttribute(STATE_DAY) != null)) {
        stateYear = ((Integer) sstate.getAttribute(STATE_YEAR)).intValue();
        stateMonth = ((Integer) sstate.getAttribute(STATE_MONTH)).intValue();
        stateDay = ((Integer) sstate.getAttribute(STATE_DAY)).intValue();
    }

    // Set up list filtering information in the context.
    context.put(TIME_FILTER_OPTION_VAR, state.getCalendarFilter().getListViewFilterMode());

    //
    // Fill in the custom dates
    //
    String sDate; // starting date
    String eDate; // ending date

    java.util.Calendar userCal = java.util.Calendar.getInstance();
    context.put("ddStartYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) - 3));
    context.put("ddEndYear", Integer.valueOf(userCal.get(java.util.Calendar.YEAR) + 4));

    String sM;
    String eM;
    String sD;
    String eD;
    String sY;
    String eY;

    if (state.getCalendarFilter().isCustomListViewDates()) {
        sDate = state.getCalendarFilter().getStartingListViewDateString();
        eDate = state.getCalendarFilter().getEndingListViewDateString();

        sM = sDate.substring(0, 2);
        eM = eDate.substring(0, 2);
        sD = sDate.substring(3, 5);
        eD = eDate.substring(3, 5);
        sY = "20" + sDate.substring(6);
        eY = "20" + eDate.substring(6);
    } else {
        //default to current week
        CalendarUtil calObj = new CalendarUtil();
        calObj.setDay(stateYear, stateMonth, stateDay);
        TimeRange weekRange = getWeekTimeRange(calObj);
        sD = String.valueOf(weekRange.firstTime().breakdownLocal().getDay());
        sY = String.valueOf(weekRange.firstTime().breakdownLocal().getYear());
        sM = monthFormat.format(weekRange.firstTime().breakdownLocal().getMonth());

        eD = String.valueOf(weekRange.lastTime().breakdownLocal().getDay());
        eY = String.valueOf(weekRange.lastTime().breakdownLocal().getYear());
        eM = monthFormat.format(weekRange.lastTime().breakdownLocal().getMonth());
    }

    context.put(TIME_FILTER_SETTING_CUSTOM_START_YEAR, Integer.valueOf(sY));
    context.put(TIME_FILTER_SETTING_CUSTOM_END_YEAR, Integer.valueOf(eY));
    context.put(TIME_FILTER_SETTING_CUSTOM_START_MONTH, Integer.valueOf(sM));
    context.put(TIME_FILTER_SETTING_CUSTOM_END_MONTH, Integer.valueOf(eM));
    context.put(TIME_FILTER_SETTING_CUSTOM_START_DAY, Integer.valueOf(sD));
    context.put(TIME_FILTER_SETTING_CUSTOM_END_DAY, Integer.valueOf(eD));

    CalendarUtil calObj = new CalendarUtil();
    calObj.setDay(stateYear, stateMonth, stateDay);
    dateObj1.setTodayDate(calObj.getMonthInteger(), calObj.getDayOfMonth(), calObj.getYear());

    // fill this month object with all days avilable for this month
    if (CalendarService.allowGetCalendar(state.getPrimaryCalendarReference()) == false) {
        allowed = false;
        context.put(ALERT_MSG_KEY, rb.getString("java.alert.younotallow"));
        calendarEventVectorObj = new CalendarEventVector();
    } else {
        try {
            allowed = CalendarService.getCalendar(state.getPrimaryCalendarReference()).allowAddEvent();
        } catch (IdUnusedException e) {
            context.put(ALERT_MSG_KEY, rb.getString("java.alert.therenoactv"));
            M_log.debug(".buildMonthContext(): " + e);
        } catch (PermissionException e) {
            context.put(ALERT_MSG_KEY, rb.getString("java.alert.younotperm"));
            M_log.debug(".buildMonthContext(): " + e);
        }
    }

    int yearInt, monthInt, dayInt = 1;

    TimeRange fullTimeRange = TimeService.newTimeRange(
            TimeService.newTimeLocal(CalendarFilter.LIST_VIEW_STARTING_YEAR, 1, 1, 0, 0, 0, 0),
            TimeService.newTimeLocal(CalendarFilter.LIST_VIEW_ENDING_YEAR, 12, 31, 23, 59, 59, 999));

    // We need to get events from all calendars for the full time range.
    CalendarEventVector masterEventVectorObj = CalendarService.getEvents(
            getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(), isOnWorkspaceTab()),
            fullTimeRange);

    // groups awareness - filtering
    String calId = state.getPrimaryCalendarReference();
    String scheduleTo = (String) sstate.getAttribute(STATE_SCHEDULE_TO);

    try {
        Calendar calendarObj = CalendarService.getCalendar(calId);
        context.put("cal", calendarObj);

        if (scheduleTo != null && scheduleTo.length() != 0) {
            context.put("scheduleTo", scheduleTo);
        } else {
            if (calendarObj.allowGetEvents()) {
                // default to make site selection
                context.put("scheduleTo", "site");
            } else if (calendarObj.getGroupsAllowGetEvent().size() > 0) {
                // to group otherwise
                context.put("scheduleTo", "groups");
            }
        }

        Collection groups = calendarObj.getGroupsAllowGetEvent();
        if (groups.size() > 0) {
            context.put("groups", groups);

        }
        List schToGroups = (List) (sstate.getAttribute(STATE_SCHEDULE_TO_GROUPS));
        context.put("scheduleToGroups", schToGroups);

        CalendarEventVector newEventVectorObj = new CalendarEventVector();
        newEventVectorObj.addAll(masterEventVectorObj);

        for (Iterator i = masterEventVectorObj.iterator(); i.hasNext();) {
            CalendarEvent e = (CalendarEvent) (i.next());

            String origSiteId = (CalendarService.getCalendar(e.getCalendarReference())).getContext();
            if (!origSiteId.equals(ToolManager.getCurrentPlacement().getContext())) {
                context.put("fromColExist", Boolean.TRUE);
            }

            if ((schToGroups != null) && (schToGroups.size() > 0)) {
                boolean eventInGroup = false;
                for (Iterator j = schToGroups.iterator(); j.hasNext();) {
                    String groupRangeForDisplay = e.getGroupRangeForDisplay(calendarObj);
                    String groupId = j.next().toString();
                    Site site = SiteService.getSite(calendarObj.getContext());
                    Group group = site.getGroup(groupId);
                    if (groupRangeForDisplay.equals("") || groupRangeForDisplay.equals("site"))
                        eventInGroup = true;
                    if (groupRangeForDisplay.indexOf(group.getTitle()) != -1)
                        eventInGroup = true;
                }
                if (!eventInGroup)
                    newEventVectorObj.remove(e);
            }
        }

        if ((schToGroups != null) && (schToGroups.size() > 0)) {
            masterEventVectorObj.clear();
            masterEventVectorObj.addAll(newEventVectorObj);
        }
    } catch (IdUnusedException e) {
        M_log.debug(".buildListContext(): " + e);
    } catch (PermissionException e) {
        M_log.debug(".buildListContext(): " + e);
    }

    boolean dateDsc = sstate.getAttribute(STATE_DATE_SORT_DSC) != null;
    context.put("currentDateSortAsc", Boolean.valueOf(!dateDsc));

    if (!dateDsc) {
        for (yearInt = CalendarFilter.LIST_VIEW_STARTING_YEAR; yearInt <= CalendarFilter.LIST_VIEW_ENDING_YEAR; yearInt++) {
            Vector arrayOfMonths = new Vector(20);
            for (monthInt = 1; monthInt < 13; monthInt++) {
                CalendarUtil AcalObj = new CalendarUtil();

                monthObj2 = new MyMonth();
                AcalObj.setDay(yearInt, monthInt, dayInt);

                dateObj1.setTodayDate(AcalObj.getMonthInteger(), AcalObj.getDayOfMonth(), AcalObj.getYear());

                // Get the events for the particular month from the
                // master list of events.
                calendarEventVectorObj = new CalendarEventVector(state.getCalendarFilter().filterEvents(
                        masterEventVectorObj.getEvents(getMonthTimeRange((CalendarUtil) AcalObj))));

                if (!calendarEventVectorObj.isEmpty()) {
                    AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay());

                    monthObj2 = calMonth(monthInt, (CalendarUtil) AcalObj, state, calendarEventVectorObj);

                    AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay());

                    if (!calendarEventVectorObj.isEmpty())
                        arrayOfMonths.addElement(monthObj2);
                }
            }
            if (!arrayOfMonths.isEmpty())
                yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator());
        }
    } else {
        for (yearInt = CalendarFilter.LIST_VIEW_ENDING_YEAR; yearInt >= CalendarFilter.LIST_VIEW_STARTING_YEAR; yearInt--) {
            Vector arrayOfMonths = new Vector(20);
            for (monthInt = 12; monthInt >= 1; monthInt--) {
                CalendarUtil AcalObj = new CalendarUtil();

                monthObj2 = new MyMonth();
                AcalObj.setDay(yearInt, monthInt, dayInt);

                dateObj1.setTodayDate(AcalObj.getMonthInteger(), AcalObj.getDayOfMonth(), AcalObj.getYear());

                // Get the events for the particular month from the
                // master list of events.
                calendarEventVectorObj = new CalendarEventVector(state.getCalendarFilter().filterEvents(
                        masterEventVectorObj.getEvents(getMonthTimeRange((CalendarUtil) AcalObj))));

                if (!calendarEventVectorObj.isEmpty()) {
                    AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay());

                    monthObj2 = calMonth(monthInt, (CalendarUtil) AcalObj, state, calendarEventVectorObj);

                    AcalObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay());

                    if (!calendarEventVectorObj.isEmpty())
                        arrayOfMonths.addElement(monthObj2);
                }
            }
            if (!arrayOfMonths.isEmpty())
                yearMap.put(Integer.valueOf(yearInt), arrayOfMonths.iterator());
        }
    }

    context.put("yearMap", yearMap);

    int row = 5;
    context.put("row", Integer.valueOf(row));
    calObj.setDay(stateYear, stateMonth, stateDay);

    // using session state stored year-month-day to replace saving calObj
    sstate.setAttribute(STATE_YEAR, Integer.valueOf(stateYear));
    sstate.setAttribute(STATE_MONTH, Integer.valueOf(stateMonth));
    sstate.setAttribute(STATE_DAY, Integer.valueOf(stateDay));

    state.setState("list");
    context.put("date", dateObj1);

    // output CalendarService and SiteService
    context.put("CalendarService", CalendarService.getInstance());
    context.put("SiteService", SiteService.getInstance());
    context.put("Context", ToolManager.getCurrentPlacement().getContext());

    buildMenu(portlet, context, runData, state,
            CalendarPermissions.allowCreateEvents(state.getPrimaryCalendarReference(),
                    state.getSelectedCalendarReference()),
            CalendarPermissions.allowDeleteEvent(state.getPrimaryCalendarReference(),
                    state.getSelectedCalendarReference(), state.getCalendarEventId()),
            CalendarPermissions.allowReviseEvents(state.getPrimaryCalendarReference(),
                    state.getSelectedCalendarReference(), state.getCalendarEventId()),
            CalendarPermissions.allowMergeCalendars(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowModifyCalendarProperties(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowImport(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowSubscribe(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowSubscribeThis(state.getPrimaryCalendarReference()));

    // added by zqian for toolbar
    context.put("allow_new", Boolean.valueOf(allowed));
    context.put("allow_delete", Boolean.valueOf(false));
    context.put("allow_revise", Boolean.valueOf(false));
    context.put("realDate", TimeService.newTime());

    context.put("selectedView", rb.getString("java.listeve"));
    context.put("tlang", rb);
    context.put("config", configProps);

    context.put("calendarFormattedText", new CalendarFormattedText());

    String currentUserId = UserDirectoryService.getCurrentUser().getId();
    boolean canViewEventAudience = SecurityService.unlock(currentUserId,
            org.sakaiproject.calendar.api.CalendarService.AUTH_VIEW_AUDIENCE,
            "/site/" + ToolManager.getCurrentPlacement().getContext());
    context.put("canViewAudience", !canViewEventAudience);

}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static Assertion createAssertion(String username, String role, String organization,
        String organizationId, String facilityType, String purposeOfUse, String xspaLocality,
        java.util.Vector permissions) {
    // assertion/*from  ww w . j  ava  2  s  .c o  m*/
    Assertion assertion = null;
    try {
        DefaultBootstrap.bootstrap();
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        SAMLObjectBuilder<Assertion> builder = (SAMLObjectBuilder<Assertion>) builderFactory
                .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);

        // Create the NameIdentifier
        SAMLObjectBuilder nameIdBuilder = (SAMLObjectBuilder) builderFactory
                .getBuilder(NameID.DEFAULT_ELEMENT_NAME);
        NameID nameId = (NameID) nameIdBuilder.buildObject();
        nameId.setValue(username);
        //nameId.setNameQualifier(strNameQualifier);
        nameId.setFormat(NameID.UNSPECIFIED);

        assertion = create(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);

        String assId = "_" + UUID.randomUUID();
        assertion.setID(assId);
        assertion.setVersion(SAMLVersion.VERSION_20);
        assertion.setIssueInstant(new org.joda.time.DateTime().minusHours(3));

        Subject subject = create(Subject.class, Subject.DEFAULT_ELEMENT_NAME);
        assertion.setSubject(subject);
        subject.setNameID(nameId);

        //Create and add Subject Confirmation
        SubjectConfirmation subjectConf = create(SubjectConfirmation.class,
                SubjectConfirmation.DEFAULT_ELEMENT_NAME);
        subjectConf.setMethod(SubjectConfirmation.METHOD_SENDER_VOUCHES);
        assertion.getSubject().getSubjectConfirmations().add(subjectConf);

        //Create and add conditions
        Conditions conditions = create(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
        org.joda.time.DateTime now = new org.joda.time.DateTime();
        conditions.setNotBefore(now.minusMinutes(1));
        conditions.setNotOnOrAfter(now.plusHours(2)); // According to Spec
        assertion.setConditions(conditions);

        //           AudienceRestriction ar = create(AudienceRestriction.class,AudienceRestriction.DEFAULT_ELEMENT_NAME);
        //           Audience aud = create(Audience.class,Audience.DEFAULT_ELEMENT_NAME);
        //           aud.setAudienceURI("aaa");

        //           conditions.s

        Issuer issuer = new IssuerBuilder().buildObject();
        issuer.setValue("urn:idp:countryB");
        issuer.setNameQualifier("urn:epsos:wp34:assertions");
        assertion.setIssuer(issuer);

        //Add and create the authentication statement
        AuthnStatement authStmt = create(AuthnStatement.class, AuthnStatement.DEFAULT_ELEMENT_NAME);
        authStmt.setAuthnInstant(now.minusHours(2));
        assertion.getAuthnStatements().add(authStmt);

        //Create and add AuthnContext
        AuthnContext ac = create(AuthnContext.class, AuthnContext.DEFAULT_ELEMENT_NAME);
        AuthnContextClassRef accr = create(AuthnContextClassRef.class,
                AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
        accr.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
        ac.setAuthnContextClassRef(accr);
        authStmt.setAuthnContext(ac);

        AttributeStatement attrStmt = create(AttributeStatement.class, AttributeStatement.DEFAULT_ELEMENT_NAME);

        // XSPA Subject
        Attribute attrPID = createAttribute(builderFactory, "XSPA subject",
                "urn:oasis:names:tc:xacml:1.0:subject:subject-id", username, "", "");
        attrStmt.getAttributes().add(attrPID);
        // XSPA Role        
        Attribute attrPID_1 = createAttribute(builderFactory, "XSPA role",
                "urn:oasis:names:tc:xacml:2.0:subject:role", role, "", "");
        attrStmt.getAttributes().add(attrPID_1);
        // HITSP Clinical Speciality
        /*        Attribute attrPID_2 = createAttribute(builderFactory,"HITSP Clinical Speciality",
         "urn:epsos:names:wp3.4:subject:clinical-speciality",role,"","");
                attrStmt.getAttributes().add(attrPID_2);
                */
        // XSPA Organization
        Attribute attrPID_3 = createAttribute(builderFactory, "XSPA Organization",
                "urn:oasis:names:tc:xspa:1.0:subject:organization", organization, "", "");
        attrStmt.getAttributes().add(attrPID_3);
        // XSPA Organization ID
        Attribute attrPID_4 = createAttribute(builderFactory, "XSPA Organization ID",
                "urn:oasis:names:tc:xspa:1.0:subject:organization-id", organizationId, "AA", "");
        attrStmt.getAttributes().add(attrPID_4);

        //           // On behalf of
        //           Attribute attrPID_4 = createAttribute(builderFactory,"OnBehalfOf",
        //         "urn:epsos:names:wp3.4:subject:on-behalf-of",organizationId,role,"");
        //         attrStmt.getAttributes().add(attrPID_4);

        // epSOS Healthcare Facility Type
        Attribute attrPID_5 = createAttribute(builderFactory, "epSOS Healthcare Facility Type",
                "urn:epsos:names:wp3.4:subject:healthcare-facility-type", facilityType, "", "");
        attrStmt.getAttributes().add(attrPID_5);
        // XSPA Purpose of Use
        Attribute attrPID_6 = createAttribute(builderFactory, "XSPA Purpose Of Use",
                "urn:oasis:names:tc:xspa:1.0:subject:purposeofuse", purposeOfUse, "", "");
        attrStmt.getAttributes().add(attrPID_6);
        // XSPA Locality
        Attribute attrPID_7 = createAttribute(builderFactory, "XSPA Locality",
                "urn:oasis:names:tc:xspa:1.0:environment:locality", xspaLocality, "", "");
        attrStmt.getAttributes().add(attrPID_7);
        // HL7 Permissions
        Attribute attrPID_8 = createAttribute(builderFactory, "Hl7 Permissions",
                "urn:oasis:names:tc:xspa:1.0:subject:hl7:permission");
        Iterator itr = permissions.iterator();
        while (itr.hasNext()) {
            attrPID_8 = AddAttributeValue(builderFactory, attrPID_8, itr.next().toString(), "", "");
        }
        attrStmt.getAttributes().add(attrPID_8);

        assertion.getStatements().add(attrStmt);

    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return assertion;
}

From source file:org.unitime.timetable.test.StudentSectioningTest.java

private static void testSectioning(Element studentElement, Element response, Session session) {
    try {//from  ww w.  jav  a  2s.com
        System.out.print("Request:");
        new XMLWriter(System.out, OutputFormat.createPrettyPrint()).write(studentElement);
    } catch (Exception e) {
    }
    Student student = new Student(Long.parseLong(studentElement.attributeValue("key")));
    sLog.info("  loading student " + student.getId());
    String courseNumbersMustBeUnique = ApplicationProperties.getProperty("tmtbl.courseNumber.unique", "true");

    StudentSctBBTest sbt = null;
    boolean commit = false;
    Vector messages = new Vector();

    if (studentElement.element("retrieveCourseRequests") != null) {
        loadStudent(session, student, messages);
        sbt = new StudentSctBBTest(student);
        for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
            Request request = (Request) e.next();
            if (request.getInitialAssignment() != null)
                request.assign(0, request.getInitialAssignment());
        }
        for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
            Request request = (Request) e.next();
            if (request instanceof FreeTimeRequest) {
                Enrollment enrollment = (Enrollment) request.values().get(0);
                if (sbt.conflictValues(enrollment).isEmpty())
                    request.assign(0, enrollment);
            }
        }
    }

    Element courseRequestsElement = studentElement.element("updateCourseRequests");
    if (courseRequestsElement == null) {
        sLog.warn("  No course requests for student " + student.getId());
    } else {
        long reqId = 0;
        int priority = 0;
        commit = "true".equals(courseRequestsElement.attributeValue("commit"));
        for (Iterator i = courseRequestsElement.elementIterator(); i.hasNext();) {
            Element requestElement = (Element) i.next();
            boolean alternative = "true".equals(requestElement.attributeValue("alternative"));
            if ("freeTime".equals(requestElement.getName())) {
                String days = requestElement.attributeValue("days");
                String startTime = requestElement.attributeValue("startTime");
                String length = requestElement.attributeValue("length");
                String endTime = requestElement.attributeValue("endTime");
                FreeTimeRequest ftRequest = new FreeTimeRequest(reqId++, priority++, alternative, student,
                        makeTime(session.getDefaultDatePattern(), days, startTime, endTime, length));
                sLog.info("    added " + ftRequest);
            } else if ("courseOffering".equals(requestElement.getName())) {
                String subjectArea = requestElement.attributeValue("subjectArea");
                String courseNumber = requestElement.attributeValue("courseNumber");
                boolean waitlist = "true".equals(requestElement.attributeValue("waitlist", "false"));
                Long timeStamp = (requestElement.attributeValue("timeStamp") == null ? null
                        : Long.parseLong(requestElement.attributeValue("timeStamp")));
                CourseOffering co = null;

                if (courseNumbersMustBeUnique.equalsIgnoreCase("true")) {
                    co = CourseOffering.findBySessionSubjAreaAbbvCourseNbr(session.getUniqueId(), subjectArea,
                            courseNumber);
                } else {
                    String title = requestElement.attributeValue("title");
                    co = CourseOffering.findBySessionSubjAreaAbbvCourseNbrTitle(session.getUniqueId(),
                            subjectArea, courseNumber, title);
                }
                if (co == null) {
                    sLog.warn("    Course " + subjectArea + " " + courseNumber + " not found.");
                    continue;
                }
                Vector courses = new Vector();
                courses.add(loadCourse(co, student.getId()));
                for (Iterator j = requestElement.elementIterator("alternative"); j.hasNext();) {
                    Element altElement = (Element) j.next();
                    String altSubjectArea = altElement.attributeValue("subjectArea");
                    String altCourseNumber = altElement.attributeValue("courseNumber");
                    CourseOffering aco = null;
                    if (courseNumbersMustBeUnique.equalsIgnoreCase("true")) {
                        aco = CourseOffering.findBySessionSubjAreaAbbvCourseNbr(session.getUniqueId(),
                                altSubjectArea, altCourseNumber);
                    } else {
                        String altTitle = altElement.attributeValue("title");
                        aco = CourseOffering.findBySessionSubjAreaAbbvCourseNbrTitle(session.getUniqueId(),
                                altSubjectArea, altCourseNumber, altTitle);
                    }
                    if (aco != null)
                        courses.add(loadCourse(aco, student.getId()));
                }
                CourseRequest cRequest = new CourseRequest(reqId++, priority++, alternative, student, courses,
                        waitlist, timeStamp);
                cRequest.values();
                sLog.info("    added " + cRequest);
            }
        }
        Element requestScheduleElement = studentElement.element("requestSchedule");
        if (requestScheduleElement != null) {
            for (Iterator i = requestScheduleElement.elementIterator("courseOffering"); i.hasNext();) {
                Element courseOfferingElement = (Element) i.next();
                String subjectArea = courseOfferingElement.attributeValue("subjectArea");
                String courseNumber = courseOfferingElement.attributeValue("courseNumber");
                CourseOffering co = null;
                if (courseNumbersMustBeUnique.equalsIgnoreCase("true")) {
                    co = CourseOffering.findBySessionSubjAreaAbbvCourseNbr(session.getUniqueId(), subjectArea,
                            courseNumber);
                } else {
                    String title = courseOfferingElement.attributeValue("title");
                    co = CourseOffering.findBySessionSubjAreaAbbvCourseNbrTitle(session.getUniqueId(),
                            subjectArea, courseNumber, title);
                }
                if (co == null) {
                    sLog.warn("    Course " + subjectArea + " " + courseNumber + " not found.");
                    continue;
                }
                for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
                    Request request = (Request) e.next();
                    if (request instanceof CourseRequest) {
                        CourseRequest courseRequest = (CourseRequest) request;
                        Course course = courseRequest.getCourse(co.getUniqueId().longValue());
                        Config config = null;
                        if (course == null)
                            continue;
                        Set assignedSections = new HashSet();
                        int nrClasses = 0;
                        for (Iterator j = courseOfferingElement.elementIterator("class"); j
                                .hasNext(); nrClasses++) {
                            Element classEl = (Element) j.next();
                            String assignmentId = classEl.attributeValue("assignmentId");
                            Section section = (assignmentId == null ? null
                                    : course.getOffering().getSection(Long.parseLong(assignmentId)));
                            if (section != null) {
                                assignedSections.add(section);
                                if (config == null)
                                    config = section.getSubpart().getConfig();
                            }
                            for (Iterator k = classEl.elementIterator("choice"); k.hasNext();) {
                                Element choiceEl = (Element) k.next();
                                Choice choice = new Choice(course.getOffering(), choiceEl.attributeValue("id"));
                                if ("select".equals(choiceEl.attributeValue("selection"))) {
                                    courseRequest.getSelectedChoices().add(choice);
                                    sLog.info("      add selection " + choice);
                                } else {
                                    courseRequest.getWaitlistedChoices().add(choice);
                                    sLog.info("      add waitlist " + choice);
                                }
                            }
                        }
                        if (nrClasses == assignedSections.size()) {
                            courseRequest
                                    .setInitialAssignment(new Enrollment(request, 0, config, assignedSections));
                            sLog.info("    initial assignment " + courseRequest.getInitialAssignment());
                        }
                    }
                }
            }
        } else {
            sLog.warn("  No schedule requests for student " + student.getId());
        }
        sLog.info("  sectioning student " + student.getId());
        sbt = new StudentSctBBTest(student);

        Model model = sbt.getSolution().getModel();
        messages.addAll(sbt.getMessages());
        sLog.info("  info: " + model.getInfo());

        if (commit)
            saveStudent(session, student, messages);
    }
    Element studentResponseElement = response.addElement("student");
    studentResponseElement.addAttribute("key", String.valueOf(student.getId()));
    Element ackResponseElement = studentResponseElement.addElement("acknowledgement");
    ackResponseElement.addAttribute("result", "ok");
    Element courseReqResponseElement = studentResponseElement.addElement("courseRequests");
    for (Iterator e = messages.iterator(); e.hasNext();) {
        StudentSctBBTest.Message message = (StudentSctBBTest.Message) e.next();
        ackResponseElement.addElement("message").addAttribute("type", message.getLevelString())
                .setText(message.getMessage());
    }
    for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
        Request request = (Request) e.next();
        Element reqElement = null;
        if (request instanceof FreeTimeRequest) {
            FreeTimeRequest ftRequest = (FreeTimeRequest) request;
            reqElement = courseReqResponseElement.addElement("freeTime");
            reqElement.addAttribute("days", dayCode2days(ftRequest.getTime().getDayCode()));
            reqElement.addAttribute("startTime", startSlot2startTime(ftRequest.getTime().getStartSlot()));
            reqElement.addAttribute("endTime", timeLocation2endTime(ftRequest.getTime()));
            reqElement.addAttribute("length",
                    String.valueOf(Constants.SLOT_LENGTH_MIN * ftRequest.getTime().getLength()));
            sLog.info("  added " + ftRequest);
        } else {
            CourseRequest courseRequest = (CourseRequest) request;
            reqElement = courseReqResponseElement.addElement("courseOffering");
            for (Iterator f = courseRequest.getCourses().iterator(); f.hasNext();) {
                Course course = (Course) f.next();
                Element element = (reqElement.attribute("subjectArea") == null ? reqElement
                        : reqElement.addElement("alternative"));
                element.addAttribute("subjectArea", course.getSubjectArea());
                element.addAttribute("courseNumber", course.getCourseNumber());
                CourseOffering co = CourseOffering.findByUniqueId(course.getId());
                element.addAttribute("title", (co.getTitle() != null ? co.getTitle() : ""));
            }
            reqElement.addAttribute("waitlist", courseRequest.isWaitlist() ? "true" : "false");
            if (courseRequest.getTimeStamp() != null)
                reqElement.addAttribute("timeStamp", courseRequest.getTimeStamp().toString());
            sLog.info("  added " + courseRequest);
        }
        if (request.isAlternative())
            reqElement.addAttribute("alternative", "true");
    }
    Comparator choiceComparator = new Comparator() {
        public int compare(Object o1, Object o2) {
            Choice c1 = (Choice) o1;
            Choice c2 = (Choice) o2;
            if (c1.getTime() == null) {
                if (c2.getTime() != null)
                    return -1;
            } else if (c2.getTime() == null)
                return 1;
            if (c1.getTime() != null) {
                int cmp = -Double.compare(c1.getTime().getDayCode(), c2.getTime().getDayCode());
                if (cmp != 0)
                    return cmp;
                cmp = Double.compare(c1.getTime().getStartSlot(), c2.getTime().getStartSlot());
                if (cmp != 0)
                    return cmp;
                cmp = c1.getTime().getDatePatternName().compareTo(c2.getTime().getDatePatternName());
                if (cmp != 0)
                    return cmp;
            }
            if (c1.getInstructorNames() == null) {
                if (c2.getInstructorNames() != null)
                    return -1;
            } else if (c2.getInstructorNames() == null)
                return 1;
            if (c1.getInstructorNames() != null) {
                int cmp = c1.getInstructorNames().compareTo(c2.getInstructorNames());
                if (cmp != 0)
                    return cmp;
            }
            return c1.getId().compareTo(c2.getId());
        }
    };
    boolean generateRandomAvailability = (student.getId() < 0);
    Element scheduleResponseElement = studentResponseElement.addElement("schedule");
    scheduleResponseElement.addAttribute("type", (commit ? "actual" : "proposed"));
    for (Iterator e = student.getRequests().iterator(); e.hasNext();) {
        Request request = (Request) e.next();
        if (request.getAssignment() == null) {
            sLog.info("    request " + request + " has no assignment");
            if (request instanceof CourseRequest && ((CourseRequest) request).isWaitlist()
                    && request.getStudent().canAssign(request)) {
                Element courseOfferingElement = scheduleResponseElement.addElement("courseOffering");
                Course course = (Course) ((CourseRequest) request).getCourses().get(0);
                courseOfferingElement.addAttribute("subjectArea", course.getSubjectArea());
                courseOfferingElement.addAttribute("courseNumber", course.getCourseNumber());
                CourseOffering co = CourseOffering.findByUniqueId(course.getId());
                courseOfferingElement.addAttribute("title", co.getTitle());
                courseOfferingElement.addAttribute("waitlist",
                        ((CourseRequest) request).isWaitlist() ? "true" : "false");
                if (((CourseRequest) request).getTimeStamp() != null)
                    courseOfferingElement.addAttribute("timeStamp",
                            ((CourseRequest) request).getTimeStamp().toString());
            }
            continue;
        }
        if (request instanceof FreeTimeRequest) {
            FreeTimeRequest ftRequest = (FreeTimeRequest) request;
            Element ftElement = scheduleResponseElement.addElement("freeTime");
            ftElement.addAttribute("days", dayCode2days(ftRequest.getTime().getDayCode()));
            ftElement.addAttribute("startTime", startSlot2startTime(ftRequest.getTime().getStartSlot()));
            ftElement.addAttribute("endTime", timeLocation2endTime(ftRequest.getTime()));
            ftElement.addAttribute("length",
                    String.valueOf(Constants.SLOT_LENGTH_MIN * ftRequest.getTime().getLength()));
            if (ftRequest.getTime() != null)
                ftElement.addAttribute("time",
                        ftRequest.getTime().getDayHeader() + " " + ftRequest.getTime().getStartTimeHeader()
                                + " - " + ftRequest.getTime().getEndTimeHeader());
            else
                ftElement.addAttribute("time", "Arr Hrs");
        } else {
            CourseRequest courseRequest = (CourseRequest) request;
            Element courseOfferingElement = scheduleResponseElement.addElement("courseOffering");
            Enrollment enrollment = (Enrollment) request.getAssignment();
            Set unusedInstructionalTypes = null;
            Offering offering = null;
            HashSet availableChoices = null;
            Vector assignments = new Vector(enrollment.getAssignments());
            Collections.sort(assignments, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Section s1 = (Section) o1;
                    Section s2 = (Section) o2;
                    return s1.getSubpart().compareTo(s2.getSubpart());
                }
            });
            for (Iterator i = assignments.iterator(); i.hasNext();) {
                Section section = (Section) i.next();
                if (courseOfferingElement.attribute("subjectArea") == null) {
                    Course course = enrollment.getCourse();
                    courseOfferingElement.addAttribute("subjectArea", course.getSubjectArea());
                    courseOfferingElement.addAttribute("courseNumber", course.getCourseNumber());
                    CourseOffering co = CourseOffering.findByUniqueId(course.getId());
                    courseOfferingElement.addAttribute("title", co.getTitle());
                }
                if (offering == null) {
                    offering = section.getSubpart().getConfig().getOffering();
                    if (generateRandomAvailability) {
                        availableChoices = generateAvailableChoices(offering, new Random(13031978l), 0.75);
                    } else {
                        availableChoices = new HashSet();
                        for (Iterator j = courseRequest.getAvaiableEnrollmentsSkipSameTime().iterator(); j
                                .hasNext();) {
                            Enrollment enr = (Enrollment) j.next();
                            for (Iterator k = enr.getAssignments().iterator(); k.hasNext();) {
                                Section s = (Section) k.next();
                                if (s.getLimit() > 0 && s.getPenalty() <= sAvailableThreshold)
                                    availableChoices.add(s.getChoice());
                            }
                        }
                    }
                }
                if (unusedInstructionalTypes == null)
                    unusedInstructionalTypes = section.getSubpart().getConfig().getOffering()
                            .getInstructionalTypes();
                unusedInstructionalTypes.remove(section.getSubpart().getInstructionalType());
                Element classElement = courseOfferingElement.addElement("class");
                classElement.addAttribute("id", section.getSubpart().getInstructionalType());
                classElement.addAttribute("assignmentId", String.valueOf(section.getId()));
                if (section.getSubpart().getParent() != null)
                    classElement.addAttribute("parent",
                            section.getSubpart().getParent().getInstructionalType());
                classElement.addAttribute("name", section.getSubpart().getName());
                if (section.getTime() != null) {
                    classElement.addAttribute("days", dayCode2days(section.getTime().getDayCode()));
                    classElement.addAttribute("startTime",
                            startSlot2startTime(section.getTime().getStartSlot()));
                    classElement.addAttribute("endTime", timeLocation2endTime(section.getTime()));
                    //classElement.addAttribute("length", String.valueOf(Constants.SLOT_LENGTH_MIN*section.getTime().getLength()));
                    if (section.getTime().getDatePatternName() != null)
                        classElement.addAttribute("date", section.getTime().getDatePatternName());
                    classElement.addAttribute("time",
                            section.getTime().getDayHeader() + " " + section.getTime().getStartTimeHeader()
                                    + " - " + section.getTime().getEndTimeHeader());
                } else
                    classElement.addAttribute("time", "Arr Hrs");
                if (section.getNrRooms() > 0) {
                    String location = "";
                    for (Iterator f = section.getRooms().iterator(); f.hasNext();) {
                        RoomLocation rl = (RoomLocation) f.next();
                        location += rl.getName();
                        if (f.hasNext())
                            location += ",";
                    }
                    classElement.addAttribute("location", location);
                }
                if (section.getChoice().getInstructorNames() != null)
                    classElement.addAttribute("instructor", section.getChoice().getInstructorNames());
                Vector choices = new Vector(section.getSubpart().getConfig().getOffering()
                        .getChoices(section.getSubpart().getInstructionalType()));
                Collections.sort(choices, choiceComparator);
                for (Iterator f = choices.iterator(); f.hasNext();) {
                    Choice choice = (Choice) f.next();
                    Element choiceEl = classElement.addElement("choice");
                    choiceEl.addAttribute("id", choice.getId());
                    choiceEl.addAttribute("available", (availableChoices == null ? "true"
                            : availableChoices.contains(choice) ? "true" : "false"));
                    if (choice.getTime() != null) {
                        choiceEl.addAttribute("days", dayCode2days(choice.getTime().getDayCode()));
                        choiceEl.addAttribute("startTime",
                                startSlot2startTime(choice.getTime().getStartSlot()));
                        choiceEl.addAttribute("endTime", timeLocation2endTime(choice.getTime()));
                        if (choice.getTime().getDatePatternName() != null)
                            choiceEl.addAttribute("date", choice.getTime().getDatePatternName());
                        choiceEl.addAttribute("time",
                                choice.getTime().getDayHeader() + " " + choice.getTime().getStartTimeHeader()
                                        + " - " + choice.getTime().getEndTimeHeader());
                    } else
                        choiceEl.addAttribute("time", "Arr Hrs");
                    if (choice.equals(section.getChoice()))
                        choiceEl.addAttribute("available", "true");
                    if (courseRequest.getSelectedChoices().isEmpty() && choice.equals(section.getChoice())) {
                        choiceEl.addAttribute("selection", "select");
                    } else if (courseRequest.getSelectedChoices().contains(choice)) {
                        choiceEl.addAttribute("selection", "select");
                        if (generateRandomAvailability)
                            choiceEl.addAttribute("available", "true");
                    } else if (courseRequest.getWaitlistedChoices().contains(choice)) {
                        choiceEl.addAttribute("selection", "wait");
                        if (generateRandomAvailability)
                            choiceEl.addAttribute("available", "false");
                    }
                    if (choice.getInstructorNames() != null)
                        choiceEl.addAttribute("instructor", choice.getInstructorNames());
                    exportDependencies(choiceEl, choice, choice.getParentSections());
                }
            }
            if (unusedInstructionalTypes != null) {
                for (Iterator i = unusedInstructionalTypes.iterator(); i.hasNext();) {
                    String unusedInstructionalType = (String) i.next();
                    Element classElement = courseOfferingElement.addElement("class");
                    classElement.addAttribute("id", unusedInstructionalType);
                    classElement.addAttribute("name",
                            ((Subpart) offering.getSubparts(unusedInstructionalType).iterator().next())
                                    .getName());
                    Vector choices = new Vector(offering.getChoices(unusedInstructionalType));
                    Collections.sort(choices, choiceComparator);
                    for (Iterator f = choices.iterator(); f.hasNext();) {
                        Choice choice = (Choice) f.next();
                        Element choiceEl = classElement.addElement("choice");
                        choiceEl.addAttribute("id", choice.getId());
                        choiceEl.addAttribute("available", (availableChoices == null ? "true"
                                : availableChoices.contains(choice) ? "true" : "false"));
                        if (choice.getTime() != null) {
                            choiceEl.addAttribute("days", dayCode2days(choice.getTime().getDayCode()));
                            choiceEl.addAttribute("startTime",
                                    startSlot2startTime(choice.getTime().getStartSlot()));
                            choiceEl.addAttribute("endTime", timeLocation2endTime(choice.getTime()));
                            if (choice.getTime().getDatePatternName() != null)
                                choiceEl.addAttribute("date", choice.getTime().getDatePatternName());
                            choiceEl.addAttribute("time",
                                    choice.getTime().getDayHeader() + " "
                                            + choice.getTime().getStartTimeHeader() + " - "
                                            + choice.getTime().getEndTimeHeader());
                        } else
                            choiceEl.addAttribute("time", "Arr Hrs");
                        if (courseRequest.getWaitlistedChoices().contains(choice))
                            choiceEl.addAttribute("selection", "wait");
                        if (choice.getInstructorNames() != null)
                            choiceEl.addAttribute("instructor", choice.getInstructorNames());
                        exportDependencies(choiceEl, choice, choice.getParentSections());
                    }
                }
            }
        }
        sLog.info("    added " + request.getAssignment());
    }
    /*
    try {
    System.out.print("Response:");
    new XMLWriter(System.out,OutputFormat.createPrettyPrint()).write(studentResponseElement);
    } catch (Exception e) {}
    */
}

From source file:sos.scheduler.cron.CronConverter.java

private void createRunTime(final Matcher pcronRegExMatcher, final Element runTimeElement) throws Exception {
    try {/*from   w  w  w . j a  va 2 s . c  om*/
        if (!pcronRegExMatcher.matches()) {
            throw new JobSchedulerException("Fail to parse cron line \"" + strCronLine + "\", regexp is "
                    + pcronRegExMatcher.toString());
        }

        String minutes = pcronRegExMatcher.group(1);
        String hours = pcronRegExMatcher.group(2);
        String days = pcronRegExMatcher.group(3);
        String months = pcronRegExMatcher.group(4);
        String weekdays = pcronRegExMatcher.group(5);

        if (minutes.equals("@reboot")) {
            runTimeElement.setAttribute("once", "yes");
            return;
        }
        Vector<Element> childElements = new Vector<Element>();
        Element periodElement = runTimeElement.getOwnerDocument().createElement("period");

        logger.debug("processing hours [" + hours + "] and minutes [" + minutes + "]");
        if (minutes.startsWith("*")) {
            if (minutes.equalsIgnoreCase("*")) {
                // every minute
                periodElement.setAttribute("repeat", "60");
            } else { // repeat interval is given
                String repeat = minutes.substring(2);
                repeat = formatTwoDigits(repeat);
                periodElement.setAttribute("repeat", "00:" + repeat);
            }
            if (hours.startsWith("*")) {
                if (!hours.equalsIgnoreCase("*")) {
                    // repeat interval is given for hours and minutes. Doesn't make sense.
                    // e.g. */2 */3 every 3 hours repeat every 2 minutes
                    throw new JobSchedulerException(
                            "Combination of minutes and hours not supported: " + minutes + " " + hours);
                }
                // every hour: keep interval from minutes
                childElements.add(periodElement);
            } else {
                logger.debug("Found specific hours, creating periods with begin and end.");
                String[] hourArray = hours.split(",");
                for (int i = 0; i < hourArray.length; i++) {
                    String currentHour = hourArray[i];
                    if (currentHour.indexOf("/") != -1) {
                        String[] additionalHours = getArrayFromColumn(currentHour);
                        hourArray = combineArrays(hourArray, additionalHours);
                        continue;
                    }
                    String[] currentHourArray = currentHour.split("-");
                    Element currentPeriodElement = (Element) periodElement.cloneNode(true);
                    String beginHour = currentHourArray[0];

                    int iEndHour = (Integer.parseInt(beginHour) + 1) % 24;
                    // workaround, bis endhour am nchsten Tag erlaubt
                    if (iEndHour == 0)
                        iEndHour = 24;
                    String endHour = "" + iEndHour;
                    if (currentHourArray.length > 1)
                        endHour = currentHourArray[1];
                    beginHour = formatTwoDigits(beginHour);
                    endHour = formatTwoDigits(endHour);
                    currentPeriodElement.setAttribute("begin", beginHour + ":00");
                    currentPeriodElement.setAttribute("end", endHour + ":00");
                    childElements.add(currentPeriodElement);
                }
            }
        } // end if  minutes.startsWith("*")
        else { // one or more minutes are fixed
            String[] minutesArray = getArrayFromColumn(minutes);
            for (String element : minutesArray) {
                Element currentPeriodElement = (Element) periodElement.cloneNode(true);
                String currentMinute = element;

                currentMinute = formatTwoDigits(currentMinute);
                if (hours.startsWith("*")) {
                    currentPeriodElement.setAttribute("absolute_repeat", "01:00");
                    usedNewRunTime = true;
                    if (!hours.equalsIgnoreCase("*")) {// repeat interval is given for hours
                        String repeat = hours.substring(2);
                        repeat = formatTwoDigits(repeat);
                        currentPeriodElement.setAttribute("absolute_repeat", repeat + ":00");
                    }
                    currentPeriodElement.setAttribute("begin", "00:" + currentMinute);
                    childElements.add(currentPeriodElement);
                } else { //fixed hour(s) is set
                    String[] hourArray = hours.split(",");
                    for (String element2 : hourArray) {
                        currentPeriodElement = (Element) periodElement.cloneNode(true);
                        String currentHour = element2;
                        if (currentHour.indexOf("-") == -1) {
                            // fixed hour and fixed minute --> create single_start
                            currentHour = formatTwoDigits(currentHour);
                            currentPeriodElement.setAttribute("single_start",
                                    currentHour + ":" + currentMinute);
                        } else {
                            // range of hours is set, create begin and end attributes
                            String[] currentHourArray = currentHour.split("[-/]");
                            int beginHour = Integer.parseInt(currentHourArray[0]);
                            int endHour = Integer.parseInt(currentHourArray[1]);
                            int beginMinute = Integer.parseInt(currentMinute);
                            int endMinute = beginMinute + 1;
                            // workaround, bis endhour am nchsten Tag erlaubt
                            endMinute = beginMinute;
                            if (endMinute == 60) {
                                endMinute = 0;
                                endHour = endHour + 1;
                            }
                            endHour = endHour % 24;
                            // workaround, bis endhour am nchsten Tag erlaubt
                            if (endHour == 0)
                                endHour = 24;
                            String stepSize = "1";
                            if (currentHourArray.length == 3) {
                                stepSize = formatTwoDigits(currentHourArray[2]);
                            }
                            currentPeriodElement.setAttribute("absolute_repeat", stepSize + ":00");
                            usedNewRunTime = true;
                            currentPeriodElement.setAttribute("begin",
                                    formatTwoDigits(beginHour) + ":" + formatTwoDigits(beginMinute));
                            currentPeriodElement.setAttribute("end",
                                    formatTwoDigits(endHour) + ":" + formatTwoDigits(endMinute));
                        }
                        childElements.add(currentPeriodElement);
                    }
                }
            }

        }

        logger.debug("processing days [" + days + "]");
        boolean monthDaysSet = false;
        if (days.startsWith("*")) {
            if (days.equals("*")) {
                // every day - do nothing, just keep periods
            } else {
                // repeat interval is given for days
                // this is not possible in the JobScheduler but can be poorly emulated
                Element monthDaysElement = runTimeElement.getOwnerDocument().createElement("monthdays");
                String repeat = days.substring(2);
                int iRepeat = Integer.parseInt(repeat);
                // use only 30 days
                for (int i = 1; i <= 30; i = i + iRepeat) {
                    String day = "" + i;
                    addDay(day, monthDaysElement, childElements);
                }
                childElements.clear();
                childElements.add(monthDaysElement);
                monthDaysSet = true;
            }
        } else {
            Element monthDaysElement = runTimeElement.getOwnerDocument().createElement("monthdays");
            String[] daysArray = getArrayFromColumn(days);
            for (String day : daysArray) {
                addDay(day, monthDaysElement, childElements);
            }
            childElements.clear();
            childElements.add(monthDaysElement);
            monthDaysSet = true;
        }

        if (!weekdays.equals("*") && monthDaysSet) {
            logger.info("Weekdays will not be processed as days are already set in current line.");
        } else {
            logger.debug("processing weekdays [" + weekdays + "]");
            weekdays = replaceDayNames(weekdays);
            if (weekdays.startsWith("*/"))
                throw new JobSchedulerException("Repeat intervals for the weekdays column [" + weekdays
                        + "] are not supported. Please use the days column.");
            if (weekdays.equals("*")) {
                // all weekdays, do nothing
            } else {
                Element weekDaysElement = runTimeElement.getOwnerDocument().createElement("weekdays");
                String[] daysArray = getArrayFromColumn(weekdays);
                for (String day : daysArray) {
                    addDay(day, weekDaysElement, childElements);
                }
                childElements.clear();
                childElements.add(weekDaysElement);
            }
        }

        logger.debug("processing months [" + months + "]");
        if (months.startsWith("*")) {
            if (months.equals("*")) {
                // every month - do nothing
            } else {
                months = replaceMonthNames(months);
                // repeat interval is given for months
                // this is not possible in the JobScheduler but can be poorly emulated
                Vector<Element> newChildElements = new Vector<Element>();
                String repeat = months.substring(2);
                int iRepeat = Integer.parseInt(repeat);

                for (int i = 1; i <= 12; i = i + iRepeat) {
                    String month = "" + i;
                    Element monthElement = runTimeElement.getOwnerDocument().createElement("month");
                    usedNewRunTime = true;
                    monthElement.setAttribute("month", month);
                    Iterator<Element> iter = childElements.iterator();
                    while (iter.hasNext()) {
                        Element child = iter.next();
                        monthElement.appendChild(child.cloneNode(true));
                    }
                    newChildElements.add(monthElement);
                }
                childElements = newChildElements;
            }
        } else {// list of months is given
            Vector<Element> newChildElements = new Vector<Element>();
            String[] monthArray = getArrayFromColumn(months);
            for (String month : monthArray) {
                Element monthElement = runTimeElement.getOwnerDocument().createElement("month");
                usedNewRunTime = true;
                monthElement.setAttribute("month", month);
                Iterator<Element> iter = childElements.iterator();
                while (iter.hasNext()) {
                    Element child = iter.next();
                    monthElement.appendChild(child.cloneNode(true));
                }
                newChildElements.add(monthElement);
            }
            childElements = newChildElements;
        }

        // add topmost child elements to run_time element
        Iterator<Element> iter = childElements.iterator();
        while (iter.hasNext()) {
            Element someElement = iter.next();
            runTimeElement.appendChild(someElement);
        }
    } catch (Exception e) {
        throw new JobSchedulerException("Error creating run time: " + e, e);
    }

}