Example usage for java.util HashSet iterator

List of usage examples for java.util HashSet iterator

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:org.unitime.timetable.action.PersonalizedExamReportAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    PersonalizedExamReportForm myForm = (PersonalizedExamReportForm) form;

    String back = (String) request.getSession().getAttribute("loginPage");
    if (back == null)
        back = "back";

    try {/*from  ww  w  .jav  a 2 s  .c o  m*/
        sessionContext.checkPermission(Right.PersonalSchedule);
    } catch (AccessDeniedException e) {
        request.setAttribute("message", e.getMessage());
        return mapping.findForward(back);
    }

    if (request.getParameter("q") != null) {
        String[] params = QueryEncoderBackend.decode(request.getParameter("q")).split(":");
        if (params != null && params.length == 2) {
            myForm.setUid(params[0]);
            myForm.setSessionId(Long.valueOf(params[1]));
        }
    }

    String externalId = sessionContext.getUser().getExternalUserId();
    String userName = sessionContext.getUser().getName();

    myForm.setAdmin(sessionContext.hasPermission(Right.PersonalScheduleLookup));
    myForm.setLogout(!"back".equals(back));

    if (sessionContext.hasPermission(Right.PersonalScheduleLookup) && myForm.getUid() != null
            && !myForm.getUid().isEmpty()) {
        externalId = myForm.getUid();
        userName = (myForm.getLname() == null || myForm.getLname().length() == 0 ? ""
                : " " + Constants.toInitialCase(myForm.getLname()))
                + (myForm.getFname() == null || myForm.getFname().length() == 0 ? ""
                        : " " + myForm.getFname().substring(0, 1).toUpperCase())
                + (myForm.getMname() == null || myForm.getMname().length() == 0 ? ""
                        : " " + myForm.getMname().substring(0, 1).toUpperCase());
    }

    if (externalId == null || externalId.length() == 0) {
        request.setAttribute("message", "No user id provided.");
        return mapping.findForward(back);
    }

    if ("Log Out".equals(myForm.getOp())) {
        SecurityContextHolder.getContext().setAuthentication(null);
        return mapping.findForward(back);
    }

    if ("classes".equals(back)) {
        if (myForm.getSessionId() == null) {
            myForm.setSessionId((Long) request.getSession().getAttribute("Classes.session"));
        } else {
            request.getSession().setAttribute("Classes.session", myForm.getSessionId());
        }
    } else if ("exams".equals(back)) {
        if (myForm.getSessionId() == null) {
            myForm.setSessionId((Long) request.getSession().getAttribute("Exams.session"));
        } else {
            request.getSession().setAttribute("Exams.session", myForm.getSessionId());
        }
    }

    HashSet<Session> sessions = new HashSet();
    DepartmentalInstructor instructor = null;
    for (Iterator i = new DepartmentalInstructorDAO().getSession()
            .createQuery("select i from DepartmentalInstructor i where i.externalUniqueId=:externalId")
            .setString("externalId", translate(externalId, Source.Staff)).setCacheable(true).list()
            .iterator(); i.hasNext();) {
        DepartmentalInstructor s = (DepartmentalInstructor) i.next();
        if (!canDisplay(s.getDepartment().getSession()))
            continue;
        sessions.add(s.getDepartment().getSession());
        if (myForm.getSessionId() == null) {
            if (instructor == null
                    || instructor.getDepartment().getSession().compareTo(s.getDepartment().getSession()) < 0)
                instructor = s;
        } else if (myForm.getSessionId().equals(s.getDepartment().getSession().getUniqueId())) {
            instructor = s;
        }
    }

    Student student = null;
    for (Iterator i = new StudentDAO().getSession()
            .createQuery("select s from Student s where s.externalUniqueId=:externalId")
            .setString("externalId", translate(externalId, Source.Student)).setCacheable(true).list()
            .iterator(); i.hasNext();) {
        Student s = (Student) i.next();
        if (!canDisplay(s.getSession()))
            continue;
        sessions.add(s.getSession());
        if (myForm.getSessionId() == null) {
            if (student == null || student.getSession().compareTo(s.getSession()) < 0)
                student = s;
        } else if (myForm.getSessionId().equals(s.getSession().getUniqueId()))
            student = s;
    }

    if (instructor == null && student == null) {
        if (myForm.getAdmin()) {
            back = "back";
            myForm.setLogout(false);
        } else {
            if ("classes".equals(back))
                request.setAttribute("message", "No classes found.");
            else if ("exams".equals(back))
                request.setAttribute("message", "No examinations found.");
            else
                request.setAttribute("message", "No schedule found.");
            sLog.info("No matching instructor or student found for " + userName + " ("
                    + translate(externalId, Source.Student) + "), forwarding back (" + back + ").");
            return mapping.findForward(back);
        }
    }

    myForm.setCanExport(false);

    if (instructor != null && student != null
            && !instructor.getDepartment().getSession().equals(student.getSession())) {
        if (instructor.getDepartment().getSession().compareTo(student.getSession()) < 0)
            instructor = null;
        else
            student = null;
    }
    long t0 = System.currentTimeMillis();
    if (instructor != null) {
        sLog.info("Requesting schedule for " + instructor.getName(DepartmentalInstructor.sNameFormatShort)
                + " (instructor)");
    } else if (student != null) {
        sLog.info("Requesting schedule for " + student.getName(DepartmentalInstructor.sNameFormatShort)
                + " (student)");
    }

    HashSet<ExamOwner> studentExams = new HashSet<ExamOwner>();
    if (student != null) {
        /*
         for (Iterator i=student.getClassEnrollments().iterator();i.hasNext();) {
        StudentClassEnrollment sce = (StudentClassEnrollment)i.next();
        studentExams.addAll(Exam.findAllRelated("Class_", sce.getClazz().getUniqueId()));
         }
         */
        studentExams.addAll(new ExamDAO().getSession().createQuery(
                "select distinct o from Student s inner join s.classEnrollments ce, ExamOwner o inner join o.course co "
                        + "inner join co.instructionalOffering io " + "inner join io.instrOfferingConfigs ioc "
                        + "inner join ioc.schedulingSubparts ss " + "inner join ss.classes c where "
                        + "s.uniqueId=:studentId and c=ce.clazz and (" + "(o.ownerType="
                        + ExamOwner.sOwnerTypeCourse + " and o.ownerId=co.uniqueId) or " + "(o.ownerType="
                        + ExamOwner.sOwnerTypeOffering + " and o.ownerId=io.uniqueId) or " + "(o.ownerType="
                        + ExamOwner.sOwnerTypeConfig + " and o.ownerId=ioc.uniqueId) or " + "(o.ownerType="
                        + ExamOwner.sOwnerTypeClass + " and o.ownerId=c.uniqueId) " + ")")
                .setLong("studentId", student.getUniqueId()).setCacheable(true).list());
        for (Iterator<ExamOwner> i = studentExams.iterator(); i.hasNext();) {
            Exam exam = i.next().getExam();
            DepartmentStatusType type = exam.effectiveStatusType();
            if (type == null || !type.can(exam.getExamType().getType() == ExamType.sExamTypeFinal
                    ? DepartmentStatusType.Status.ReportExamsFinal
                    : DepartmentStatusType.Status.ReportExamsMidterm))
                i.remove();
        }
    }

    HashSet<Exam> instructorExams = new HashSet<Exam>();
    if (instructor != null) {
        instructorExams.addAll(instructor.getAllExams());
        for (Iterator<Exam> i = instructorExams.iterator(); i.hasNext();) {
            Exam exam = i.next();
            DepartmentStatusType type = exam.effectiveStatusType();
            if (type == null || !type.can(exam.getExamType().getType() == ExamType.sExamTypeFinal
                    ? DepartmentStatusType.Status.ReportExamsFinal
                    : DepartmentStatusType.Status.ReportExamsMidterm))
                i.remove();
        }
    }

    WebTable.setOrder(sessionContext, "exams.o0", request.getParameter("o0"), 1);
    WebTable.setOrder(sessionContext, "exams.o1", request.getParameter("o1"), 1);
    WebTable.setOrder(sessionContext, "exams.o2", request.getParameter("o2"), 1);
    WebTable.setOrder(sessionContext, "exams.o3", request.getParameter("o3"), 1);
    WebTable.setOrder(sessionContext, "exams.o4", request.getParameter("o4"), 1);
    WebTable.setOrder(sessionContext, "exams.o5", request.getParameter("o5"), 1);
    WebTable.setOrder(sessionContext, "exams.o6", request.getParameter("o6"), 1);
    WebTable.setOrder(sessionContext, "exams.o7", request.getParameter("o7"), 1);

    boolean hasClasses = false;
    if (student != null && student.getSession().canNoRoleReportClass()
            && !student.getClassEnrollments().isEmpty()) {
        PdfWebTable table = getStudentClassSchedule(true, student);
        if (!table.getLines().isEmpty()) {
            request.setAttribute("clsschd", table.printTable(WebTable.getOrder(sessionContext, "exams.o6")));
            hasClasses = true;
            myForm.setCanExport(true);
        }
    }
    if (instructor != null && instructor.getDepartment().getSession().canNoRoleReportClass()) {
        PdfWebTable table = getInstructorClassSchedule(true, instructor);
        if (!table.getLines().isEmpty()) {
            request.setAttribute("iclsschd",
                    table.printTable(Math.abs(WebTable.getOrder(sessionContext, "exams.o7"))));
            hasClasses = true;
            myForm.setCanExport(true);
        }
    }

    if (instructor != null && sessions.size() > 1) {
        PdfWebTable table = getSessions(true, sessions,
                instructor.getName(DepartmentalInstructor.sNameFormatLastFist),
                instructor.getDepartment().getSession().getUniqueId());
        request.setAttribute("sessions", table.printTable(WebTable.getOrder(sessionContext, "exams.o0")));
    } else if (student != null && sessions.size() > 1) {
        PdfWebTable table = getSessions(true, sessions,
                student.getName(DepartmentalInstructor.sNameFormatLastFist),
                student.getSession().getUniqueId());
        request.setAttribute("sessions", table.printTable(WebTable.getOrder(sessionContext, "exams.o0")));
    }

    if (!hasClasses && instructorExams.isEmpty() && studentExams.isEmpty()) {
        if ("classes".equals(back))
            myForm.setMessage("No classes found in "
                    + (instructor != null ? instructor.getDepartment().getSession() : student.getSession())
                            .getLabel()
                    + ".");
        else if ("exams".equals(back))
            myForm.setMessage("No examinations found in "
                    + (instructor != null ? instructor.getDepartment().getSession() : student.getSession())
                            .getLabel()
                    + ".");
        else if (student != null || instructor != null)
            myForm.setMessage("No classes or examinations found in "
                    + (instructor != null ? instructor.getDepartment().getSession() : student.getSession())
                            .getLabel()
                    + ".");
        else if (sessionContext.hasPermission(Right.PersonalScheduleLookup))
            myForm.setMessage(
                    "No classes or examinations found in "
                            + SessionDAO.getInstance()
                                    .get(sessionContext.getUser().getCurrentAcademicSessionId()).getLabel()
                            + ".");
        else
            myForm.setMessage("No classes or examinations found for " + userName + ".");
        sLog.info("No classes or exams found for " + (instructor != null
                ? instructor.getName(DepartmentalInstructor.sNameFormatShort)
                : student != null ? student.getName(DepartmentalInstructor.sNameFormatShort) : userName));
    }

    boolean useCache = ApplicationProperty.ExaminationCacheConflicts.isTrue();

    if ("Export PDF".equals(myForm.getOp())) {
        sLog.info("  Generating PDF for "
                + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort)
                        : student.getName(DepartmentalInstructor.sNameFormatShort)));
        OutputStream out = ExportUtils.getPdfOutputStream(response, "schedule");

        if (!instructorExams.isEmpty()) {
            TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>();
            for (Exam exam : instructorExams) {
                if (exam.getAssignedPeriod() == null)
                    continue;
                exams.add(new ExamAssignmentInfo(exam, useCache));
            }

            InstructorExamReport ir = new InstructorExamReport(InstructorExamReport.sModeNormal, out,
                    instructor.getDepartment().getSession(), null, null, exams);
            ir.setM2d(true);
            ir.setDirect(true);
            ir.setClassSchedule(instructor.getDepartment().getSession().canNoRoleReportClass());
            ir.printHeader();
            ir.printReport(ExamInfo.createInstructorInfo(instructor), exams);
            ir.lastPage();
            ir.close();
        } else if (!studentExams.isEmpty()) {
            TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>();
            TreeSet<ExamSectionInfo> sections = new TreeSet<ExamSectionInfo>();
            for (ExamOwner examOwner : studentExams) {
                if (examOwner.getExam().getAssignedPeriod() == null)
                    continue;
                ExamAssignmentInfo x = new ExamAssignmentInfo(examOwner, student, studentExams);
                exams.add(x);
                sections.addAll(x.getSectionsIncludeCrosslistedDummies());
            }

            StudentExamReport sr = new StudentExamReport(StudentExamReport.sModeNormal, out,
                    student.getSession(), null, null, exams);
            sr.setM2d(true);
            sr.setBtb(true);
            sr.setDirect(true);
            sr.setClassSchedule(student.getSession().canNoRoleReportClass());
            sr.printHeader();
            sr.printReport(student, sections);
            sr.lastPage();
            sr.close();
        } else if (hasClasses) {
            if (instructor != null) {
                InstructorExamReport ir = new InstructorExamReport(InstructorExamReport.sModeNormal, out,
                        instructor.getDepartment().getSession(), null, null, new TreeSet<ExamAssignmentInfo>());
                ir.setM2d(true);
                ir.setDirect(true);
                ir.setClassSchedule(instructor.getDepartment().getSession().canNoRoleReportClass());
                ir.printHeader();
                ir.printReport(ExamInfo.createInstructorInfo(instructor), new TreeSet<ExamAssignmentInfo>());
                ir.lastPage();
                ir.close();
            } else if (student != null) {
                StudentExamReport sr = new StudentExamReport(StudentExamReport.sModeNormal, out,
                        student.getSession(), null, null, new TreeSet<ExamAssignmentInfo>());
                sr.setM2d(true);
                sr.setBtb(true);
                sr.setDirect(true);
                sr.setClassSchedule(student.getSession().canNoRoleReportClass());
                sr.printHeader();
                sr.printReport(student, new TreeSet<ExamSectionInfo>());
                sr.lastPage();
                sr.close();
            }
        }

        out.flush();
        out.close();
        return null;
    }

    if ("iCalendar".equals(myForm.getOp())) {
        Long sid = (instructor != null ? instructor.getDepartment().getSession().getUniqueId()
                : student.getSession().getUniqueId());
        response.sendRedirect(response.encodeURL("export?q=" + QueryEncoderBackend.encode(
                "output=events.ics&type=person&ext=" + externalId + (sid == null ? "" : "&sid=" + sid))));
        return null;
    }

    /*
    if ("iCalendar".equals(myForm.getOp())) {
    sLog.info("  Generating calendar for "+(instructor!=null?instructor.getName(DepartmentalInstructor.sNameFormatShort):student.getName(DepartmentalInstructor.sNameFormatShort)));
    try {
        File file = ApplicationProperties.getTempFile("schedule", "ics");
                
        if (instructor!=null) {
            printInstructorSchedule(file, instructor, instructorExams);
        } else {
            printStudentSchedule(file, student, studentExams);
        }
                
        request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/"+file.getName());
    } catch (Exception e) {
        sLog.error("Unable to generate calendar for "+(instructor!=null?instructor.getName(DepartmentalInstructor.sNameFormatShort):student.getName(DepartmentalInstructor.sNameFormatShort)),e);
    }
    }
    */

    if (!studentExams.isEmpty()) {
        myForm.setCanExport(true);
        TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>();
        for (ExamOwner examOwner : studentExams)
            exams.add(new ExamAssignmentInfo(examOwner, student, studentExams));

        PdfWebTable table = getStudentExamSchedule(true, exams, student);
        request.setAttribute("schedule", table.printTable(WebTable.getOrder(sessionContext, "exams.o1")));

        table = getStudentConflits(true, exams, student);
        if (!table.getLines().isEmpty())
            request.setAttribute("conf", table.printTable(WebTable.getOrder(sessionContext, "exams.o3")));
    }

    if (!instructorExams.isEmpty()) {
        myForm.setCanExport(true);
        TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>();
        for (Exam exam : instructorExams)
            exams.add(new ExamAssignmentInfo(exam, useCache));

        PdfWebTable table = getInstructorExamSchedule(true, exams, instructor);
        request.setAttribute("ischedule", table.printTable(WebTable.getOrder(sessionContext, "exams.o2")));

        table = getInstructorConflits(true, exams, instructor);
        if (!table.getLines().isEmpty())
            request.setAttribute("iconf", table.printTable(WebTable.getOrder(sessionContext, "exams.o4")));

        table = getStudentConflits(true, exams, instructor);
        if (!table.getLines().isEmpty())
            request.setAttribute("sconf", table.printTable(WebTable.getOrder(sessionContext, "exams.o5")));
    }
    long t1 = System.currentTimeMillis();
    sLog.info("Request processed in " + new DecimalFormat("0.00").format(((double) (t1 - t0)) / 1000.0)
            + " s for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort)
                    : student != null ? student.getName(DepartmentalInstructor.sNameFormatShort) : userName));
    return mapping.findForward("show");
}

From source file:eionet.cr.harvest.scheduled.HarvestingJob.java

/**
 *
 * @throws DAOException//from   w w w  .  ja v a2 s .  co m
 */
private void handleBatchQueue() throws DAOException {

    // Even if it is not currently a batch harvesting hour, we shall proceed to getting the list of next scheduled sources, and
    // looping over them, as there are specific sources for which the batch-harvesting hours should be ignored. Currently these
    // are sources whose harvest interval is less than 8 hours.

    if (isBatchHarvestingHour()) {
        LOGGER.trace("Handling batch queue...");
    }

    // Initialize batch queue collection.
    batchQueue = Collections.synchronizedList(new ArrayList<HarvestSourceDTO>());

    // Initialize collection for sources that will have to be deleted.
    HashSet<String> sourcesToDelete = new HashSet<String>();

    // Initialize harvest source DAO.
    HarvestSourceDAO sourceDao = DAOFactory.get().getDao(HarvestSourceDAO.class);

    // Get next scheduled sources.
    List<HarvestSourceDTO> nextScheduledSources = getNextScheduledSources();
    if (isBatchHarvestingHour()) {
        LOGGER.trace(nextScheduledSources.size() + " next scheduled sources found");
    }

    // Loop over next scheduled sources.
    for (HarvestSourceDTO sourceDTO : nextScheduledSources) {

        // If source is marked with permanent error then increase its unavailability count if it's a
        // priority source, or simply delete it if it's not a priority source.
        // If source not marked with permanent and its unavailability count is >=5 and it's a
        // non-priority source then delete it.
        // In all other cases, add the harvest source to the batch-harvest queue.
        if (sourceDTO.isPermanentError()) {
            if (sourceDTO.isPrioritySource()) {
                LOGGER.trace("Increasing unavailability count of permanent-error priority source "
                        + sourceDTO.getUrl());
                sourceDao.increaseUnavailableCount(sourceDTO.getUrl());
            } else {
                LOGGER.debug(
                        sourceDTO.getUrl() + "  will be deleted as a non-priority source with permanent error");
                sourcesToDelete.add(sourceDTO.getUrl());
            }
        } else if (sourceDTO.getCountUnavail() >= 5) {
            if (!sourceDTO.isPrioritySource()) {
                LOGGER.debug(sourceDTO.getUrl()
                        + "  will be deleted as a non-priority source with unavailability >= 5");
                sourcesToDelete.add(sourceDTO.getUrl());
            }
        } else {
            batchQueue.add(sourceDTO);
        }
    }

    // Harvest the batch harvest queue (if anything added to it).
    for (Iterator<HarvestSourceDTO> iter = batchQueue.iterator(); iter.hasNext();) {

        HarvestSourceDTO sourceDTO = iter.next();

        // For sources where interval is less than 8 hours, the batch harvesting hours doesn't apply.
        // They are always harvested.
        boolean ignoreBatchHarvestingHour = sourceDTO.getIntervalMinutes().intValue() < 480;
        if (isBatchHarvestingHour() || ignoreBatchHarvestingHour) {

            // Remove source from batch harvest queue before starting its harvest.
            iter.remove();

            LOGGER.trace("Going to batch-harvest " + sourceDTO.getUrl());
            pullHarvest(sourceDTO, false);
        }
    }

    // Delete sources that were found necessary to delete (if any).
    if (!sourcesToDelete.isEmpty()) {

        LOGGER.debug("Deleting " + sourcesToDelete.size() + " sources found above");
        for (Iterator<String> iter = sourcesToDelete.iterator(); iter.hasNext();) {

            String sourceUrl = iter.next();
            if (CurrentHarvests.contains(sourceUrl)) {
                iter.remove();
                LOGGER.debug("Skipping deletion of " + sourceUrl + " because it is currently being harvested");
            }
        }
        sourceDao.removeHarvestSources(sourcesToDelete);
    }
}

From source file:admixture.parameter.Parameter.java

public void commandListenor(String[] args) {
    CommandLine cl = null;/*from  w  ww .java2 s.com*/
    try {
        cl = parser.parse(ops, args);
    } catch (ParseException E) {
        System.err.println(E.getMessage());
        System.exit(0);
    }
    if (cl.hasOption(cmd_help)) {
        help = true;
    }
    if (cl.hasOption(cmd_trans)) {
        transFlag = true;
    }
    if (cl.hasOption(cmd_out)) {
        out = cl.getOptionValue(cmd_out);
    }

    if (cl.hasOption(cmd_collapse)) {
        collapseFlag = true;
    }

    if (cl.hasOption(cmd_cc)) {
        ccFlag = true;

        piFlag = false;
        piiFlag = false;
        uiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_pi)) {
        piFlag = true;

        ccFlag = false;
        piiFlag = false;
        uiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_pii)) {
        piiFlag = true;

        ccFlag = false;
        piFlag = false;
        uiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_ui)) {
        uiFlag = true;

        ccFlag = false;
        piFlag = false;
        piiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_uii)) {
        uiiFlag = true;

        ccFlag = false;
        piFlag = false;
        piiFlag = false;
        uiFlag = false;
    }

    // file
    if (cl.hasOption(cmd_file)) {
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        sb1.append(cl.getOptionValue(cmd_file));
        sb1.append(".ped");

        sb2.append(cl.getOptionValue(cmd_file));
        sb2.append(".map");

        ped = sb1.toString();
        map = sb2.toString();
    }
    //      if (cl.hasOption(cmd_ped)) {
    //         ped = cl.getOptionValue(cmd_ped);
    //      }
    //      if (cl.hasOption(cmd_map)) {
    //         map = cl.getOptionValue(cmd_map);
    //      }
    if (ped != null && map != null) {
        File fped = new File(ped);
        if (!fped.exists()) {
            System.err.println("could not open " + ped + ".");
            Test.LOG.append("could not open " + ped + ".\n");
            Test.printLog();
            System.exit(0);
        }
        File fmap = new File(map);
        if (!fmap.exists()) {
            System.err.println("could not open " + map + ".");
            Test.LOG.append("could not open " + map + ".\n");
            Test.printLog();
            System.exit(0);
        }
        fileFlag = true;
    }

    // bfile
    if (cl.hasOption(cmd_bfile)) {
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        StringBuffer sb3 = new StringBuffer();
        sb1.append(cl.getOptionValue(cmd_bfile));
        sb1.append(".bed");

        sb2.append(cl.getOptionValue(cmd_bfile));
        sb2.append(".bim");

        sb3.append(cl.getOptionValue(cmd_bfile));
        sb3.append(".fam");

        bed = sb1.toString();
        bim = sb2.toString();
        fam = sb3.toString();
    }
    //      if (cl.hasOption(cmd_bed)) {
    //         bed = cl.getOptionValue(cmd_bed);
    //      }
    //      if (cl.hasOption(cmd_bim)) {
    //         bim = cl.getOptionValue(cmd_bim);
    //      }
    //      if (cl.hasOption(cmd_fam)) {
    //         fam = cl.getOptionValue(cmd_fam);
    //      }
    if (bed != null && bim != null && fam != null) {
        File fbed = new File(bed);
        if (!fbed.exists()) {
            System.err.println("could not open " + bed + ".");
            Test.LOG.append("could not open " + bed + ".\n");
            Test.printLog();
            System.exit(0);
        }
        File fbim = new File(bim);
        if (!fbim.exists()) {
            System.err.println("could not open " + bim + ".");
            Test.LOG.append("could not open " + bim + ".\n");
            Test.printLog();
            System.exit(0);
        }
        File ffam = new File(fam);
        if (!ffam.exists()) {
            System.err.println("could not open " + fam + ".");
            Test.LOG.append("could not open " + fam + ".\n");
            Test.printLog();
            System.exit(0);
        }
        bfileFlag = true;
    }

    if (cl.hasOption(cmd_covar)) {
        pheno = cl.getOptionValue(cmd_covar);
        File fpheno = new File(pheno);
        if (!fpheno.exists()) {
            System.err.println("could not open " + fpheno + ".");
            Test.LOG.append("could not open " + fpheno + ".\n");
            Test.printLog();
            System.exit(0);
        }
    }

    if (cl.hasOption(cmd_covar_header)) {
        covar_header_flag = true;
    }

    if (cl.hasOption(cmd_header)) {
        header = true;
    }

    if (cl.hasOption(cmd_linear)) {
        linkfunction = 0;
    }

    if (cl.hasOption(cmd_logistic)) {
        linkfunction = 1;
    }
    if (cl.hasOption(cmd_pheno_number)) {
        response = Integer.parseInt(cl.getOptionValue(cmd_pheno_number)) - 1;
        if (response < -1) {
            System.err.println("bad parameter for --" + cmd_pheno_number_long + ": " + (response + 1) + ".");
            Test.LOG.append("bad parameter for --" + cmd_pheno_number_long + ": " + (response + 1) + ".\n");
            Test.printLog();
            System.exit(0);
        }
    }

    if (cl.hasOption(cmd_covar_number)) {
        String[] p = cl.getOptionValues(cmd_covar_number);
        HashSet<Integer> idx = NewIt.newHashSet();
        for (int i = 0, len = p.length; i < len; i++) {
            if (p[i].contains("-")) {
                String[] pp = p[i].split("-");
                if (pp.length != 2) {
                    System.err
                            .println("bad parameter for option --" + cmd_covar_number_long + ": " + p[i] + ".");
                    Test.LOG.append(
                            "bad parameter for option --" + cmd_covar_number_long + ": " + p[i] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                for (int j = Integer.parseInt(pp[0]); j <= Integer.parseInt(pp[1]); j++) {
                    idx.add(new Integer(j));
                }
            } else {
                idx.add(new Integer(Integer.parseInt(p[i])));
            }
        }
        predictor = new int[idx.size()];
        int c = 0;
        for (Iterator<Integer> e = idx.iterator(); e.hasNext();) {
            predictor[c] = e.next().intValue() - 1;
            if (predictor[c] < 0) {
                System.err.println(
                        "bad parameter for option --" + cmd_covar_number_long + ": " + predictor[c] + ".");
                Test.LOG.append(
                        "bad parameter for option --" + cmd_covar_number_long + ": " + predictor[c] + ".\n");
                Test.printLog();
                System.exit(0);
            }
            c++;
        }
    }

    //      if (cl.hasOption(cmd_covar_name)) {
    //         HashSet<String> cn = NewIt.newHashSet();
    //         String[] p = cl.getOptionValues(cmd_covar_name);
    //         for (int i = 0; i < p.length; i++) {
    //            if (p[i].contains("-")) {
    //               String[] pp = predictor_name[i].split("-");
    //               if (pp.length != 2) {
    //                  System.err.println("bad parameter for option --" + cmd_covar_name_long + ": " + p[i] + ".");
    //                  Test.LOG.append("bad parameter for option --" + cmd_covar_name_long + ": " + p[i] + ".\n");
    //                  Test.printLog();
    //                  System.exit(0);
    //               }
    //               for (int j = 0; j < pp.length; j++) {
    //                  cn.add(pp[j]);
    //               }
    //            } else {
    //               cn.add(p[i]);
    //            }
    //         }
    //         predictor_name = (String[]) cn.toArray(new String[0]);
    //      }

    if (cl.hasOption(cmd_bgsnp)) {
        String[] bg = cl.getOptionValues(cmd_bgsnp);
        HashSet<String> bgSet = NewIt.newHashSet();
        for (int i = 0; i < bg.length; i++) {
            bgSet.add(bg[i]);
        }
        if (bgSet.size() != bg.length) {
            System.err.println("bad parameter for --" + cmd_bgsnp + ".");
            Test.LOG.append("bad parameter for --" + cmd_bgsnp + ".\n");
            Test.printLog();
            System.exit(0);
        }
        bgsnp = cl.getOptionValues(cmd_bgsnp);
        bgsnpFlag = true;
    }

    if (cl.hasOption(cmd_hg18)) {
        hg18Flag = true;
        hg19Flag = false;
        hgFile = "/gene36.txt";
    }

    if (cl.hasOption(cmd_hg19)) {
        hg19Flag = true;
        hg18Flag = false;
        hgFile = "/gene37.txt";
    }

    if (cl.hasOption(cmd_hg)) {
        hg19Flag = false;
        hg18Flag = false;
        hgFile = cl.getOptionValue(cmd_hg);
    }

    if (cl.hasOption(cmd_snp2genelist)) {
        snp2genefileFlag = true;
    }

    if (cl.hasOption(cmd_snp2genemlist)) {
        snp2genefilesFlag = true;
    }

    if (cl.hasOption(cmd_region)) {
        String[] r = cl.getOptionValues(cmd_region);
        ArrayList<String> chr = NewIt.newArrayList();
        ArrayList<String> b = NewIt.newArrayList();
        ArrayList<String> e = NewIt.newArrayList();

        for (int i = 0; i < r.length; i++) {
            String[] s = r[i].split(",");
            if (s.length != 3) {
                System.err.println("bad parameter for --" + cmd_region + ": " + r[i] + ".");
                Test.LOG.append("bad parameter for --" + cmd_region + ": " + r[i] + ".\n");
                Test.printLog();
                System.exit(0);
            }
            chr.add(s[0]);
            b.add(s[1]);
            e.add(s[2]);
        }
        chr_reg = (String[]) chr.toArray(new String[0]);
        begin = new double[b.size()];
        end = new double[e.size()];
        for (int i = 0; i < r.length; i++) {
            begin[i] = Double.parseDouble(b.get(i));
            end[i] = Double.parseDouble(e.get(i));
        }
        regionFlag = true;
    }

    if (cl.hasOption(cmd_gene_list)) {
        String gl = cl.getOptionValue(cmd_gene_list);

        File f = new File(gl);
        if (!f.exists()) {
            System.err.println("could not find file for --option " + cmd_gene_list_long + ": " + gl + ".");
            Test.LOG.append("could not find file for --option " + cmd_gene_list_long + ": " + gl + ".\n");
            Test.printLog();
            System.exit(0);
        }
        BufferedReader reader0 = null;
        try {
            reader0 = new BufferedReader(new FileReader(f));
        } catch (IOException E) {
            System.err.println("could not open gene list " + gl + ".");
            Test.LOG.append("could not open gene list " + gl + ".\n");
            Test.printLog();
            System.exit(0);
        }
        String line0 = null;
        HashSet<String> gSet = NewIt.newHashSet();
        try {
            while ((line0 = reader0.readLine()) != null) {
                String[] gn = line0.split(delim);
                gSet.add(gn[0]);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String[] g = (String[]) gSet.toArray(new String[0]);
        boolean[] gflag = new boolean[gSet.size()];
        Arrays.fill(gflag, false);
        ArrayList<String> ge = NewIt.newArrayList();
        ArrayList<String> g_chr = NewIt.newArrayList();
        ArrayList<String> g_begin = NewIt.newArrayList();
        ArrayList<String> g_end = NewIt.newArrayList();

        BufferedReader reader = null;
        if (hg18Flag || hg19Flag) {
            InputStream is = getClass().getResourceAsStream(hgFile);
            DataInputStream in = new DataInputStream(is);
            reader = new BufferedReader(new InputStreamReader(in));
        } else {
            File fhg = new File(hgFile);
            if (!fhg.exists()) {
                System.err.println("could not find file for --option " + cmd_hg + ": " + hgFile + ".");
                Test.LOG.append("could not find file for --option " + cmd_hg + ": " + hgFile + ".\n");
                Test.printLog();
                System.exit(0);
            }

            try {
                reader = new BufferedReader(new FileReader(fhg));
            } catch (IOException E) {
                System.err.println("could not open gene list " + hgFile + ".");
                Test.LOG.append("could not open gene list " + hgFile + ".\n");
                Test.printLog();
                System.exit(0);
            }

        }

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {

                String[] s = line.split("\\s+");
                //               System.err.println(line);
                if (s.length != 4) {
                    continue;
                }

                for (int i = 0; i < g.length; i++) {
                    if (s[0].compareTo(g[i]) == 0) {
                        ge.add(s[0]);
                        g_chr.add(s[1]);
                        g_begin.add(s[2]);
                        g_end.add(s[3]);
                        gflag[i] = true;
                    }
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean flag = true;
        int count = 0;
        for (int i = 0; i < gflag.length; i++) {
            if (!gflag[i]) {
                System.err.println("could not fine gene " + g[i] + ".");
                Test.LOG.append("could not find gene " + g[i] + ".\n");
                flag = false;
                count++;
            }
        }

        System.err.println("of " + gflag.length + " genes " + (gflag.length - count) + " was found.");
        Test.LOG.append("of " + gflag.length + " genes " + (gflag.length - count) + " was found.\n");

        if (!snp2genefileFlag && !snp2genefilesFlag) {
            if (!flag) {
                Test.printLog();
                System.exit(0);
            }
        }

        gene = (String[]) ge.toArray(new String[0]);
        gene_chr = (String[]) g_chr.toArray(new String[0]);
        gene_begin = new double[gene_chr.length];
        gene_end = new double[gene_chr.length];

        for (int i = 0; i < gene_chr.length; i++) {
            gene_begin[i] = Double.parseDouble(g_begin.get(i)) / 1000;
            gene_end[i] = Double.parseDouble(g_end.get(i)) / 1000;
            System.err.println(
                    gene[i] + ": chr" + gene_chr[i] + " " + gene_begin[i] + "k ~ " + gene_end[i] + "k.");
            Test.LOG.append(
                    gene[i] + ": chr" + gene_chr[i] + " " + gene_begin[i] + "k ~ " + gene_end[i] + "k.\n");
        }
        geneFlag = true;
    }

    if (cl.hasOption(cmd_gene_window)) {
        double gw = Double.parseDouble(cl.getOptionValue(cmd_gene_window));
        if (gw < 0) {
            System.err.println("bad parameter for option --" + cmd_gene_window_long + ": " + gw + ".");
            Test.LOG.append("bad parameter for option --" + cmd_gene_window_long + ": " + gw + ".\n");
            Test.printLog();
            System.exit(0);
        }
        genewindow = gw;
    }

    //      if (cl.hasOption(cmd_gene)) {
    //         String[] g = cl.getOptionValues(cmd_gene);
    //         boolean[] gflag = new boolean[g.length];
    //         Arrays.fill(gflag, false);
    //         ArrayList<String> ge = NewIt.newArrayList();
    //         ArrayList<String> g_chr = NewIt.newArrayList();
    //         ArrayList<String> g_begin = NewIt.newArrayList();
    //         ArrayList<String> g_end = NewIt.newArrayList();
    //         
    //         BufferedReader reader = null;
    //         if(hg18Flag || hg19Flag) {
    //            InputStream is = getClass().getResourceAsStream(hgFile);
    //            DataInputStream in = new DataInputStream(is);
    //            reader = new BufferedReader(new InputStreamReader(in));
    //         } else {
    //            File fhg = new File(hgFile);
    //            if (!fhg.exists()) {
    //               System.err.println("could not find file for --option " + cmd_hg + ": " + hgFile +".");
    //               Test.LOG.append("could not find file for --option " + cmd_hg + ": " + hgFile + ".\n");
    //               Test.printLog();
    //               System.exit(0);
    //            }
    //            try {
    //               reader = new BufferedReader(new FileReader(fhg));
    //            } catch (IOException E) {
    //               System.err.println("could not open gene list " + hgFile + ".");
    //               Test.LOG.append("could not open gene list " + hgFile + ".\n");
    //               Test.printLog();
    //               System.exit(0);
    //            }
    //
    //         }
    //
    //         String line = null;
    //         try {
    //            while ((line = reader.readLine()) != null) {
    //
    //               String[] s = line.split("\\s+");
    ////               System.err.println(line);
    //               if (s.length != 4) {
    //                  continue;
    //               }
    //
    //               for (int i = 0; i < g.length; i++) {
    //                  if (s[0].compareTo(g[i]) == 0) {
    //                     ge.add(s[0]);
    //                     g_chr.add(s[1]);
    //                     g_begin.add(s[2]);
    //                     g_end.add(s[3]);
    //                     gflag[i] = true;
    //                  }
    //               }
    //
    //            }
    //            reader.close();
    //         } catch (IOException e) {
    //            e.printStackTrace();
    //         }
    //         boolean flag = true;
    //         int count = 0;
    //         for(int i = 0; i < gflag.length; i++) {
    //            if(!gflag[i]) {
    //               System.err.println("could not find gene " + g[i] + ".");
    //               Test.LOG.append("could not find gene " + g[i] + ".\n");
    //               flag = false;
    //               count++;
    //            }
    //         }
    //         System.err.println("of " + gflag.length + " genes " + (gflag.length - count) + " was found.");
    //         Test.LOG.append("of " + gflag.length + " genes " + (gflag.length - count) + " was found.\n");
    //         if (!snp2genefileFlag && !snp2genefilesFlag) {
    //            if(!flag) {
    //               Test.printLog();
    //               System.exit(0);
    //            }
    //         }
    //
    //         gene = (String[]) ge.toArray(new String[0]);
    //         gene_chr = (String[]) g_chr.toArray(new String[0]);
    //         gene_begin = new double[gene_chr.length];
    //         gene_end = new double[gene_chr.length];
    //
    //         for (int i = 0; i < gene_chr.length; i++) {
    //            gene_begin[i] = Double.parseDouble(g_begin.get(i)) / 1000;
    //            gene_end[i] = Double.parseDouble(g_end.get(i)) / 1000;
    //            System.err.println(gene[i] + ": chr" + gene_chr[i] + " " +gene_begin[i] + "k ~ " + gene_end[i] + "k");
    //            Test.LOG.append(gene[i] + ": chr" + gene_chr[i] + " " +gene_begin[i] + "k ~ " + gene_end[i] + "k.\n");
    //         }
    //         geneFlag = true;
    //      }

    if (cl.hasOption(cmd_extract)) {

        if (!transFlag) {
            includesnpFile = cl.getOptionValues(cmd_extract);
            ArrayList<String> includesnpList = NewIt.newArrayList();
            for (int h = 0; h < includesnpFile.length; h++) {
                File f = new File(includesnpFile[h]);
                if (!f.exists()) {
                    System.err.println("could not find --" + cmd_extract + ": " + includesnpFile[h] + ".");
                    Test.LOG.append("could not fine --" + cmd_extract + ": " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                } catch (IOException E) {
                    System.err.println("could not read --" + cmd_extract + ": " + includesnpFile[h] + ".");
                    Test.LOG.append("could not read --" + cmd_extract + ": " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                ArrayList<String> snp = NewIt.newArrayList();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        String[] s = line.split(delim);
                        snp.add(s[0]);
                    }
                    reader.close();
                } catch (IOException E) {
                    System.err.println("bad lines in " + includesnpFile[h] + ".");
                    Test.LOG.append("bad lines in " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                if (snp.size() > 0) {
                    ArrayList<String> insnp = NewIt.newArrayList();
                    for (int i = 0; i < snp.size(); i++) {
                        String subSNP = snp.get(i);
                        insnp.add(subSNP);
                    }

                    if (insnp.size() > 0) {
                        includesnpList.addAll(insnp);
                        snpFlag = true;
                    }
                }
                if (includesnpList.size() > 0) {
                    includesnp = (String[]) includesnpList.toArray(new String[0]);
                }

            }
        } else {
            includesnpFile = cl.getOptionValues(cmd_extract);
            xincludesnp = new String[includesnpFile.length][];
            for (int h = 0; h < includesnpFile.length; h++) {
                File f = new File(includesnpFile[h]);
                if (!f.exists()) {
                    System.err.println("could not find " + includesnpFile[h] + ".");
                    Test.LOG.append("could not find " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                } catch (IOException E) {

                    System.err.println("could not read " + includesnpFile[h] + ".");
                    Test.LOG.append("could not read " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                ArrayList<String> snp = NewIt.newArrayList();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        String[] s = line.split(delim);
                        snp.add(s[0]);
                    }
                    reader.close();
                } catch (IOException E) {

                    System.err.println("bad lines in " + includesnpFile[h] + ".");
                    Test.LOG.append("bad lines in " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                if (snp.size() > 0) {
                    ArrayList<String> insnp = NewIt.newArrayList();

                    for (int i = 0; i < snp.size(); i++) {
                        String subSNP = snp.get(i);
                        insnp.add(subSNP);
                    }
                    if (insnp.size() > 0) {
                        xincludesnp[h] = (String[]) insnp.toArray(new String[0]);
                        snpFlag = true;
                    }
                }
            }
        }
    }

    if (cl.hasOption(cmd_exclude)) {

        if (!transFlag) {
            String snps_file = cl.getOptionValue(cmd_exclude);
            ArrayList<String> excludesnpList = NewIt.newArrayList();
            for (int h = 0; h < 1; h++) {
                File f = new File(snps_file);
                if (!f.exists()) {
                    System.err.println("could not find --" + cmd_extract + ": " + snps_file + ".");
                    Test.LOG.append("could not fine --" + cmd_extract + ": " + snps_file + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                } catch (IOException E) {
                    System.err.println("could not read --" + cmd_extract + ": " + snps_file + ".");
                    Test.LOG.append("could not read --" + cmd_extract + ": " + snps_file + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                ArrayList<String> snp = NewIt.newArrayList();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        String[] s = line.split(delim);
                        snp.add(s[0]);
                    }
                    reader.close();
                } catch (IOException E) {
                    System.err.println("bad lines in " + snps_file + ".");
                    Test.LOG.append("bad lines in " + snps_file + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                if (snp.size() > 0) {
                    ArrayList<String> exsnp = NewIt.newArrayList();
                    for (int i = 0; i < snp.size(); i++) {
                        String subSNP = snp.get(i);
                        exsnp.add(subSNP);
                    }
                    if (exsnp.size() > 0) {
                        excludesnpList.addAll(exsnp);
                        snpFlag = true;
                    }
                }
                if (excludesnpList.size() > 0) {
                    excludesnp = (String[]) excludesnpList.toArray(new String[0]);
                }
            }
        }

    }

    if (cl.hasOption(cmd_keep_male)) {
        keep_maleFlag = true;
    }
    if (cl.hasOption(cmd_keep_female)) {
        keep_femaleFlag = true;
    }
    if (cl.hasOption(cmd_ex_nosex)) {
        ex_nosexFlag = true;
    }
    if (cl.hasOption(cmd_remove)) {
        String file = cl.getOptionValue(cmd_remove);
        File f = new File(file);
        if (!f.exists()) {
            System.err.println("could not open " + file + ".");
            Test.LOG.append("could not open " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File(file)));
        } catch (IOException E) {
            System.err.println("could not read " + file + ".");
            Test.LOG.append("coudl not read " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        ArrayList<String> famList = NewIt.newArrayList();
        ArrayList<String> indList = NewIt.newArrayList();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                String[] l = line.split(MDRConstant.delim);
                if (l.length < 2)
                    continue;
                famList.add(l[0]);
                indList.add(l[1]);
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
        ex_family = new String[2][];
        ex_family[0] = (String[]) famList.toArray(new String[0]);
        ex_family[1] = (String[]) indList.toArray(new String[0]);
        removeFlag = true;
    }

    if (cl.hasOption(cmd_keep)) {
        String file = cl.getOptionValue(cmd_keep);
        File f = new File(file);
        if (!f.exists()) {
            System.err.println("could not open " + file + ".");
            Test.LOG.append("could not open " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File(file)));
        } catch (IOException E) {
            System.err.println("could not read " + file + ".");
            Test.LOG.append("coudl not read " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        ArrayList<String> famList = NewIt.newArrayList();
        ArrayList<String> indList = NewIt.newArrayList();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                String[] l = line.split(MDRConstant.delim);
                if (l.length < 2)
                    continue;
                famList.add(l[0]);
                indList.add(l[1]);
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
        indKeep = new String[2][];
        indKeep[0] = (String[]) famList.toArray(new String[0]);
        indKeep[1] = (String[]) indList.toArray(new String[0]);
        keepFlag = true;
    }

    if (cl.hasOption(cmd_chr)) {

        String[] chr = cl.getOptionValues(cmd_chr);
        HashSet<String> chrSet = NewIt.newHashSet();
        HashSet<String> exSet = NewIt.newHashSet();
        for (int i = 0; i < chr.length; i++) {
            if (chr[i].startsWith("-")) {
                exSet.add(chr[i].substring(1, chr[i].length()));
            } else {
                chrSet.add(chr[i]);
            }
        }
        if (chr.length != chrSet.size() + exSet.size()) {
            System.err.println("bad parameter for optin --" + cmd_chr + ".");
            Test.LOG.append("bad parameter for option --" + cmd_chr + ".\n");
            Test.printLog();
            System.exit(0);
        }
        if (chrSet.size() > 0) {
            in_chr = (String[]) chrSet.toArray(new String[0]);
            inchrFlag = true;
        }
        if (exSet.size() > 0) {
            ex_chr = (String[]) exSet.toArray(new String[0]);
            exchrFlag = true;
        }
    }

    if (cl.hasOption(cmd_snpwindow)) {
        String[] s = cl.getOptionValues(cmd_snpwindow);
        snpwindow = new String[s.length];
        snp_window = new double[s.length][2];
        for (int i = 0; i < s.length; i++) {
            String[] ss = s[i].split(incommand_separator);
            if (ss.length != 3) {
                System.err.println("bad parameter for optin --" + cmd_snpwindow_long + " " + s[i] + ".");
                Test.LOG.append("bad parameter for option --" + cmd_snpwindow_long + " " + s[i] + ".\n");
                Test.printLog();
                System.exit(0);
            }
            snpwindow[i] = ss[0];
            snp_window[i][0] = Double.parseDouble(ss[1]) * -1000;
            if (Double.parseDouble(ss[2]) > 0) {
                snp_window[i][1] = Double.parseDouble(ss[2]) * 1000;
            } else {
                snp_window[i][1] = Double.MAX_VALUE;
            }
        }
        snpwindowFlag = true;
    }

    if (cl.hasOption(cmd_maf)) {
        maf = Double.parseDouble(cl.getOptionValue(cmd_maf));
        if (maf < 0) {

            System.err.println("bad parameter for optin --" + cmd_maf + " " + maf + ".");
            Test.LOG.append("bad parameter for option --" + cmd_maf + " " + maf + ".\n");
            Test.printLog();
            System.exit(0);
        }
        mafFlag = true;
    }

    if (cl.hasOption(cmd_max_maf)) {
        max_maf = Double.parseDouble(cl.getOptionValue(cmd_max_maf));
        if (max_maf < 0) {
            System.err.println("bad parameter for optin --" + cmd_max_maf_long + " " + max_maf + ".");
            Test.LOG.append("bad parameter for option --" + cmd_max_maf_long + " " + max_maf + ".\n");
            Test.printLog();
            System.exit(0);
        }
        maxmafFlag = true;
    }

    if (cl.hasOption(cmd_geno)) {
        geno = Double.parseDouble(cl.getOptionValue(cmd_geno));
        if (geno < 0) {

            System.err.println("bad parameter for optin --" + cmd_geno + " " + geno + ".");
            Test.LOG.append("bad parameter for option --" + cmd_geno + " " + geno + ".\n");
            Test.printLog();
            System.exit(0);
        }
        genoFlag = true;
    }
    //
    // if (cl.hasOption(cmd_hwe)) {
    // hwe = Double.parseDouble(cl.getOptionValue(cmd_hwe));
    // if (hwe < 0) {
    // throw new IllegalArgumentException("bad parameter for --hwe: " +
    // hwe);
    // }
    // hweFlag = true;
    // }

    //      if (cl.hasOption(cmd_reg)) {
    //         linkfunction = Integer.parseInt(cl.getOptionValue(cmd_reg));
    //      }
    if (cl.hasOption(cmd_cv)) {
        cv = Integer.parseInt(cl.getOptionValue(cmd_cv));
        if (cv < 2) {

            System.err.println("bad parameter for optin --" + cmd_cv + " " + cv + ".");
            Test.LOG.append("bad parameter for option --" + cmd_cv + " " + cv + ".\n");
            Test.printLog();
            System.exit(0);
        }
        cvFlag = true;
    }
    // if (cl.hasOption(cmd_trgroup)) {
    // trgroup = Double.parseDouble(cl.getOptionValue(cmd_trgroup));
    // trgroupFlag = true;
    // }
    // if (cl.hasOption(cmd_trsex)) {
    // trsex = Integer.parseInt(cl.getOptionValue(cmd_trsex));
    // if (trsex != 1 && trsex != 2) {
    // throw new
    // IllegalArgumentException("unknown value for option --trsex.");
    // }
    // trsexFlag = true;
    // }
    // if (cl.hasOption(cmd_ttfile)) {
    // String tf = cl.getOptionValue(cmd_ttfile);
    // File ttfile = new File(tf);
    // if (!ttfile.exists()) {
    // throw new IllegalArgumentException("could not open ttfile " + tf);
    // }
    //
    // ArrayList<String> Farray = NewIt.newArrayList();
    // ArrayList<String> Iarray = NewIt.newArrayList();
    // BufferedReader reader = null;
    // try {
    // reader = new BufferedReader(new FileReader(new File(tf)));
    // } catch (IOException E) {
    // throw new IllegalArgumentException("failed in reading " + tf);
    // }
    // String line = null;
    // try {
    // while ((line = reader.readLine()) != null) {
    // String[] l = line.split(delim);
    // Farray.add(l[0]);
    // Iarray.add(l[1]);
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    //
    // ttArray = new String[2][Farray.size()];
    // ttArray[0] = (String[]) Farray.toArray(new String[0]);
    // ttArray[1] = (String[]) Iarray.toArray(new String[0]);
    // ttfileFlag = true;
    // }
    // if (cl.hasOption(cmd_border)) {
    // String[] h = cl.getOptionValues(cmd_border);
    // if (h.length != 2) {
    // throw new
    // IllegalArgumentException("bad parameter for option --border.");
    // }
    // boolean rflag = false;
    // if (h[0].startsWith("-")) {
    // border_fid = h[0].substring(1, h[0].length());
    // rflag = true;
    // } else {
    // border_fid = h[0];
    // }
    // if (h[1].startsWith("-")) {
    // border_iid = h[1].substring(1, h[1].length());
    // rflag = true;
    // } else {
    // border_iid = h[1];
    // }
    // borderFlag = true;
    // reverseborderFlag = rflag;
    // }
    if (cl.hasOption(cmd_seed)) {
        seed = Integer.parseInt(cl.getOptionValue(cmd_seed));
    }
    if (cl.hasOption(cmd_tie)) {
        String t = cl.getOptionValue(cmd_tie);
        if (t.compareTo("h") == 0) {
            tie = 1;
        } else if (t.compareTo("l") == 0) {
            tie = 0;
        } else {
            tie = -1;
        }
    }
    // if (cl.hasOption(cmd_simu)) {
    // simu = Integer.parseInt(cl.getOptionValue(cmd_simu));
    // }
    if (cl.hasOption(cmd_perm)) {
        perm = Integer.parseInt(cl.getOptionValue(cmd_perm));
        permFlag = true;
    }
    /*
    if (cl.hasOption(cmd_ep)) {
       ep = Double.parseDouble(cl.getOptionValue(cmd_ep));
       if (ep >= 1 || ep < 0) {
            
    System.err.println("bad parameter for optin --" + ep + " " + ep + ".");
    Test.LOG.append("bad parameter for option --" + ep + " " + ep + ".\n");
    Test.printLog();
    System.exit(0);
       }
       epFlag = true;
    }
    */
    // if (cl.hasOption(cmd_perm_scheme)) {
    // permu_scheme = true;
    // }
    // if (cl.hasOption(cmd_unrelated_only)) {
    // unrelated_only = true;
    // }
    if (cl.hasOption(cmd_order)) {
        order = Integer.parseInt(cl.getOptionValue(cmd_order));
    }
    if (cl.hasOption(cmd_thin)) {
        thin = Double.parseDouble(cl.getOptionValue(cmd_thin));
        if (thin < 0) {

            System.err.println("bad parameter for optin --" + cmd_thin + " " + thin + ".");
            Test.LOG.append("bad parameter for option --" + cmd_thin + " " + thin + ".\n");
            Test.printLog();
            System.exit(0);
        }
    }
    if (cl.hasOption(cmd_slice)) {
        String[] s = cl.getOptionValue(cmd_slice).split("/");
        slice = Integer.parseInt(s[0]);
        sliceN = Integer.parseInt(s[1]);
        if (slice <= 0 || sliceN <= 0 || slice > sliceN) {

            System.err.println("bad parameter for optin --" + cmd_slice + " " + slice + ".");
            Test.LOG.append("bad parameter for option --" + cmd_slice + " " + slice + ".\n");
            Test.printLog();
            System.exit(0);
        }
        sliceFlag = true;
    }
    if (cl.hasOption(cmd_missing_phenotype)) {
        String[] s = cl.getOptionValues(cmd_missing_phenotype);
        na = s;
        //         missing_phenotype = cl.getOptionValue(cmd_missing_phenotype);
    }
    // if (cl.hasOption(cmd_missing_genotype)) {
    // missing_genotype = cl.getOptionValue(cmd_missing_genotype);
    // }
    if (cl.hasOption(cmd_missing_allele)) {
        missing_allele = cl.getOptionValue(cmd_missing_allele);
    }
    if (cl.hasOption(cmd_status_shift)) {
        status_shift = 0;
        status_shiftFlag = true;
    }
    /*
    if (cl.hasOption(cmd_Vc)) {
       vc = Double.parseDouble(cl.getOptionValue(cmd_Vc));
       vcFlag = true;
    }
    if (cl.hasOption(cmd_training)) {
       threshold_training = Double.parseDouble(cl
       .getOptionValue(cmd_training));
       trainingFlag = true;
    }
    if (cl.hasOption(cmd_testing)) {
       threshold_testing = Double.parseDouble(cl
       .getOptionValue(cmd_testing));
       testingFlag = true;
    }
    */
    if (cl.hasOption(cmd_version)) {
        System.err.println();
        Test.printLog();
        System.exit(1);
    }
    if (cl.hasOption(cmd_testdrive)) {
        testdrive = true;
    }
    if (cl.hasOption(cmd_node)) {
        node = Integer.parseInt(cl.getOptionValue(cmd_node));
        nodeFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_email)) {
        email = cl.getOptionValue(cmd_email);
        emailFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_memory)) {
        memory = cl.getOptionValue(cmd_memory);
        memoryFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_walltime)) {
        walltime = Integer.parseInt(cl.getOptionValue(cmd_walltime));
        walltimeFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_submit)) {
        submit = true;
        clusterFlag = true;
    }
    if (help) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("UGMDR", ops);
        System.exit(1);
    }

}

From source file:org.prom5.analysis.petrinet.cpnexport.HLToCPNTranslator.java

private void generateFrequencyDependencySubpage(ColoredTransition transition) {
    // in the case that the incoming place of the transition is a decision place,
    // calculate the gcd of the frequency dependencies that are attached to the
    // outgoing transitions of that decision place

    HLActivity act = highLevelPN.findActivity(transition);
    ArrayList<HLChoice> choices = highLevelPN.getHLProcess().getChoicesForTargetActivity(act.getID());
    // TODO: now only take first choice (and assume that the others would be consistent)
    // However, it might be that different frequencies are given for this activity for different choices
    // The cpn export currently does not deal with this - needs global normalization if required
    HLChoice choice = choices.get(0);/*  ww  w.  ja v a  2s  . c om*/
    // calculate the gcd for the frequencydependencies in transitionsFreqDep
    int gcd = 1;
    boolean start = true;
    Iterator<HLCondition> conditions = choice.getConditions().iterator();
    while (conditions.hasNext()) {
        HLCondition cond1 = conditions.next();
        if (start && conditions.hasNext()) {
            HLCondition cond2 = conditions.next();
            int freq1 = cond1.getFrequency();
            int freq2 = cond2.getFrequency();
            gcd = org.apache.commons.math.util.MathUtils.gcd(freq1, freq2);
            start = false;
        } else {
            gcd = org.apache.commons.math.util.MathUtils.gcd(gcd, cond1.getFrequency());
        }
    }
    SubpageMapping oldMapping = transition.getSubpageMapping();
    ColoredPetriNet oldSubpage = transition.getSubpage();
    // Generate subpage between the already existing subpage for this transition
    ColoredPetriNet subpage = new ColoredPetriNet();
    subpage.setIdentifier("Frequency_dependency_" + transition.getIdentifier());
    subpage.setCpnID(ManagerID.getNewID());
    // Generate an input and an output place for each input and output place of transition
    SubpageMapping mappingFromSubpageToTop = new SubpageMapping();
    mappingFromSubpageToTop.setSubPageID(subpage.getCpnID());

    HashSet inputPlacesSubpage = new HashSet<ColoredPlace>();
    HashSet outputPlacesSubpage = new HashSet<ColoredPlace>();

    Iterator inputPlaces = transition.getVerticesOnlyPredecessor().iterator();
    while (inputPlaces.hasNext()) {
        ColoredPlace top = (ColoredPlace) inputPlaces.next();
        ColoredPlace sub = new ColoredPlace(top.getIdentifier(), subpage);
        // the type of the top and sub place needs to be the same
        sub.setPlaceType(top.getPlaceType());
        subpage.addPlace(sub);
        inputPlacesSubpage.add(sub);
        mappingFromSubpageToTop.addMapping(sub, top);
    }
    // the same for the output places
    Iterator outputPlaces = transition.getVerticesOnlySuccessor().iterator();
    while (outputPlaces.hasNext()) {
        ColoredPlace top = (ColoredPlace) outputPlaces.next();
        ColoredPlace sub = new ColoredPlace(top.getIdentifier(), subpage);
        // the type of the top and sub place needs to be the same
        sub.setPlaceType(top.getPlaceType());
        subpage.addPlace(sub);
        outputPlacesSubpage.add(sub);
        mappingFromSubpageToTop.addMapping(sub, top);
    }
    // the same for the places that are both output and input
    Iterator inputOutputPlaces = transition.getVerticesPredecessorAndSuccessor().iterator();
    while (inputOutputPlaces.hasNext()) {
        ColoredPlace top = (ColoredPlace) inputOutputPlaces.next();
        ColoredPlace sub = new ColoredPlace(top.getIdentifier(), subpage);
        // the type of the top and sub place needs to be the same
        sub.setPlaceType(top.getPlaceType());
        subpage.addPlace(sub);
        inputPlacesSubpage.add(sub);
        outputPlacesSubpage.add(sub);
        mappingFromSubpageToTop.addMapping(sub, top);
    }

    transition.setSubpageMapping(mappingFromSubpageToTop);
    transition.setSubpage(subpage);

    // The number of the generated transitions on the subpage equals the frequency dependency
    // that has been set for the transition. Furthermore, ensure that each generated transition
    // is connected correctly with the input and output places
    HLCondition cond = choice.getCondition(act.getID());
    for (int i = 0; i < ((cond.getFrequency()) / gcd); i++) {
        ColoredTransition generatedTransition = new ColoredTransition(transition.getIdentifier() + (i + 1),
                subpage);
        subpage.addTransition(generatedTransition);
        Iterator<ColoredPlace> subPageInputPlaces = inputPlacesSubpage.iterator();
        while (subPageInputPlaces.hasNext()) {
            ColoredPlace inputSubpage = subPageInputPlaces.next();
            // connect with generatedTransition
            ColoredEdge edge = new ColoredEdge(inputSubpage, generatedTransition);
            subpage.addEdge(edge);
        }
        Iterator<ColoredPlace> subPageOutputPlaces = outputPlacesSubpage.iterator();
        while (subPageOutputPlaces.hasNext()) {
            ColoredPlace outputSubpage = subPageOutputPlaces.next();
            // connect with generatedTransition
            ColoredEdge edge = new ColoredEdge(generatedTransition, outputSubpage);
            subpage.addEdge(edge);
        }

        // ensure that the generatedTransition is pointing to the correct subpage and that
        // the mapping is correct
        generatedTransition.setSubpage(oldSubpage);
        SubpageMapping newMapping = new SubpageMapping();
        generatedTransition.setSubpageMapping(newMapping);
        newMapping.setSubPageID(oldMapping.getSubPageID());
        // fix the mappings
        Iterator<Place> placesSub = oldSubpage.getPlaces().iterator();
        while (placesSub.hasNext()) {
            ColoredPlace placeSub = (ColoredPlace) placesSub.next();
            // Get the mapping that belongs to this place, if existing
            SubpageMapping.Mapping oldMappingForSubPlace = oldMapping.getMappingForSubPlace(placeSub);
            if (oldMappingForSubPlace != null) {
                ColoredPlace topPlace = oldMappingForSubPlace.second();
                SubpageMapping.Mapping mappingTopToSubpageForPlace = mappingFromSubpageToTop
                        .getMappingForTopPlace(topPlace);
                newMapping.addMapping(placeSub, mappingTopToSubpageForPlace.first());
            }
        }
    }
    subpage.generateCpnIDs();
    // generate the layout of the subpage
    generateLayoutHierarchicalPN(subpage, false);
}

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public Vector hashSet2Vector(HashSet hset) {
    if (hset == null)
        return null;
    Vector v = new Vector();
    Iterator it = hset.iterator();
    while (it.hasNext()) {
        String t = (String) it.next();
        v.add(t);/*from www  .  j  av  a 2 s  .c  o m*/
    }
    return v;
}

From source file:org.unitime.timetable.solver.TimetableDatabaseLoader.java

private void propagateCommittedAssignment(HashSet students, Class_ parent, Class_ clazz) {
    Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId());
    if (lecture != null && !lecture.isCommitted()) {
        //iProgress.debug("[B] Students "+students+" cannot enroll "+lecture.getName()+" due to the enrollment of "+parent.getClassLabel());
        for (Iterator i = students.iterator(); i.hasNext();) {
            Student student = (Student) i.next();
            student.addCanNotEnroll(lecture);
        }/* ww  w  .j ava  2s .  c  om*/
    } else {
        for (Iterator i = clazz.getChildClasses().iterator(); i.hasNext();) {
            Class_ child = (Class_) i.next();
            propagateCommittedAssignment(students, parent, child);
        }
    }
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryObjectCollectionBean.java

/**
* Checks if composed object being saved already exists else it is new.
* 
* @param none//  ww  w .j  a va2s  . c  o m
* @return boolean
*/
private boolean isComposedObjectNew() {
    boolean isNew = true;
    try {
        Object composedObject = currentComposedRegistryObject.getNonRegistryObject();
        if (composedObject == null) {
            composedObject = currentComposedRegistryObject.getRegistryObject();
        }
        HashSet<?> composedObjects = ((RegistryObjectImpl) currentRegistryObject.getRegistryObject())
                .getComposedObjects();

        Iterator<?> iter = composedObjects.iterator();
        while (!currentComposedRegistryObject.isNew() && iter.hasNext()) {
            Object existingComposedObject = iter.next();
            if (existingComposedObject == composedObject) {
                isNew = false;
                break;
            }
        }

    } catch (Exception je) {
        log.error(WebUIResourceBundle.getInstance().getString("message.ErrorDeterminingIfComposedObjectIsNew"),
                je);
    }
    return isNew;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.author.ItemAddListener.java

private void preparePublishedTextForMatching(ItemFacade item, ItemBean bean, ItemService delegate) {
    Set textSet = item.getItemTextSet();
    Iterator textIter = textSet.iterator();
    HashMap itemTextMap = new HashMap();
    while (textIter.hasNext()) {
        ItemTextIfc itemText = (ItemTextIfc) textIter.next();
        itemTextMap.put(itemText.getSequence(), itemText);
    }/* w ww .j  a  v  a  2s. c o m*/

    // looping through matchItemBean
    ArrayList matchItemBeanList = bean.getMatchItemBeanList();
    Iterator choiceIter = matchItemBeanList.iterator();

    Set answerSet = null;
    ItemTextIfc itemText = null;
    AnswerIfc answer = null;
    MatchItemBean choiceBean = null;
    MatchItemBean matchBean = null;
    Long choiceSequence = null;
    Long matchSequence = null;

    while (choiceIter.hasNext()) {
        choiceBean = (MatchItemBean) choiceIter.next();
        choiceSequence = choiceBean.getSequence();
        if (itemTextMap.get(choiceSequence) == null) {
            // new - add it in
            itemText = new PublishedItemText();
            itemText.setItem(item.getData());
            itemText.setSequence(choiceBean.getSequence());
            itemText.setText(stripPtags(choiceBean.getChoice()));
        } else {
            itemText = (ItemTextIfc) itemTextMap.get(choiceSequence);
            itemText.setText(choiceBean.getChoice());
        }
        HashMap answerMap = new HashMap();
        answerSet = itemText.getAnswerSet();
        if (answerSet != null) {
            Iterator answerIter = answerSet.iterator();
            while (answerIter.hasNext()) {
                answer = (AnswerIfc) answerIter.next();
                answerMap.put(answer.getSequence(), answer);
            }
        } else {
            answerSet = new HashSet();
            itemText.setAnswerSet(answerSet);
            textSet.add(itemText);
        }
        Iterator matchIter = matchItemBeanList.iterator();
        while (matchIter.hasNext()) {
            matchBean = (MatchItemBean) matchIter.next();
            matchSequence = matchBean.getSequence();
            if (answerMap.get(matchSequence) == null) {
                // new - add it in
                if (matchBean.getSequence().equals(choiceBean.getSequence())) {
                    answer = new PublishedAnswer(itemText, stripPtags(matchBean.getMatch()),
                            matchBean.getSequence(),
                            AnswerBean.getChoiceLabels()[matchBean.getSequence().intValue() - 1], Boolean.TRUE,
                            null, new Double(bean.getItemScore()), null,
                            Double.valueOf(bean.getItemDiscount()));
                } else {
                    answer = new PublishedAnswer(itemText, stripPtags(matchBean.getMatch()),
                            matchBean.getSequence(),
                            AnswerBean.getChoiceLabels()[matchBean.getSequence().intValue() - 1], Boolean.FALSE,
                            null, new Double(bean.getItemScore()), null,
                            Double.valueOf(bean.getItemDiscount()));
                }

                // record answers for all combination of pairs
                HashSet answerFeedbackSet = new HashSet();
                answerFeedbackSet.add(new PublishedAnswerFeedback(answer, AnswerFeedbackIfc.CORRECT_FEEDBACK,
                        stripPtags(matchBean.getCorrMatchFeedback())));
                answerFeedbackSet.add(new PublishedAnswerFeedback(answer, AnswerFeedbackIfc.INCORRECT_FEEDBACK,
                        stripPtags(matchBean.getIncorrMatchFeedback())));
                answer.setAnswerFeedbackSet(answerFeedbackSet);
                answerSet.add(answer);

            } else {
                answer = (AnswerIfc) answerMap.get(matchSequence);
                answer.setScore(Double.valueOf(bean.getItemScore()));
                String oneAnswer = stripPtags(matchBean.getMatch());
                String oneLabel = AnswerBean.getChoiceLabels()[matchSequence.intValue() - 1];
                log.debug("oneAnswer = " + oneAnswer);
                log.debug("oneLabel = " + oneLabel);
                answer.setText(oneAnswer);
                answer.setLabel(oneLabel);
                if (choiceSequence.longValue() == matchSequence.longValue()) {
                    answer.setIsCorrect(Boolean.TRUE);
                } else {
                    answer.setIsCorrect(Boolean.FALSE);
                }
                Set answerFeedbackSet = answer.getAnswerFeedbackSet();
                Iterator answerFeedbackIter = answerFeedbackSet.iterator();
                String feedback = "";
                while (answerFeedbackIter.hasNext()) {
                    AnswerFeedbackIfc answerFeedback = (AnswerFeedbackIfc) answerFeedbackIter.next();
                    if (answerFeedback.getTypeId().equals(AnswerFeedbackIfc.CORRECT_FEEDBACK)) {
                        answerFeedback.setText(stripPtags(matchBean.getCorrMatchFeedback()));
                    } else if (answerFeedback.getTypeId().equals(AnswerFeedbackIfc.INCORRECT_FEEDBACK)) {
                        answerFeedback.setText(stripPtags(matchBean.getIncorrMatchFeedback()));
                    }
                }
            }
        }
    }

    int oldSize = textSet.size();
    int newSize = matchItemBeanList.size();
    if (oldSize > newSize) {
        HashSet toBeRemovedTextSet = new HashSet();
        HashSet toBeRemovedAnswerSet = new HashSet();
        // Need to remove from answer too
        for (int i = 1; i < newSize + 1; i++) {
            ItemTextIfc text = (ItemTextIfc) itemTextMap.get(Long.valueOf(i));
            answerSet = text.getAnswerSet();
            if (answerSet != null) {
                Iterator answerIter = answerSet.iterator();
                while (answerIter.hasNext()) {
                    answer = (AnswerIfc) answerIter.next();
                    for (int j = newSize + 1; j < oldSize + 1; j++) {
                        if (answer.getSequence().intValue() == j) {
                            toBeRemovedAnswerSet.add(answer);
                        }
                    }
                }
                answerSet.removeAll(toBeRemovedAnswerSet);
                delegate.deleteSet(toBeRemovedAnswerSet);
            }
        }
        for (int i = newSize + 1; i < oldSize + 1; i++) {
            ItemTextIfc text = (ItemTextIfc) itemTextMap.get(Long.valueOf(i));
            toBeRemovedTextSet.add(text);
        }
        textSet.removeAll(toBeRemovedTextSet);
        delegate.deleteSet(toBeRemovedTextSet);
    }
}

From source file:org.openmeetings.servlet.outputhandler.BackupImportController.java

@SuppressWarnings("unchecked")
private void getUsersByXML(File userFile) {
    try {/*from  w  w  w  .  j  a  v a 2 s.c om*/

        SAXReader reader = new SAXReader();
        Document document = reader.read(userFile);

        Element root = document.getRootElement();

        for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
            Element itemObject = i.next();
            if (itemObject.getName().equals("users")) {

                for (Iterator<Element> innerIter = itemObject.elementIterator("user"); innerIter.hasNext();) {

                    Element itemUsers = innerIter.next();

                    Users us = new Users();
                    Long userId = Long.valueOf(unformatString(itemUsers.element("user_id").getText()));

                    us.setAge(CalendarPatterns
                            .parseImportDate(unformatString(itemUsers.element("age").getText())));
                    us.setAvailible(
                            importIntegerType(unformatString(itemUsers.element("availible").getText())));
                    us.setDeleted(unformatString(itemUsers.element("deleted").getText()));
                    us.setFirstname(unformatString(itemUsers.element("firstname").getText()));
                    us.setLastname(unformatString(itemUsers.element("lastname").getText()));
                    us.setLogin(unformatString(itemUsers.element("login").getText()));
                    us.setPassword(unformatString(itemUsers.element("pass").getText()));
                    us.setDeleted(itemUsers.element("deleted").getText());

                    if (itemUsers.element("activatehash") != null) {
                        us.setActivatehash(unformatString(itemUsers.element("activatehash").getText()));
                    } else {
                        us.setActivatehash("");
                    }
                    if (itemUsers.element("externalUserType") != null) {
                        us.setExternalUserType(unformatString(itemUsers.element("externalUserType").getText()));
                    } else {
                        us.setExternalUserType("");
                    }
                    if (itemUsers.element("externalUserId") != null) {
                        us.setExternalUserId(unformatString(itemUsers.element("externalUserId").getText()));
                    } else {
                        us.setExternalUserId(null);
                    }
                    if (itemUsers.element("resethash") != null) {
                        us.setResethash(unformatString(itemUsers.element("resethash").getText()));
                    } else {
                        us.setResethash(null);
                    }
                    if (itemUsers.element("userOffers") != null) {
                        us.setUserOffers(unformatString(itemUsers.element("userOffers").getText()));
                    } else {
                        us.setUserOffers("");
                    }
                    if (itemUsers.element("userSearchs") != null) {
                        us.setUserSearchs(unformatString(itemUsers.element("userSearchs").getText()));
                    } else {
                        us.setUserSearchs("");
                    }
                    if (itemUsers.element("forceTimeZoneCheck") != null) {
                        us.setForceTimeZoneCheck(importBooleanType(
                                unformatString(itemUsers.element("forceTimeZoneCheck").getText())));
                    } else {
                        us.setForceTimeZoneCheck(null);
                    }
                    if (itemUsers.element("lasttrans") != null) {
                        us.setLasttrans(
                                importLongType(unformatString(itemUsers.element("lasttrans").getText())));
                    } else {
                        us.setLasttrans(null);
                    }
                    if (itemUsers.element("showContactData") != null) {
                        us.setShowContactData(importBooleanType(
                                unformatString(itemUsers.element("showContactData").getText())));
                    } else {
                        us.setShowContactData(null);
                    }
                    if (itemUsers.element("showContactDataToContacts") != null) {
                        us.setShowContactDataToContacts(importBooleanType(
                                unformatString(itemUsers.element("showContactDataToContacts").getText())));
                    } else {
                        us.setShowContactDataToContacts(null);
                    }

                    us.setPictureuri(unformatString(itemUsers.element("pictureuri").getText()));
                    if (unformatString(itemUsers.element("language_id").getText()).length() > 0)
                        us.setLanguage_id(
                                Long.valueOf(unformatString(itemUsers.element("language_id").getText())));

                    us.setStatus(importIntegerType(unformatString(itemUsers.element("status").getText())));
                    us.setRegdate(CalendarPatterns
                            .parseImportDate(unformatString(itemUsers.element("regdate").getText())));
                    us.setTitle_id(importIntegerType(unformatString(itemUsers.element("title_id").getText())));
                    us.setLevel_id(importLongType(unformatString(itemUsers.element("level_id").getText())));

                    // UserSIP Data
                    if (itemUsers.element("sip_username") != null && itemUsers.element("sip_userpass") != null
                            && itemUsers.element("sip_authid") != null) {
                        UserSipData userSipData = new UserSipData();
                        userSipData.setUsername(unformatString(itemUsers.element("sip_username").getText()));
                        userSipData.setUsername(unformatString(itemUsers.element("sip_userpass").getText()));
                        userSipData.setUsername(unformatString(itemUsers.element("sip_authid").getText()));
                        us.setUserSipData(userSipData);
                    }

                    String additionalname = unformatString(itemUsers.element("additionalname").getText());
                    String comment = unformatString(itemUsers.element("comment").getText());
                    // A User can not have a deleted Adress, you cannot
                    // delete the
                    // Adress of an User
                    // String deleted = u.getAdresses().getDeleted()
                    // Phone Number not done yet
                    String fax = unformatString(itemUsers.element("fax").getText());
                    Long state_id = importLongType(unformatString(itemUsers.element("state_id").getText()));
                    String street = unformatString(itemUsers.element("street").getText());
                    String town = unformatString(itemUsers.element("town").getText());
                    String zip = unformatString(itemUsers.element("zip").getText());

                    if (itemUsers.element("omTimeZone") != null) {
                        OmTimeZone omTimeZone = omTimeZoneDaoImpl
                                .getOmTimeZone(unformatString(itemUsers.element("omTimeZone").getText()));

                        us.setOmTimeZone(omTimeZone);
                        us.setForceTimeZoneCheck(false);
                    } else {

                        String jNameTimeZone = cfgManagement.getConfValue("default.timezone", String.class,
                                "Europe/Berlin");
                        OmTimeZone omTimeZone = omTimeZoneDaoImpl.getOmTimeZone(jNameTimeZone);
                        us.setOmTimeZone(omTimeZone);
                        us.setForceTimeZoneCheck(true);
                    }

                    String phone = "";
                    if (itemUsers.element("phone") != null) {
                        phone = unformatString(itemUsers.element("phone").getText());
                    }

                    String email = "";
                    if (itemUsers.element("mail") != null) {
                        email = unformatString(itemUsers.element("mail").getText());
                    }

                    States st = statemanagement.getStateById(state_id);
                    if (st == null) {
                        st = statemanagement.getStateById(1L);
                    }

                    us.setAdresses(street, zip, town, st, additionalname, comment, fax, phone, email);

                    HashSet<Organisation_Users> orgUsers = new HashSet<Organisation_Users>();

                    for (Iterator<Element> organisationsIterator = itemUsers
                            .elementIterator("organisations"); organisationsIterator.hasNext();) {

                        Element organisations = organisationsIterator.next();

                        for (Iterator<Element> organisationIterator = organisations
                                .elementIterator("user_organisation"); organisationIterator.hasNext();) {

                            Element organisationObject = organisationIterator.next();

                            Long organisation_id = getNewId(
                                    importLongType(unformatString(
                                            organisationObject.element("organisation_id").getText())),
                                    Maps.ORGANISATIONS);
                            Boolean isModerator = importBooleanType(
                                    unformatString(organisationObject.element("isModerator").getText()));
                            String deleted = unformatString(organisationObject.element("deleted").getText());

                            Organisation_Users orgUser = new Organisation_Users();
                            orgUser.setOrganisation(
                                    organisationmanagement.getOrganisationByIdBackup(organisation_id));
                            orgUser.setIsModerator(isModerator);
                            orgUser.setStarttime(new Date());
                            orgUser.setDeleted(deleted);

                            orgUsers.add(orgUser);

                        }

                    }

                    log.debug("Import User ID " + userId);
                    us.setStarttime(new Date());
                    Long actualNewUserId = userManagement.addUserBackup(us);
                    usersMap.put(userId, actualNewUserId);

                    for (Iterator<Organisation_Users> orgUserIterator = orgUsers.iterator(); orgUserIterator
                            .hasNext();) {

                        Organisation_Users organisationUsers = orgUserIterator.next();

                        organisationmanagement.addOrganisationUserObj(actualNewUserId, organisationUsers);

                    }

                }

            }
        }

    } catch (Exception err) {
        log.error("[getUsersByXML]", err);
    }
}