Example usage for java.util Vector isEmpty

List of usage examples for java.util Vector isEmpty

Introduction

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

Prototype

public synchronized boolean isEmpty() 

Source Link

Document

Tests if this vector has no components.

Usage

From source file:JavaViewer.java

/**
 * Event.detail line start offset (input) Event.text line text (input)
 * LineStyleEvent.styles Enumeration of StyleRanges, need to be in order.
 * (output) LineStyleEvent.background line background color (output)
 *///from  w  w w.  jav a  2 s  .  co m
public void lineGetStyle(LineStyleEvent event) {
    Vector styles = new Vector();
    int token;
    StyleRange lastStyle;
    // If the line is part of a block comment, create one style for the
    // entire line.
    if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) {
        styles.addElement(new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null));
        event.styles = new StyleRange[styles.size()];
        styles.copyInto(event.styles);
        return;
    }
    Color defaultFgColor = ((Control) event.widget).getForeground();
    scanner.setRange(event.lineText);
    token = scanner.nextToken();
    while (token != EOF) {
        if (token == OTHER) {
            // do nothing for non-colored tokens
        } else if (token != WHITE) {
            Color color = getColor(token);
            // Only create a style if the token color is different than the
            // widget's default foreground color and the token's style is
            // not
            // bold. Keywords are bolded.
            if ((!color.equals(defaultFgColor)) || (token == KEY)) {
                StyleRange style = new StyleRange(scanner.getStartOffset() + event.lineOffset,
                        scanner.getLength(), color, null);
                if (token == KEY) {
                    style.fontStyle = SWT.BOLD;
                }
                if (styles.isEmpty()) {
                    styles.addElement(style);
                } else {
                    // Merge similar styles. Doing so will improve
                    // performance.
                    lastStyle = (StyleRange) styles.lastElement();
                    if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) {
                        lastStyle.length += style.length;
                    } else {
                        styles.addElement(style);
                    }
                }
            }
        } else if ((!styles.isEmpty())
                && ((lastStyle = (StyleRange) styles.lastElement()).fontStyle == SWT.BOLD)) {
            int start = scanner.getStartOffset() + event.lineOffset;
            lastStyle = (StyleRange) styles.lastElement();
            // A font style of SWT.BOLD implies that the last style
            // represents a java keyword.
            if (lastStyle.start + lastStyle.length == start) {
                // Have the white space take on the style before it to
                // minimize the number of style ranges created and the
                // number of font style changes during rendering.
                lastStyle.length += scanner.getLength();
            }
        }
        token = scanner.nextToken();
    }
    event.styles = new StyleRange[styles.size()];
    styles.copyInto(event.styles);
}

From source file:org.apache.axis.message.MessageElement.java

protected MessageElement findElement(Vector vec, String namespace, String localPart) {
    if (vec.isEmpty()) {
        return null;
    }/* ww w  .j  av a  2  s .  c  o m*/

    QName qname = new QName(namespace, localPart);
    Enumeration e = vec.elements();
    MessageElement element;
    while (e.hasMoreElements()) {
        element = (MessageElement) e.nextElement();
        if (element.getQName().equals(qname)) {
            return element;
        }
    }

    return null;
}

From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java

/**
 * This method using GridFTP Client returns directory list of stageOut directory 
 * and sub directories.//from   w  ww. j  a v a2s . co  m
 * @param fullDirname
 * @param credential
 * @return
 */
private FileInformation[] getDirectoryListing(String fullDirname, Object credential) {
    GridFTPClient gridStore = null;
    FileInformation[] fileDetails = new FileInformation[0];
    try {
        gridStore = new GridFTPClient(gridAccess.getRepoHostName(), gridAccess.getRepoHostFTPPort());
        gridStore.authenticate((GSSCredential) credential); //authenticating
        gridStore.setDataChannelAuthentication(DataChannelAuthentication.SELF);
        gridStore.setDataChannelProtection(GridFTPSession.PROTECTION_SAFE);
        logger.debug("Change to Grid StageOut dir:" + fullDirname);
        gridStore.changeDir(fullDirname);
        logger.debug("List files in StageOut dir:" + gridStore.getCurrentDir());
        gridStore.setType(GridFTPSession.TYPE_ASCII);
        gridStore.setPassive();
        gridStore.setLocalActive();

        Vector list = gridStore.list("*");

        if (list != null && !(list.isEmpty())) {
            fileDetails = new FileInformation[list.size()];
            for (int i = list.size() - 1; i >= 0; i--) {
                FileInfo fInfo = (FileInfo) list.get(i);
                fileDetails[i] = new FileInformation(fInfo.getName(), fInfo.getSize(), fullDirname,
                        fInfo.isDirectory());
            }
        }
    } catch (ServerException e) {
        logger.error("GridFTP ServerException: " + e.getMessage());
    } catch (IOException e) {
        logger.error("GridFTP IOException: " + e.getMessage());
    } catch (Exception e) {
        logger.error("GridFTP Exception: " + e.getMessage());
    } finally {
        try {
            if (gridStore != null)
                gridStore.close();
        } catch (Exception e) {
            logger.error("GridFTP Exception: " + e.getMessage());
        }
    }
    return fileDetails;
}

From source file:tkwatch.Utilities.java

/**
 * Finds the value of the named element, if any, in an XML string. Adapted
 * from Vohra and Vohra, <i>Pro XML Development with Java Technology</i>, p.
 * 47.//w ww . j  av a2s. c om
 * 
 * @param desiredElementName
 *            The name of the element to search for in the XML string.
 * @param xmlString
 *            The XML string to search for an account number.
 * 
 * @return Returns the element value(s) as formatted in the incoming string
 *         (if found) as a <code>Vector<String></code>, <code>null</code>
 *         otherwise.
 */
public static final Vector<String> getValueFromXml(final String desiredElementName, final String xmlString) {
    Vector<String> elementValue = new Vector<String>();
    String elementValueText = null;
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    try {
        String elementName = "";
        StringReader stringReader = new StringReader(xmlString);
        XMLStreamReader reader = inputFactory.createXMLStreamReader(stringReader);
        while (reader.hasNext()) {
            int eventType = reader.getEventType();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getAttributeValue(0);
                    System.out.println("START_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getElementText();
                    System.out.println("ATTRIBUTE case, element name is " + elementName + ", element value is "
                            + elementValueText);
                    elementValue.add(elementValueText);
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    System.out.println("END_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            default:
                elementName = reader.getLocalName();
                if (elementName != null) {
                    if (elementName.equals(desiredElementName)) {
                        System.out.println("default case, element name is " + elementName);
                    }
                }
                break;
            }
            reader.next();
        }
    } catch (XMLStreamException e) {
        TradekingException.handleException(e);
    }
    return (elementValue.isEmpty() ? null : elementValue);
}

From source file:org.ecoinformatics.seek.datasource.eml.eml2.Eml200DataSource.java

public void preview() {

    String displayText = "PREVIEW NOT IMPLEMENTED FOR THIS ACTOR";
    JFrame frame = new JFrame(this.getName() + " Preview");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JScrollPane scrollPane = null;
    JTable jtable = null;/*from   w ww.  ja v  a 2s.  co m*/

    try {

        // set everything up (datawise)
        this.initialize();

        // check the entity - different displays for different formats
        // Compressed file
        if (this._selectedTableEntity.getHasGZipDataFile() || this._selectedTableEntity.getHasTarDataFile()
                || this._selectedTableEntity.getHasZipDataFile()) {
            displayText = "Selected entity is a compressed file.  \n"
                    + "Preview not implemented for output format: " + this.dataOutputFormat.getExpression();
            if (this._dataOutputFormat instanceof Eml200DataOutputFormatUnzippedFileName) {
                Eml200DataOutputFormatUnzippedFileName temp = (Eml200DataOutputFormatUnzippedFileName) this._dataOutputFormat;
                displayText = "Files: \n";
                for (int i = 0; i < temp.getTargetFilePathInZip().length; i++) {
                    displayText += temp.getTargetFilePathInZip()[i] + "\n";
                }
            }

        }
        // SPATIALRASTERENTITY or SPATIALVECTORENTITY are "image entities"
        // as far as the parser is concerned
        else if (this._selectedTableEntity.getIsImageEntity()) {
            // use the content of the cache file
            displayText = new String(this.getSelectedCachedDataItem().getData());
        }
        // TABLEENTITY
        else {
            // holds the rows for the table on disk with some in memory
            String vectorTempDir = DotKeplerManager.getInstance().getCacheDirString();
            // + "vector"
            // + File.separator;
            PersistentVector rowData = new PersistentVector(vectorTempDir);

            // go through the rows and add them to the persistent vector
            // model
            Vector row = this.gotRowVectorFromSource();
            while (!row.isEmpty()) {
                rowData.addElement(row);
                row = this.gotRowVectorFromSource();
            }
            // the column headers for the table
            Vector columns = this.getColumns();

            /*
             * with java 6, there is a more built-in sorting mechanism that
             * does not require the custom table sorter class
             */
            TableModel tableModel = new PersistentTableModel(rowData, columns);
            TableSorter tableSorter = new TableSorter(tableModel);
            jtable = new JTable(tableSorter) {
                // make this table read-only by overriding the default
                // implementation
                public boolean isCellEditable(int row, int col) {
                    return false;
                }
            };
            // sets up the listeners for sorting and such
            tableSorter.setTableHeader(jtable.getTableHeader());
            // set up the listener to trash persisted data when done
            frame.addWindowListener(new PersistentTableModelWindowListener((PersistentTableModel) tableModel));
        }
    } catch (Exception e) {
        displayText = "Problem encountered while generating preview: \n" + e.getMessage();
        log.error(displayText);
        e.printStackTrace();
    }

    // make sure there is a jtable, otherwise show just a text version of
    // the data
    if (jtable != null) {
        jtable.setVisible(true);
        // jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollPane = new JScrollPane(jtable);
    } else {
        JTextArea textArea = new JTextArea();
        textArea.setColumns(80);
        textArea.setText(displayText);
        textArea.setVisible(true);
        scrollPane = new JScrollPane(textArea);
    }
    scrollPane.setVisible(true);
    panel.setOpaque(true);
    panel.add(scrollPane, BorderLayout.CENTER);
    frame.setContentPane(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

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

private static void loadStudent(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;//from w w w  . jav  a 2 s .  c o m
    }

    int priority = 0;
    for (Iterator i = new TreeSet(s.getCourseDemands()).iterator(); i.hasNext();) {
        CourseDemand cd = (CourseDemand) i.next();
        Request request = null;
        if (cd.getFreeTime() != null) {
            request = new FreeTimeRequest(cd.getUniqueId().longValue(), priority++,
                    cd.isAlternative().booleanValue(), student,
                    new TimeLocation(cd.getFreeTime().getDayCode().intValue(),
                            cd.getFreeTime().getStartSlot().intValue(), cd.getFreeTime().getLength().intValue(),
                            0, 0, s.getSession().getDefaultDatePattern().getUniqueId(),
                            s.getSession().getDefaultDatePattern().getName(),
                            s.getSession().getDefaultDatePattern().getPatternBitSet(),
                            cd.getFreeTime().getCategory().intValue()));
            sLog.info("  -- added request " + request);
        } else if (!cd.getCourseRequests().isEmpty()) {
            Vector courses = new Vector();
            HashSet wlChoices = new HashSet();
            HashSet selChoices = new HashSet();
            HashSet assignedSections = new HashSet();
            Config assignedConfig = null;
            for (Iterator j = new TreeSet(cd.getCourseRequests()).iterator(); j.hasNext();) {
                org.unitime.timetable.model.CourseRequest cr = (org.unitime.timetable.model.CourseRequest) j
                        .next();
                Course course = loadCourse(cr.getCourseOffering(), student.getId());
                courses.addElement(course);
                for (Iterator k = cr.getClassWaitLists().iterator(); k.hasNext();) {
                    ClassWaitList cwl = (ClassWaitList) k.next();
                    Section section = course.getOffering().getSection(cwl.getClazz().getUniqueId().longValue());
                    if (section != null) {
                        if (cwl.getType().equals(ClassWaitList.TYPE_SELECTION))
                            selChoices.add(section.getChoice());
                        else if (cwl.getType().equals(ClassWaitList.TYPE_WAITLIST))
                            wlChoices.add(section.getChoice());
                    }
                }
                if (assignedConfig == null) {
                    for (Iterator k = cr.getClassEnrollments().iterator(); k.hasNext();) {
                        StudentClassEnrollment sce = (StudentClassEnrollment) k.next();
                        Section section = course.getOffering()
                                .getSection(sce.getClazz().getUniqueId().longValue());
                        if (section != null) {
                            assignedSections.add(section);
                            assignedConfig = section.getSubpart().getConfig();
                        }
                    }
                }
            }
            if (courses.isEmpty())
                continue;
            request = new CourseRequest(cd.getUniqueId().longValue(), priority++,
                    cd.isAlternative().booleanValue(), student, courses, cd.isWaitlist(),
                    cd.getTimestamp().getTime());
            ((CourseRequest) request).getWaitlistedChoices().addAll(wlChoices);
            ((CourseRequest) request).getSelectedChoices().addAll(selChoices);
            if (assignedConfig != null && assignedSections.size() == assignedConfig.getSubparts().size()) {
                Enrollment enrollment = new Enrollment(request, 0, assignedConfig, assignedSections);
                request.setInitialAssignment(enrollment);
            }
            sLog.info("  -- added request " + request);
        } else {
            sLog.warn("  -- course demand " + cd.getUniqueId() + " has no course requests");
        }
        if (request != null) {
            for (Iterator k = new TreeSet(cd.getEnrollmentMessages()).iterator(); k.hasNext();) {
                StudentEnrollmentMessage m = (StudentEnrollmentMessage) k.next();
                messages.add(new StudentSctBBTest.Message(m.getLevel().intValue(), request, m.getMessage()));
            }
        }
    }
}

From source file:org.unitime.timetable.solver.course.ui.ClassInfoModel.java

public String getRoomTable() {
    try {/* w ww.  j a  v a  2 s. co  m*/
        Vector<ClassRoomInfo> rooms = getRooms();
        ClassAssignment ClassAssignment = (iChange == null ? null : iChange.getCurrent(iClass));
        Collection<ClassRoomInfo> assigned = (ClassAssignment != null ? ClassAssignment.getRooms()
                : isClassAssigned() ? getClassAssignment().getRooms() : null);
        Collection<ClassRoomInfo> original = (getClassOldAssignment() != null
                ? getClassOldAssignment().getRooms()
                : null);
        if (rooms == null || rooms.isEmpty())
            return "";
        Collections.sort(rooms, new Comparator<ClassRoomInfo>() {
            public int compare(ClassRoomInfo r1, ClassRoomInfo r2) {
                int cmp = 0;
                if (ClassInfoForm.sRoomOrdNameAsc.equals(iForm.getRoomOrder())) {
                    cmp = r1.getName().compareTo(r2.getName());
                } else if (ClassInfoForm.sRoomOrdNameDesc.equals(iForm.getRoomOrder())) {
                    cmp = -r1.getName().compareTo(r2.getName());
                } else if (ClassInfoForm.sRoomOrdSizeAsc.equals(iForm.getRoomOrder())) {
                    cmp = Double.compare(r1.getCapacity(), r2.getCapacity());
                } else if (ClassInfoForm.sRoomOrdSizeDesc.equals(iForm.getRoomOrder())) {
                    cmp = -Double.compare(r1.getCapacity(), r2.getCapacity());
                } else {
                    cmp = r1.getName().compareTo(r2.getName());
                }
                if (cmp != 0)
                    return cmp;
                cmp = r1.getName().compareTo(r2.getName());
                ;
                if (cmp != 0)
                    return cmp;
                return r1.getLocationId().compareTo(r2.getLocationId());
            }
        });
        String ret = "";
        ret += "<script language='javascript'>";
        ret += "function roomOver(source, id) { ";
        ret += "    document.getElementById('r'+id).style.backgroundColor='rgb(223,231,242)';";
        ret += "    document.getElementById('c'+id).style.backgroundColor='rgb(223,231,242)';";
        ret += "    source.style.cursor='hand';source.style.cursor='pointer';";
        ret += "}";
        ret += "var sCap = -1;";
        ret += "var sRooms = '";
        if (assigned != null && assigned.size() > 0) {
            for (ClassRoomInfo room : assigned) {
                ret += ":" + room.getLocationId() + "@" + room.getCapacity();
            }
        }
        ret += "';";
        ret += "var sNrRooms = " + (assigned != null ? assigned.size() : 0) + ";";
        ret += "function roomSelected(id) {";
        ret += "    return sRooms.indexOf(':'+id+'@')>=0;";
        ret += "}";
        ret += "function roomOut(id) { ";
        ret += "    var bg = 'transparent';";
        ret += "    if (roomSelected(id)) bg='rgb(168,187,225)';";
        ret += "    document.getElementById('r'+id).style.backgroundColor=bg;";
        ret += "    document.getElementById('c'+id).style.backgroundColor=bg;";
        ret += "}";
        ret += "function roomClick(source, id, cap) { ";
        ret += "    if (sCap<0) {";
        ret += "        sCap = 0; sRooms=''; sNrRooms=0;";
        if (assigned != null && assigned.size() > 0) {
            for (ClassRoomInfo room : assigned)
                ret += "        roomOut(" + room.getLocationId() + ");";
        }
        ret += "    }";
        ret += "    var i = sRooms.indexOf(':'+id+'@');";
        ret += "    if (i>=0) {";
        ret += "        var j = sRooms.indexOf(':',i+1);";
        ret += "        sRooms = sRooms.substring(0, i)+(j>=0?sRooms.substring(j):'');";
        ret += "        sCap -= cap; sNrRooms--;";
        ret += "    } else {";
        ret += "        sRooms = sRooms + ':' + id + '@' + cap;";
        ret += "        sCap += cap; sNrRooms++;";
        ret += "        if (sNrRooms>" + getClazz().getNumberOfRooms() + ") {";
        ret += "            var fid = sRooms.substring(1, sRooms.indexOf('@'));";
        ret += "            var fcap = sRooms.substring(sRooms.indexOf('@')+1, sRooms.indexOf(':',1));";
        ret += "            sRooms = sRooms.substring(sRooms.indexOf(':',1));";
        ret += "            sCap -= fcap; sNrRooms--; roomOut(fid);";
        ret += "        };";
        ret += "    }";
        ret += "    roomOut(id);";
        ret += "    if (sNrRooms==" + getClazz().getNumberOfRooms()
                + ") {displayLoading(); document.location='classInfo.do?op=Select&room='+sRooms+'&noCacheTS="
                + new Date().getTime() + "';}";
        ret += "    var c = document.getElementById('roomCapacityCounter');";
        ret += "    if (c!=null) c.innerHTML = (sCap<" + getClazz().getClassLimit()
                + "?'<font color=\"red\">'+sCap+'</font>':''+sCap);";
        ret += "}";
        ret += "</script>";
        ret += "<table border='0' cellspacing='0' cellpadding='3'>";
        int idx = 0;
        int step = 6;
        for (ClassRoomInfo room : rooms) {
            if ((idx % step) == 0) {
                if (idx > 0)
                    ret += "</tr>";
                ret += "<tr>";
            }
            String style = "";
            if (assigned != null && assigned.contains(room))
                style += "background-color:rgb(168,187,225);";
            if (original != null && original.contains(room))
                style += "text-decoration:underline;";
            String mouse = "onMouseOver=\"roomOver(this," + room.getLocationId() + ");\" "
                    + "onMouseOut=\"roomOut(" + room.getLocationId() + ");\" " + "onClick=\"roomClick(this,"
                    + room.getLocationId() + "," + room.getCapacity() + ");\"";
            ret += "<td nowrap id='r" + room.getLocationId() + "' "
                    + (style.length() > 0 ? "style='" + style + "' " : "") + mouse + ">" + room.toString()
                    + "</td>";
            if ((idx % step) < step - 1)
                style += "border-right: #646464 1px dashed;";
            ret += "<td id='c" + room.getLocationId() + "' "
                    + (style.length() > 0 ? "style='" + style + "' " : "") + mouse + ">" + room.getCapacity()
                    + "</td>";
            idx++;
        }
        while ((idx % step) != 0) {
            ret += "<td colspan='2'>&nbsp;</td>";
            idx++;
        }
        ret += "</tr>";
        ret += "</table>";
        return ret;
    } catch (Exception e) {
        iForm.setMessage(e.getMessage());
        sLog.error(e.getMessage(), e);
        return "";
    }
}

From source file:org.unitime.timetable.solver.course.ui.ClassInfoModel.java

public void update() throws Exception {
    if (iChange == null)
        return;/* ww  w .  ja va 2  s.c o  m*/
    Vector<ClassAssignment> assignments = new Vector(iChange.getAssignments());
    Hashtable<Long, ClassAssignment> table = iChange.getAssignmentTable();
    iUnassignConflictingAssignments = !iForm.getKeepConflictingAssignments();
    iChange.getAssignments().clear();
    for (ClassAssignment assignment : assignments) {
        iChange.getAssignments().add(new ClassAssignmentInfo(assignment.getClazz(), assignment.getTime(),
                assignment.getDate(), assignment.getRooms(), table));
    }
    if (assignments.isEmpty()) {
        for (Iterator<ClassAssignment> i = iChange.getConflicts().iterator(); i.hasNext();) {
            ClassAssignment assignment = i.next();
            if (!assignment.getClassId().equals(getClazz().getClassId()))
                i.remove();
        }
    } else {
        iChange.getConflicts().clear();
    }
    for (ClassAssignment assignment : iChange.getAssignments()) {
        // Skip incomplete assignments (that have no time assigned yet)
        if (!assignment.hasTime())
            continue;

        // Check for room conflicts
        if (iUnassignConflictingAssignments) {
            if (assignment.getRooms() != null)
                for (ClassRoomInfo room : assignment.getRooms()) {
                    if (!room.isIgnoreRoomChecks()) {
                        for (Assignment a : room.getLocation().getCommitedAssignments()) {
                            if (a.getClazz().isCancelled())
                                continue;
                            if (assignment.getTime().overlaps(new ClassTimeInfo(a))
                                    && !a.getClazz().canShareRoom(assignment.getClazz())) {
                                if (iChange.getCurrent(a.getClassId()) == null
                                        && iChange.getConflict(a.getClassId()) == null)
                                    iChange.getConflicts().add(new ClassAssignment(a));
                            }
                        }
                    }
                }

            // Check for instructor conflicts
            if (assignment.getInstructors() != null)
                for (ClassInstructorInfo instructor : assignment.getInstructors()) {
                    if (!instructor.isLead())
                        continue;
                    // check all departmental instructors with the same external id
                    for (DepartmentalInstructor di : DepartmentalInstructor
                            .getAllForInstructor(instructor.getInstructor().getInstructor())) {
                        for (ClassInstructor ci : di.getClasses()) {
                            if (ci.equals(instructor.getInstructor()))
                                continue;
                            Assignment a = ci.getClassInstructing().getCommittedAssignment();
                            if (a == null || a.getClazz().isCancelled())
                                continue;
                            if (assignment.getTime() != null
                                    && assignment.getTime().overlaps(new ClassTimeInfo(a))
                                    && !a.getClazz().canShareInstructor(assignment.getClazz())) {
                                if (iChange.getCurrent(a.getClassId()) == null
                                        && iChange.getConflict(a.getClassId()) == null)
                                    iChange.getConflicts().add(new ClassAssignment(a));
                            }
                        }
                    }
                    /*
                    // Potential speed-up #1) only check the current department instructors
                    for (ClassInstructor ci : instructor.getInstructor().getInstructor().getClasses()) {
                       if (ci.equals(instructor.getInstructor())) continue;
                       Assignment a = ci.getClassInstructing().getCommittedAssignment();
                       if (a == null) continue;
                       if (assignment.getTime().overlaps(new ClassTimeInfo(a))) {
                          if (iChange.getCurrent(a.getClassId())==null && iChange.getConflict(a.getClassId())==null)
                             iChange.getConflicts().add(new ClassAssignment(a));
                       }
                    }
                    */
                    /*
                    // Potential speed-up #2) use instructor assignments from the solution
                    for (Assignment a : instructor.getInstructor().getInstructor().getCommitedAssignments()) {
                       if (assignment.getTime().overlaps(new ClassTimeInfo(a))) {
                          if (iChange.getCurrent(a.getClassId())==null && iChange.getConflict(a.getClassId())==null)
                             iChange.getConflicts().add(new ClassAssignment(a));
                       }
                    }
                    */
                }
        }
        // Check the course structure for conflicts
        Class_ clazz = assignment.getClazz(Class_DAO.getInstance().getSession());
        // a) all parents
        Class_ parent = clazz.getParentClass();
        while (parent != null) {
            if (iChange.getCurrent(parent.getUniqueId()) == null
                    && iChange.getConflict(parent.getUniqueId()) == null) {
                Assignment a = parent.getCommittedAssignment();
                if (a != null && !a.getClazz().isCancelled()
                        && assignment.getTime().overlaps(new ClassTimeInfo(a))) {
                    iChange.getConflicts().add(new ClassAssignment(a));
                }
            }
            parent = parent.getParentClass();
        }
        // b) all children
        Queue<Class_> children = new LinkedList();
        try {
            children.addAll(clazz.getChildClasses());
        } catch (LazyInitializationException e) {
            sLog.error("This should never happen.");
            Class_ c = Class_DAO.getInstance().get(assignment.getClassId());
            children.addAll(c.getChildClasses());
        }
        Class_ child = null;
        while ((child = children.poll()) != null) {
            if (iChange.getCurrent(child.getUniqueId()) == null
                    && iChange.getConflict(child.getUniqueId()) == null) {
                Assignment a = child.getCommittedAssignment();
                if (a != null && !a.getClazz().isCancelled()
                        && assignment.getTime().overlaps(new ClassTimeInfo(a))) {
                    iChange.getConflicts().add(new ClassAssignment(a));
                }
            }
            if (!child.getChildClasses().isEmpty())
                children.addAll(child.getChildClasses());
        }
        // c) all single-class subparts
        for (Iterator i = clazz.getSchedulingSubpart().getInstrOfferingConfig().getSchedulingSubparts()
                .iterator(); i.hasNext();) {
            SchedulingSubpart ss = (SchedulingSubpart) i.next();
            if (ss.getClasses().size() == 1) {
                child = (Class_) ss.getClasses().iterator().next();
                if (iChange.getCurrent(child.getUniqueId()) == null
                        && iChange.getConflict(child.getUniqueId()) == null) {
                    Assignment a = child.getCommittedAssignment();
                    if (a != null && !a.getClazz().isCancelled()
                            && assignment.getTime().overlaps(new ClassTimeInfo(a))) {
                        iChange.getConflicts().add(new ClassAssignment(a));
                    }
                }
                if (!child.getChildClasses().isEmpty())
                    children.addAll(child.getChildClasses());
            }
        }

        //TODO: Check for other HARD conflicts (e.g., distribution constraints)
    }
}

From source file:com.alfaariss.oa.authentication.password.PasswordAuthenticationMethod.java

/**
 * Function for online authentication.//  w w w  .j a v  a2  s.c  o  m
 * 
 * Authenticates the user using the configured Password handler
 * (JDBC, JNDI, RADIUS etc.). When Captcha is enabled the user must also
 * submit the supplied text in the captcha image.
 * @see IWebAuthenticationMethod#authenticate(
 *  HttpServletRequest, HttpServletResponse, ISession)
 */
public UserEvent authenticate(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession)
        throws OAException {
    IUser oUser = null;
    String sUserPassword = null;
    boolean bRetries = true;
    int iTries = _iAllowedTries;
    ISessionAttributes oAttributes = null;
    UserEvent userEvent = null;
    String sUserId = null;

    try {
        oAttributes = oSession.getAttributes();
        // Get retries left
        Integer intTries = ((Integer) oAttributes.get(PasswordAuthenticationMethod.class,
                _sMethodID + RETRIES_ATTRIBUTE_NAME));

        //handle
        if (intTries == null) //First call to pwd method
        {
            //get user from session
            oUser = oSession.getUser();
            if (oUser == null) {
                // If no user in session, check forced user
                sUserId = oSession.getForcedUserID();
                if (sUserId != null) {
                    oUser = _oUserFactory.getUser(sUserId);
                    if (oUser == null) {
                        throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
                    }

                    if (!oUser.isEnabled()) {
                        throw new UserException(UserEvent.USER_DISABLED);
                    }

                    // Check is user is registered for password method
                    if (!oUser.isAuthenticationRegistered(_sMethodID)) {
                        throw new UserException(UserEvent.AUTHN_METHOD_NOT_REGISTERED);
                    }
                    oSession.setUser(oUser);
                }
            } else {
                // Check is user is registered for password method
                if (!oUser.isAuthenticationRegistered(_sMethodID)) {
                    throw new UserException(UserEvent.AUTHN_METHOD_NOT_REGISTERED);
                }
            }
            forwardUser(oRequest, oResponse, oSession, iTries, bRetries, new Vector<Enum>());
            userEvent = UserEvent.AUTHN_METHOD_IN_PROGRESS;
        } else {
            iTries = intTries.intValue();
            Vector<Enum> warnings = new Vector<Enum>();
            // Check if captcha is enabled and verify if a captcha is supplied.
            String sCaptcha = null;
            if (_bCaptchaEnabled) {
                // Get supplied captcha.
                sCaptcha = oRequest.getParameter(CAPTCHA);
                if ((sCaptcha == null) || (sCaptcha.trim().length() <= 0)) {
                    // does not count as an attempt
                    bRetries = false;
                    warnings.add(Warnings.NO_CAPTCHA_SUPPLIED);
                }
            }

            //get user from session
            oUser = oSession.getUser();
            if (oUser == null) {
                // If no user in session, get it from request
                sUserId = oRequest.getParameter(USERID_ATTRIBUTE_NAME);
                if ((sUserId == null) || sUserId.equals("")) {
                    // do not treat as an attempt
                    bRetries = false;
                    warnings.add(Warnings.NO_USERNAME_SUPPLIED);
                } else {
                    oUser = _oUserFactory.getUser(sUserId);
                }
            }

            // Get supplied password.
            sUserPassword = oRequest.getParameter(PASSWORD);
            if ((sUserPassword == null) || sUserPassword.trim().equalsIgnoreCase("")) {
                // does not count as an attempt
                bRetries = false;
                warnings.add(Warnings.NO_PASSWORD_SUPPLIED);
            }

            //Check for missing request parameters
            if (!warnings.isEmpty()) {
                //throw new DetailedUserException(warnings);
                throw new DetailedUserException(UserEvent.AUTHN_METHOD_IN_PROGRESS, warnings);
            }

            //Verify captcha
            if (_bCaptchaEnabled) {
                Class cCaptchaEngine = null;

                try {
                    cCaptchaEngine = Class.forName("com.alfaariss.oa.helper.captcha.engine.CaptchaEngine");
                } catch (ClassNotFoundException e) {
                    _logger.error(
                            "Captcha enabled, but 'com.alfaariss.oa.helper.captcha.engine.CaptchaEngine' is not available",
                            e);
                    throw new OAException(SystemErrors.ERROR_INTERNAL);
                }
                byte[] baCaptchaHash = (byte[]) oAttributes.get(cCaptchaEngine, CAPTCHA_HASH);
                if (!verifyCaptcha(sCaptcha, baCaptchaHash)) {
                    throw new DetailedUserException(UserEvent.AUTHN_METHOD_IN_PROGRESS,
                            Warnings.INVALID_CAPTCHA_SUPPLIED);
                }
                oAttributes.remove(cCaptchaEngine, CAPTCHA_HASH);
            }

            //Verify User
            if (sUserId != null) //Submitted user
            {
                if (oUser == null) {
                    throw new DetailedUserException(UserEvent.AUTHN_METHOD_IN_PROGRESS,
                            Warnings.NO_SUCH_USER_FOUND);
                }
            }

            //Get the correct User ID to authenticate with the resource.
            String sAuthUserId = null;
            //If ID mapping is enabled, map the OA user name to the corresponding pwd username.
            if (_idMapper != null) {
                sAuthUserId = _idMapper.map(oUser.getID());
                if (sAuthUserId == null) {
                    throw new UserException(UserEvent.AUTHN_METHOD_FAILED);
                }
            } else {
                sAuthUserId = oUser.getID();
            }

            // Authenticate with supplied credentials against the configured password method.
            if (!_oPasswordHandler.authenticate(sAuthUserId, sUserPassword)) {
                throw new DetailedUserException(UserEvent.AUTHN_METHOD_IN_PROGRESS,
                        Warnings.INVALID_CREDENTIALS_SUPPLIED);
            }

            if (sUserId != null) {
                if (!oUser.isEnabled()) {
                    throw new UserException(UserEvent.USER_DISABLED);
                }

                // Check is user is registered for password method
                if (!oUser.isAuthenticationRegistered(_sMethodID)) {
                    throw new UserException(UserEvent.AUTHN_METHOD_NOT_REGISTERED);
                }
            }

            //everything Okay
            oSession.setUser(oUser);
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                    UserEvent.AUTHN_METHOD_SUCCESSFUL, this, null));

            userEvent = UserEvent.AUTHN_METHOD_SUCCESSFUL;
        }
    } catch (UserException e) {
        userEvent = e.getEvent();

        _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), e.getEvent(), this, null));
    } catch (DetailedUserException e) {
        if (iTries <= 0) {
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                    UserEvent.AUTHN_METHOD_FAILED, this, e.getDetails().toString()));
            userEvent = UserEvent.AUTHN_METHOD_FAILED;
        } else {
            //Event logging is executed in showPage

            //Show page once again
            forwardUser(oRequest, oResponse, oSession, iTries, bRetries, e.getDetails());
            userEvent = e.getEvent();
        }

    } catch (OAException e) {
        _eventLogger.info(
                new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR, this, null));
        //already logged to system log.
        throw e;
    } catch (Exception e) {
        if (oSession != null) {
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, e.getMessage()));
        } else {
            _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                    oRequest.getRemoteAddr(), null, this, e.getMessage()));
        }

        _logger.fatal("Unexpected runtime error occured: ", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
    return userEvent;
}

From source file:org.ecoinformatics.seek.ecogrid.EcoGridServicesController.java

/**
 * Add a service to service list. If new service has same endpoints to
 * service already in current. Then we will compare document type array and
 * add new document type into service If the serviceType is not a in our
 * list, it will throw an exception/*w  ww. j  a va  2s . c  o  m*/
 * 
 * @param service
 *            EcoGridService
 * @throws InvalidEcoGridServiceException
 */
public void addService(EcoGridService service) throws InvalidEcoGridServiceException {
    String serviceType = service.getServiceType();
    if (serviceType == null || !serviceTypes.contains(serviceType)) {
        throw new InvalidEcoGridServiceException(
                "The service type is invalid or null: " + serviceType + ".  Couldn't be added to list");
    } // if

    // isDuplicateService
    int index = isDuplicateService(service, currentServicesList);
    if (index == -1) {
        // it is new end point
        if (isDebugging) {
            log.debug("Add service " + service.getServiceName() + " into list");
        }
        currentServicesList.add(service);
    } else {
        // compare document type list if new service has same endpoint
        EcoGridService currentService = (EcoGridService) currentServicesList.elementAt(index);
        DocumentType[] currentDocTypeList = currentService.getDocumentTypeList();
        DocumentType[] newDocTypeList = service.getDocumentTypeList();
        if (currentDocTypeList == null || currentDocTypeList.length == 0) {
            // if current service doesn't have any document type, just set
            // the new one
            currentService.setDocumentTypeList(newDocTypeList);
        } else if (newDocTypeList != null) {
            int sizeOfnew = newDocTypeList.length;
            int sizeofCurrent = currentDocTypeList.length;
            Vector newDocTypeVector = new Vector();
            // go through new document type
            for (int j = 0; j < sizeOfnew; j++) {
                boolean existed = false;
                DocumentType newType = newDocTypeList[j];
                if (newType == null) {
                    continue;
                }
                String newNamespace = newType.getNamespace();
                if (newNamespace == null || newNamespace.trim().equals("")) {
                    continue;
                }
                for (int i = 0; i < sizeofCurrent; i++) {
                    DocumentType currentType = currentDocTypeList[i];
                    if (currentType == null) {
                        continue;
                    } else {
                        String currentNamespace = currentType.getNamespace();
                        if (currentNamespace == null || currentNamespace.trim().equals("")) {
                            continue;
                        } else if (currentNamespace.equals(newNamespace)) {
                            existed = true;
                        } //
                    } // else

                } // for
                  // if the namespace is a new space, add this document type
                  // into the array
                if (!existed) {
                    newDocTypeVector.add(newType);
                }
            } // for
              // if we do get some new document type(newDocTypeVector is not
              // empty)
              // we should a new doctype into list
            if (!newDocTypeVector.isEmpty()) {
                DocumentType[] updatedDocTypeList = addNewDocType(currentDocTypeList, newDocTypeVector);
                currentService.setDocumentTypeList(updatedDocTypeList);
            } // if

        } // else if
    } // else
}