Example usage for java.util Hashtable containsKey

List of usage examples for java.util Hashtable containsKey

Introduction

In this page you can find the example usage for java.util Hashtable containsKey.

Prototype

public synchronized boolean containsKey(Object key) 

Source Link

Document

Tests if the specified object is a key in this hashtable.

Usage

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

/** 
  * Create subJob stageIn directory on portal host, so user can upload files easy.
  * This method is called each time the user is uploading a file for a multiJob.
  *//w  ww . j a v  a  2 s.c om
  */
private boolean createLocalSubJobDir(HttpServletRequest request, String subJobInputDir, String fileType,
        String subJobId) {

    boolean success = false;
    File subJobFile = new File(subJobInputDir); //create if subJob directory does not exist
    success = subJobFile.exists();
    if (!success) {
        success = subJobFile.mkdir();
        Hashtable localSubJobDir = (Hashtable) request.getSession().getAttribute("localSubJobDir");

        if (localSubJobDir == null)
            localSubJobDir = new Hashtable();

        if (!localSubJobDir.containsKey(subJobId)) {
            localSubJobDir.put(subJobId, gridAccess.getLocalGridFtpServer() + subJobInputDir);
            request.getSession().setAttribute("localSubJobDir", localSubJobDir);
        }
    }

    if (fileType.equals(GridSubmitController.RINEX_DIR)) {
        //create rinex directory for the subJob.
        File subJobRinexDir = new File(subJobInputDir + GridSubmitController.RINEX_DIR + File.separator);
        success = subJobRinexDir.exists();
        if (!success) {
            success = subJobRinexDir.mkdir();
        }
    } else {
        //create tables directory for the subJob.
        File subJobTablesDir = new File(subJobInputDir + GridSubmitController.TABLE_DIR + File.separator);
        success = subJobTablesDir.exists();
        if (!success) {
            success = subJobTablesDir.mkdir();
        }
    }

    if (!success) {
        logger.error("Could not create local subJobStageIn directories ");
    }

    return success;
}

From source file:org.apache.nutch.parse.mspowerpoint.ContentReaderListener.java

/**
 * Extracts the client text boxes of a slide.
 * //from  www . java  2 s  .  com
 * @param containerTextBox
 * @param offset
 * @param pptdata
 * @param offsetPD
 * @return Hashtable
 * @see TextBox
 */
protected Hashtable/* <Long, TextBox> */ extractTextBoxes(final Hashtable/* <Long, TextBox> */ containerTextBox,
        final int offset, final byte[] pptdata, final long offsetPD) {

    // To hold temporary data
    FilteredStringWriter outStream = new FilteredStringWriter();

    TextBox textBox;

    // Traversing the bytearray up to Presist directory position
    for (int i = offset; i < offsetPD - 20; i++) {
        try {
            // Record info
            // final long rinfo = LittleEndian.getUShort(pptdata, (int) i);
            // Record Type
            final long recordType = LittleEndian.getUShort(pptdata, i + 2);
            // Record Size
            final long recordSize = LittleEndian.getUInt(pptdata, i + 4);

            if (recordType == PPTConstants.PPT_ATOM_DRAWINGGROUP) {
                /*
                 * Record type is of Drawing Group
                 */

                // Total number of objects
                // final long objectCount = LittleEndian.getUInt(pptdata, (int) i +
                // 8);
                // currentID = Group ID+number of objects
                long currentID = LittleEndian.getInt(pptdata, i + 12);
                currentID = ((int) (currentID / 1024)) * 1024;

                if (currentID == PPTConstants.PPT_MASTERSLIDE) {
                    // Ignore Master Slide objects
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Ignore master slide.");
                    }
                    i++;
                    continue;
                }

                // Check for the ClientTextBox GroupID existence
                if (containerTextBox.containsKey(new Long(currentID))) {
                    // If exists get Client Textbox Group
                    textBox = (TextBox) containerTextBox.get(new Long(currentID));
                    textBox.setContent("");

                } else {
                    textBox = new TextBox(currentID);
                    containerTextBox.put(new Long(currentID), textBox);
                }

                /*
                 * Iterating the bytearray for TextCharAtoms and TextBytesAtom
                 */
                if ((offsetPD - 20) != recordSize) {
                    // TODO something wrong? Probably an OLE-Object, which we ignore.
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("offsetPD - 20=" + (offsetPD - 20) + " recordsize=" + recordSize);
                    }
                } else {
                    for (int startPos = i + 8; startPos < offsetPD - 20 && startPos < recordSize; startPos++) { // && startPos <
                        // recordSize??
                        try {

                            // Record info
                            // final long nrinfo = LittleEndian.getUShort(pptdata, (int) j);

                            // Record Type
                            final long ntype = LittleEndian.getUShort(pptdata, startPos + 2);

                            // Record size
                            // Note that the size doesn't include the 8 byte atom header
                            final long nsize = LittleEndian.getUInt(pptdata, startPos + 4);

                            if (ntype == PPTConstants.PPT_ATOM_DRAWINGGROUP) {
                                /*
                                 * Break the loop if next GroupID found
                                 */
                                i = startPos - 1;
                                break;
                            } else if (ntype == PPTConstants.PPT_ATOM_TEXTBYTE) {
                                // TextByteAtom record
                                outStream = new FilteredStringWriter();
                                long ii = 0;
                                for (ii = startPos + 6; ii <= startPos + 6 + nsize; ii++) {
                                    // For loop to changed to a function
                                    // if ((ii + 2) >= pptdata.length)
                                    // break; // FIXME
                                    outStream.write((char) (pptdata[(int) ii + 2]));
                                }

                                // Setting the identified text for Current
                                // groupID
                                textBox.setContent(textBox.getContent() + outStream.toString());

                            } else if (ntype == PPTConstants.PPT_ATOM_TEXTCHAR) {
                                // TextCharAtom record

                                final String strTempContent = new String(pptdata, startPos + 6,
                                        (int) (nsize) + 2);
                                final byte bytes[] = strTempContent.getBytes();
                                if (true) {
                                    outStream = new FilteredStringWriter();
                                    for (int ii = 0; ii < bytes.length - 1; ii += 2) {
                                        // For loop to changed to a function
                                        outStream.write((char) (pptdata[ii + 2]));
                                    }
                                    textBox.setContent(textBox.getContent() + outStream.toString());
                                } else {
                                    // this version is used within POI
                                    String text = StringUtil.getFromCompressedUnicode(bytes, 0, bytes.length);
                                    textBox.setContent(textBox.getContent() + text);
                                }

                            } else {
                                // ignored
                                // if (LOG.isTraceEnabled()) {
                                //   LOG.trace("Ignored atom type: " + type);
                                // }
                            }
                        } catch (Throwable e) {
                            if (LOG.isErrorEnabled()) {
                                LOG.error("extractTextBoxes", e);
                            }
                            break;
                        }
                    }
                }
            } else {
                // Record type is ignored
                // if (LOG.isTraceEnabled()) {
                //   LOG.trace("Ignored record type: " + type);
                // }
            }
        } catch (Throwable ee) {
            if (LOG.isErrorEnabled()) {
                LOG.error("extractClientTextBoxes", ee);
            }
            break;
        }
    }
    return containerTextBox;
}

From source file:org.agnitas.backend.Data.java

/**
 * Find entry in map for overwrite/virtual records
 * @param cid the customer id/*  w  w  w  . java 2s.  c om*/
 * @param multi optional available multi hash table
 * @param simple optional simple hash table
 * @param colname the name of the column
 * @return the found string or null
 */
private String findInMap(Long cid, Hashtable<Long, Hashtable<String, String>> multi,
        Hashtable<String, String> simple, String colname) {
    Hashtable<String, String> map;

    if ((multi != null) && multi.containsKey(cid))
        map = multi.get(cid);
    else
        map = simple;
    if ((map != null) && map.containsKey(colname))
        return map.get(colname);
    return null;
}

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

/**
 * create a subjob for each day in the date range, using first parameter as a template.
 * Then transfer all the rinex files for each subjob. 
 * @param strDateFrom/*  w  w  w .  ja  v a 2  s.  co m*/
 * @param strDateTo
 * @param param
 * @return array of strings
 */
private String[] createSubjobs(String strDateFrom, String strDateTo, String param, HttpServletRequest request,
        List<GeodesyGridInputFile> gpsFiles) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    List<String> paramList = new ArrayList<String>();
    // Save in session to use it when submitting job
    String jobInputDir = (String) request.getSession().getAttribute("jobInputDir");

    //Use the first parameter from GUI as template for generating param for each day in the date range
    String paramTemp = param.substring(param.indexOf("-expt", 0), param.length());

    try {
        Date dateFrom = df.parse(strDateFrom);
        Date dateTo = df.parse(strDateTo);

        Calendar calFrom = Calendar.getInstance();
        calFrom.setTime(dateFrom);

        Calendar calTo = Calendar.getInstance();
        calTo.setTime(dateTo);

        //String gpsFiles = (String)request.getSession().getAttribute("gridInputFiles");   
        //List<String> urlsList = GeodesyUtil.getSelectedGPSFiles(gpsFiles);

        //while dateFrom is less than or equal to dateTo
        int jobCount = 0;
        while ((calFrom.compareTo(calTo)) <= 0) {
            //TO-DO check if this subJob has renix files available
            int year = calFrom.get(Calendar.YEAR);
            int doy = calFrom.get(Calendar.DAY_OF_YEAR);
            String strParam = "-d " + year + " " + doy + " " + paramTemp;
            paramList.add(strParam);

            String[] rinexOfDay = getRinexFilesOfDate(calFrom, gpsFiles);
            if (rinexOfDay.length > 0) {
                //First create subJob/rinex/ directories path for this subJob
                //Then urlcopy relevent rinex files for this sub job
                String subJobId = "subJob_" + jobCount;
                String subJobDir = jobInputDir + subJobId + File.separator;
                if (createGridDir(request, subJobDir)) {
                    String rinexSubJobDir = subJobDir + GridSubmitController.RINEX_DIR + File.separator;
                    if (createGridDir(request, rinexSubJobDir)) {
                        // Full URL
                        // e.g. "gsiftp://pbstore.ivec.org:2811//pbstore/au01/grid-auscope/Abdi.Jama@csiro.au-20091103_163322/"
                        //       +"rinex/" + filename
                        String toURL = gridAccess.getGridFtpServer() + File.separator + rinexSubJobDir;
                        urlCopy(rinexOfDay, request, toURL);

                        Hashtable subJobStageInDir = (Hashtable) request.getSession()
                                .getAttribute("subJobStageInDir");

                        if (subJobStageInDir == null)
                            subJobStageInDir = new Hashtable();

                        if (!subJobStageInDir.containsKey(subJobId)) {
                            String gridSubjobDir = gridAccess.getGridFtpServer() + subJobDir;
                            subJobStageInDir.put(subJobId, gridSubjobDir);
                            request.getSession().setAttribute("subJobStageInDir", subJobStageInDir);
                            logger.info("Added gridStageInDir: " + gridSubjobDir);
                        }
                    }
                    /*Hashtable subJobStageInDir = (Hashtable) request.getSession().getAttribute("subJobStageInDir");
                            
                    if(subJobStageInDir == null)
                       subJobStageInDir = new Hashtable();
                            
                    if(!subJobStageInDir.containsKey(subJobId)){
                       String gridSubjobDir = gridAccess.getGridFtpServer()+subJobDir;
                       subJobStageInDir.put(subJobId, gridSubjobDir);
                       request.getSession().setAttribute("subJobStageInDir", subJobStageInDir);
                       logger.info("Added gridStageInDir: "+gridSubjobDir);
                    }*/
                }
            } else {
                logger.info("No rinex files found for this day: " + year + "-" + doy);
            }

            calFrom.add(Calendar.DATE, 1);
            jobCount++;
            logger.debug("Added param: " + strParam);
        }
    } catch (ParseException e) {
        //do we need to pass this to the gui
        logger.error("Error casting date: " + e.getMessage());
    }
    String[] paramArray = new String[paramList.size()];
    paramArray = paramList.toArray(paramArray);
    return paramArray;
}

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

private Long[] save(org.hibernate.Session hibSession) throws Exception {

    if (iStudentSectioning)
        getModel().switchStudents(getAssignment());

    iProgress.setStatus("Saving solution ...");

    if (iSolverGroupId == null || iSolverGroupId.length == 0) {
        iProgress.fatal("No solver group loaded.");
        return null;
    }//from   w w  w.  j ava2  s  .c  o m

    Hashtable solverGroups = new Hashtable();
    for (int i = 0; i < iSolverGroupId.length; i++) {
        SolverGroup solverGroup = SolverGroupDAO.getInstance().get(iSolverGroupId[i], hibSession);
        if (solverGroup == null) {
            iProgress.fatal("Unable to load solver group " + iSolverGroupId[i] + ".");
            return null;
        }
        solverGroups.put(solverGroup.getUniqueId(), solverGroup);
        iProgress.debug("solver group [" + (i + 1) + "]: " + solverGroup.getName());
    }

    iSolutions = new Hashtable();
    if (!iCreateNew && iSolutionId != null && iSolutionId.length >= 0) {
        for (int i = 0; i < iSolverGroupId.length; i++) {
            if (i < iSolutionId.length && iSolutionId[i] != null) {
                Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession);
                if (solution == null) {
                    iProgress.warn("Unable to load solution " + iSolutionId[i]);
                    continue;
                }
                if (!solverGroups.containsKey(solution.getOwner().getUniqueId())) {
                    iProgress.warn("Solution " + iSolutionId[i]
                            + " ignored -- it does not match with the owner(s) of the problem");
                    continue;
                }
                if (solution.isCommited().booleanValue()) {
                    solution.uncommitSolution(hibSession,
                            getModel().getProperties().getProperty("General.OwnerPuid"));
                    if (!iCommitSolution) {
                        String className = ApplicationProperty.ExternalActionSolutionCommit.value();
                        if (className != null && className.trim().length() > 0) {
                            HashSet<Solution> touchedSolutions = new HashSet<Solution>();
                            touchedSolutions.add(solution);
                            ExternalSolutionCommitAction commitAction = (ExternalSolutionCommitAction) (Class
                                    .forName(className).newInstance());
                            commitAction.performExternalSolutionCommitAction(touchedSolutions, hibSession);
                        }

                    }
                }
                solution.empty(hibSession, getFileProxy());
                iSolutions.put(solution.getOwner().getUniqueId(), solution);
            }
        }
    }

    Session session = SessionDAO.getInstance().get(iSessionId, hibSession);
    if (session == null) {
        iProgress.fatal("No session loaded.");
        return null;
    }
    iProgress.debug("session: " + session.getLabel());

    for (Enumeration e = solverGroups.elements(); e.hasMoreElements();) {
        SolverGroup solverGroup = (SolverGroup) e.nextElement();
        Solution solution = (Solution) iSolutions.get(solverGroup.getUniqueId());
        if (solution == null) {
            solution = new Solution();
            iSolutions.put(solverGroup.getUniqueId(), solution);
        }
        solution.setCommitDate(null);
        solution.setCreated(new Timestamp((new Date()).getTime()));
        solution.setCreator(Test.getVersionString());
        solution.setNote(getModel().getProperties().getProperty("General.Note"));
        solution.setOwner(solverGroup);
        solverGroup.getSolutions().add(solution);
        solution.setValid(Boolean.TRUE);
        solution.setCommited(Boolean.FALSE);

        iProgress.setPhase("Saving solver parameters ...", getModel().getProperties().size());
        HashSet params = new HashSet();
        for (Iterator i1 = getModel().getProperties().entrySet().iterator(); i1.hasNext();) {
            Map.Entry entry = (Map.Entry) i1.next();
            String name = (String) entry.getKey();
            String value = (String) entry.getValue();
            SolverParameterDef def = SolverParameterDef.findByNameType(hibSession, name,
                    SolverParameterGroup.sTypeCourse);
            if (def != null) {
                iProgress.trace("save " + name + "=" + value);
                SolverParameter param = new SolverParameter();
                param.setDefinition(def);
                param.setValue(value);
                hibSession.save(param);
                params.add(param);
            }
            iProgress.incProgress();
        }
        solution.setParameters(params);

        hibSession.saveOrUpdate(solution);
    }

    hibSession.flush();
    hibSession.clear();
    int batchIdx = 0;

    iProgress.setPhase("Saving assignments ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        Placement placement = getAssignment().getValue(lecture);
        if (placement != null) {
            iProgress.trace("save " + lecture.getName() + " " + placement.getName());
            Class_ clazz = (new Class_DAO()).get(lecture.getClassId(), hibSession);
            if (clazz == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm) + ") -- class (id:" + lecture.getClassId()
                        + ") does not exist.");
                continue;
            }
            HashSet rooms = new HashSet();
            if (placement.isMultiRoom()) {
                for (RoomLocation r : placement.getRoomLocations()) {
                    Location room = (new LocationDAO()).get(r.getId(), hibSession);
                    if (room == null) {
                        iProgress.warn("Unable to save assignment for class " + lecture + " ("
                                + placement.getLongName(iUseAmPm) + ") -- room (id:" + r.getId()
                                + ") does not exist.");
                        continue;
                    }
                    rooms.add(room);
                }
                if (rooms.size() != placement.getRoomLocations().size())
                    continue;
            } else {
                Location room = (new LocationDAO()).get(placement.getRoomLocation().getId(), hibSession);
                if (room == null) {
                    iProgress.warn("Unable to save assignment for class " + lecture + " ("
                            + placement.getLongName(iUseAmPm) + ") -- room (id:"
                            + placement.getRoomLocation().getId() + ") does not exist.");
                    continue;
                }
                rooms.add(room);
            }

            HashSet instructors = new HashSet();
            for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
                DepartmentalInstructor instructor = null;
                if (ic.getPuid() != null && ic.getPuid().length() > 0) {
                    instructor = DepartmentalInstructor.findByPuidDepartmentId(ic.getPuid(),
                            clazz.getControllingDept().getUniqueId());
                } else if (ic.getResourceId() != null) {
                    instructor = (new DepartmentalInstructorDAO()).get(ic.getResourceId(), hibSession);
                }
                if (instructor != null)
                    instructors.add(instructor);
            }

            TimePattern pattern = (new TimePatternDAO()).get(placement.getTimeLocation().getTimePatternId(),
                    hibSession);
            if (pattern == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm) + ") -- time pattern (id:"
                        + placement.getTimeLocation().getTimePatternId() + ") does not exist.");
                continue;
            }
            Solution solution = getSolution(lecture, hibSession);
            if (solution == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm)
                        + ") -- none or wrong solution group assigned to the class");
                continue;
            }
            Assignment assignment = new Assignment();
            assignment.setClazz(clazz);
            assignment.setClassId(clazz.getUniqueId());
            assignment.setClassName(lecture.getName());
            assignment.setDays(new Integer(placement.getTimeLocation().getDayCode()));
            assignment.setStartSlot(new Integer(placement.getTimeLocation().getStartSlot()));
            assignment.setTimePattern(pattern);
            if (placement.getTimeLocation().getDatePatternId() != null)
                assignment.setDatePattern(DatePatternDAO.getInstance()
                        .get(placement.getTimeLocation().getDatePatternId(), hibSession));
            assignment.setRooms(rooms);
            assignment.setInstructors(instructors);
            assignment.setSolution(solution);
            hibSession.save(assignment);
            iAssignments.put(lecture.getClassId(), assignment);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    if (getModel().getProperties().getPropertyBoolean("General.SaveStudentEnrollments", true)) {
        iProgress.setPhase("Saving student enrollments ...", getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            Class_ clazz = (new Class_DAO()).get(lecture.getClassId(), hibSession);
            if (clazz == null)
                continue;
            iProgress.trace("save " + lecture.getName());
            Solution solution = getSolution(lecture, hibSession);
            if (solution == null) {
                iProgress.warn("Unable to save student enrollments for class " + lecture
                        + "  -- none or wrong solution group assigned to the class");
                continue;
            }

            for (Iterator i2 = lecture.students().iterator(); i2.hasNext();) {
                Student student = (Student) i2.next();
                StudentEnrollment enrl = new StudentEnrollment();
                enrl.setStudentId(student.getId());
                enrl.setClazz(clazz);
                enrl.setSolution(solution);
                hibSession.save(enrl);
                if (++batchIdx % BATCH_SIZE == 0) {
                    hibSession.flush();
                    hibSession.clear();
                }
            }

            iProgress.incProgress();
        }

        hibSession.flush();
        hibSession.clear();
        batchIdx = 0;
    }

    /**  // is this needed?
    iProgress.setPhase("Saving joint enrollments ...", getModel().getJenrlConstraints().size());
    for (Enumeration e1=getModel().getJenrlConstraints().elements();e1.hasMoreElements();) {
     JenrlConstraint jenrlConstraint = (JenrlConstraint)e1.nextElement();
             
     Class_ clazz1 = (new Class_DAO()).get(((Lecture)jenrlConstraint.first()).getClassId());
     Class_ clazz2 = (new Class_DAO()).get(((Lecture)jenrlConstraint.second()).getClassId());
             
     JointEnrollment jenrl = new JointEnrollment();
     jenrl.setJenrl(new Double(jenrlConstraint.getJenrl()));
     jenrl.setClass1(clazz1);
     jenrl.setClass2(clazz2);
     jenrl.setSolution(solution);
     hibSession.save(jenrl);
             
     iProgress.incProgress();
    }
    */

    SolverInfoDef defGlobalInfo = SolverInfoDef.findByName(hibSession, "GlobalInfo");
    if (defGlobalInfo == null)
        iProgress.warn("Global info is not registered.");
    SolverInfoDef defCbsInfo = SolverInfoDef.findByName(hibSession, "CBSInfo");
    if (defCbsInfo == null)
        iProgress.warn("Constraint-based statistics info is not registered.");
    SolverInfoDef defAssignmentInfo = SolverInfoDef.findByName(hibSession, "AssignmentInfo");
    if (defAssignmentInfo == null)
        iProgress.warn("Assignment info is not registered.");
    SolverInfoDef defDistributionInfo = SolverInfoDef.findByName(hibSession, "DistributionInfo");
    if (defDistributionInfo == null)
        iProgress.warn("Distribution constraint info is not registered.");
    SolverInfoDef defJenrlInfo = SolverInfoDef.findByName(hibSession, "JenrlInfo");
    if (defJenrlInfo == null)
        iProgress.warn("Joint enrollments info is not registered.");
    SolverInfoDef defLogInfo = SolverInfoDef.findByName(hibSession, "LogInfo");
    if (defLogInfo == null)
        iProgress.warn("Solver log info is not registered.");
    SolverInfoDef defBtbInstrInfo = SolverInfoDef.findByName(hibSession, "BtbInstructorInfo");
    if (defBtbInstrInfo == null)
        iProgress.warn("Back-to-back instructor info is not registered.");

    Hashtable<Solution, List<Lecture>> lectures4solution = new Hashtable<Solution, List<Lecture>>();
    for (Lecture lecture : getModel().variables()) {
        Solution s = getSolution(lecture, hibSession);
        if (s == null)
            continue;
        List<Lecture> lectures = lectures4solution.get(s);
        if (lectures == null) {
            lectures = new ArrayList<Lecture>();
            lectures4solution.put(s, lectures);
        }
        lectures.add(lecture);
    }

    iProgress.setPhase("Saving global info ...", solverGroups.size());
    for (Enumeration e = solverGroups.elements(); e.hasMoreElements();) {
        SolverGroup solverGroup = (SolverGroup) e.nextElement();
        Solution solution = (Solution) iSolutions.get(solverGroup.getUniqueId());
        List<Lecture> lectures = lectures4solution.get(solution);
        if (lectures == null)
            lectures = new ArrayList<Lecture>(0);
        SolutionInfo solutionInfo = new SolutionInfo();
        solutionInfo.setDefinition(defGlobalInfo);
        solutionInfo.setOpt(null);
        solutionInfo.setSolution(solution);
        solutionInfo.setInfo(new PropertiesInfo(getSolution().getInfo(lectures)), getFileProxy());
        hibSession.save(solutionInfo);
        solution.setGlobalInfo(solutionInfo);
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    ConflictStatistics cbs = null;
    for (Extension ext : getSolver().getExtensions()) {
        if (ext instanceof ConflictStatistics) {
            cbs = (ConflictStatistics) ext;
            break;
        }
    }
    if (cbs != null && cbs.getNoGoods() != null) {
        ConflictStatisticsInfo cbsInfo = new ConflictStatisticsInfo();
        cbsInfo.load(getSolver(), cbs);
        iProgress.setPhase("Saving conflict-based statistics ...", 1);
        for (Enumeration e = iSolutions.elements(); e.hasMoreElements();) {
            Solution solution = (Solution) e.nextElement();
            List<Lecture> lectures = lectures4solution.get(solution);
            if (lectures == null)
                lectures = new ArrayList<Lecture>(0);
            SolutionInfo cbsSolutionInfo = new SolutionInfo();
            cbsSolutionInfo.setDefinition(defCbsInfo);
            cbsSolutionInfo.setOpt(null);
            cbsSolutionInfo.setSolution(solution);
            cbsSolutionInfo.setInfo(cbsInfo.getConflictStatisticsSubInfo(lectures), getFileProxy());
            hibSession.save(cbsSolutionInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving variable infos ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        Placement placement = getAssignment().getValue(lecture);
        if (placement != null) {
            Assignment assignment = (Assignment) iAssignments.get(lecture.getClassId());
            AssignmentInfo assignmentInfo = new AssignmentInfo();
            assignmentInfo.setAssignment(assignment);
            assignmentInfo.setDefinition(defAssignmentInfo);
            assignmentInfo.setOpt(null);
            assignmentInfo.setInfo(new AssignmentPreferenceInfo(getSolver(), placement, true, true),
                    getFileProxy());
            hibSession.save(assignmentInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving btb instructor infos ...", getModel().variables().size());
    for (Lecture lecture1 : getModel().variables()) {
        Placement placement1 = (Placement) getAssignment().getValue(lecture1);
        iProgress.incProgress();
        if (placement1 == null)
            continue;
        for (InstructorConstraint ic : lecture1.getInstructorConstraints()) {
            for (Lecture lecture2 : ic.variables()) {
                Placement placement2 = (Placement) getAssignment().getValue(lecture2);
                if (placement2 == null || lecture2.getClassId().compareTo(lecture1.getClassId()) <= 0)
                    continue;
                int pref = ic.getDistancePreference(placement1, placement2);
                if (pref == PreferenceLevel.sIntLevelNeutral)
                    continue;
                iProgress.trace("Back-to-back instructor constraint (" + pref + ") between " + placement1
                        + " and " + placement2);
                BtbInstructorConstraintInfo biInfo = new BtbInstructorConstraintInfo();
                biInfo.setPreference(pref);
                biInfo.setInstructorId(ic.getResourceId());
                ConstraintInfo constraintInfo = new ConstraintInfo();
                constraintInfo.setDefinition(defBtbInstrInfo);
                constraintInfo.setOpt(String.valueOf(ic.getResourceId()));
                HashSet biAssignments = new HashSet();
                Assignment assignment = (Assignment) iAssignments.get(lecture1.getClassId());
                if (assignment != null)
                    biAssignments.add(assignment);
                assignment = (Assignment) iAssignments.get(lecture2.getClassId());
                if (assignment != null)
                    biAssignments.add(assignment);
                if (!biAssignments.isEmpty()) {
                    constraintInfo.setAssignments(biAssignments);
                    constraintInfo.setInfo(biInfo, getFileProxy());
                    hibSession.save(constraintInfo);
                    if (++batchIdx % BATCH_SIZE == 0) {
                        hibSession.flush();
                        hibSession.clear();
                    }
                } else {
                    iProgress.trace("   NO ASSIGNMENTS !!!");
                }
            }
        }
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving group constraint infos ...", getModel().getGroupConstraints().size());
    for (GroupConstraint gc : getModel().getGroupConstraints()) {
        GroupConstraintInfo gcInfo = new GroupConstraintInfo(getAssignment(), gc);
        ConstraintInfo constraintInfo = new ConstraintInfo();
        constraintInfo.setDefinition(defDistributionInfo);
        constraintInfo.setOpt(gcInfo.isSatisfied() ? "1" : "0");
        iProgress.trace("Distribution constraint " + gcInfo.getName() + " (p:" + gcInfo.getPreference() + ", s:"
                + gcInfo.isSatisfied() + ") between");
        HashSet gcAssignments = new HashSet();
        for (Lecture lecture : gc.variables()) {
            Assignment assignment = (Assignment) iAssignments.get(lecture.getClassId());
            iProgress.trace("  " + getAssignment().getValue(lecture));
            if (assignment != null)
                gcAssignments.add(assignment);
        }

        if (!gcAssignments.isEmpty()) {
            constraintInfo.setAssignments(gcAssignments);
            constraintInfo.setInfo(gcInfo, getFileProxy());
            hibSession.save(constraintInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        } else {
            iProgress.trace("   NO ASSIGNMENTS !!!");
        }

        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving student enrollment infos ...", getModel().getJenrlConstraints().size());
    for (JenrlConstraint jc : getModel().getJenrlConstraints()) {
        if (!jc.isInConflict(getAssignment()) || !jc.isOfTheSameProblem()) {
            iProgress.incProgress();
            continue;
        }
        JenrlInfo jInfo = new JenrlInfo(getSolver(), jc);
        ConstraintInfo constraintInfo = new ConstraintInfo();
        constraintInfo.setDefinition(defJenrlInfo);
        constraintInfo.setOpt((jInfo.isSatisfied() ? "S" : "") + (jInfo.isHard() ? "H" : "")
                + (jInfo.isDistance() ? "D" : "") + (jInfo.isFixed() ? "F" : "")
                + (jInfo.isImportant() ? "I" : "") + (jInfo.isInstructor() ? "X" : ""));
        Assignment firstAssignment = (Assignment) iAssignments.get(((Lecture) jc.first()).getClassId());
        Assignment secondAssignment = (Assignment) iAssignments.get(((Lecture) jc.second()).getClassId());
        if (firstAssignment == null || secondAssignment == null)
            continue;
        HashSet jAssignments = new HashSet();
        jAssignments.add(firstAssignment);
        jAssignments.add(secondAssignment);
        constraintInfo.setAssignments(jAssignments);
        constraintInfo.setInfo(jInfo, getFileProxy());
        hibSession.save(constraintInfo);
        if (++batchIdx % BATCH_SIZE == 0) {
            hibSession.flush();
            hibSession.clear();
        }

        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving committed student enrollment infos ...", iSolutions.size());
    for (Enumeration e = iSolutions.elements(); e.hasMoreElements();) {
        Solution solution = (Solution) e.nextElement();
        solution.updateCommittedStudentEnrollmentInfos(hibSession);
        iProgress.incProgress();
    }
    iProgress.incProgress();

    /*
    iProgress.setPhase("Saving committed student enrollment infos ...", getModel().assignedVariables().size());
    for (Enumeration e1=getModel().assignedVariables().elements();e1.hasMoreElements();) {
     Lecture lecture = (Lecture)e1.nextElement();
     Assignment assignment = (Assignment)iAssignments.get(lecture.getClassId());
    if (assignment==null) continue;
    Hashtable infos = JenrlInfo.getCommitedJenrlInfos(lecture);
     for (Iterator i2=infos.entrySet().iterator();i2.hasNext();) {
        Map.Entry entry = (Map.Entry)i2.next();
        Integer assignmentId = (Integer)entry.getKey();
        JenrlInfo jInfo = (JenrlInfo)entry.getValue();
        Assignment other = (new AssignmentDAO()).get(assignmentId,hibSession);
        if (other==null) continue;
         ConstraintInfo constraintInfo = new ConstraintInfo();
         constraintInfo.setDefinition(defJenrlInfo);
         constraintInfo.setOpt("C"+(jInfo.isSatisfied()?"S":"")+(jInfo.isHard()?"H":"")+(jInfo.isDistance()?"D":"")+(jInfo.isFixed()?"F":""));
         HashSet jAssignments = new HashSet();
         jAssignments.add(assignment);
         jAssignments.add(other);
         constraintInfo.setAssignments(jAssignments);
         constraintInfo.setInfo(jInfo,getFileProxy());
         hibSession.save(constraintInfo);
        if (++batchIdx % BATCH_SIZE == 0) {
           hibSession.flush(); hibSession.clear();
        }
     }
     iProgress.incProgress();
    }
    */

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

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

    Long ret[] = new Long[iSolutions.size()];
    int idx = 0;
    for (Enumeration e = iSolutions.elements(); e.hasMoreElements();)
        ret[idx++] = ((Solution) e.nextElement()).getUniqueId();

    return ret;
}

From source file:com.alfaariss.oa.profile.aselect.processor.ASelectProcessor.java

private Hashtable<String, Integer> readConfigAuthNLevels(IConfigurationManager oConfigurationManager,
        Element eAuthentication) throws OAException {
    IAuthenticationProfileFactory authNProfileFactory = Engine.getInstance().getAuthenticationProfileFactory();

    Hashtable<String, Integer> htAuthSPLevels = new Hashtable<String, Integer>();
    Element eAuthNProfile = oConfigurationManager.getSection(eAuthentication, "profile");
    while (eAuthNProfile != null) {
        String sAuthNProfileID = oConfigurationManager.getParam(eAuthNProfile, "id");
        if (sAuthNProfileID == null) {
            _logger.error("No 'id' item in 'profile' section found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }// w  ww.  j  a va 2  s.c  om

        if (authNProfileFactory.getProfile(sAuthNProfileID) == null) {
            _logger.error("The configured 'id' doesn't exist as an authentication profile: " + sAuthNProfileID);
            throw new OAException(SystemErrors.ERROR_INIT);
        }

        String sAuthSPLevel = oConfigurationManager.getParam(eAuthNProfile, "authsp_level");
        if (sAuthSPLevel == null) {
            _logger.error("No 'authsp_level' item in 'profile' section found in configuration for profile id: "
                    + sAuthNProfileID);
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        Integer intAuthSPLevel = null;
        try {
            intAuthSPLevel = Integer.parseInt(sAuthSPLevel);
        } catch (NumberFormatException e) {
            StringBuffer sbError = new StringBuffer(
                    "Invalid 'authsp_level' item in 'profile' section found in configuration for profile id '");
            sbError.append(sAuthNProfileID);
            sbError.append("' level isn't a number: ");
            sbError.append(sAuthSPLevel);
            _logger.error(sbError.toString(), e);
            throw new OAException(SystemErrors.ERROR_INIT);
        }

        if (htAuthSPLevels.containsKey(sAuthNProfileID)) {
            _logger.warn("The configured authentication profile doesn't have an unique id: " + sAuthNProfileID);
            throw new OAException(SystemErrors.ERROR_INIT);
        }

        htAuthSPLevels.put(sAuthNProfileID, intAuthSPLevel);
        StringBuffer sbInfo = new StringBuffer("Configured: authsp_level=");
        sbInfo.append(sAuthSPLevel);
        sbInfo.append(" for authentication profile with id: ");
        sbInfo.append(sAuthNProfileID);
        _logger.info(sbInfo.toString());

        eAuthNProfile = oConfigurationManager.getNextSection(eAuthNProfile);
    }

    return htAuthSPLevels;
}

From source file:org.fcrepo.server.access.DefaultAccess.java

/**
 * <p>//  w  ww  . java  2 s  . c  om
 * Disseminates the content produced by executing the specified method of
 * the associated deployment object of the specified digital object.
 * </p>
 *
 * @param context
 *        The context of this request.
 * @param PID
 *        The persistent identifier of the digital object.
 * @param sDefPID
 *        The persistent identifier of the Service Definition object.
 * @param methodName
 *        The name of the method to be executed.
 * @param userParms
 *        An array of user-supplied method parameters consisting of
 *        name/value pairs.
 * @param asOfDateTime
 *        The versioning datetime stamp.
 * @return A MIME-typed stream containing the result of the dissemination.
 * @throws ServerException
 *         If any type of error occurred fulfilling the request.
 */
@Override
public MIMETypedStream getDissemination(Context context, String PID, String sDefPID, String methodName,
        Property[] userParms, Date asOfDateTime) throws ServerException {
    PID = Server.getPID(PID).toString();
    sDefPID = Server.getPID(sDefPID).toString();
    long initStartTime = (logger.isDebugEnabled()) ? System.currentTimeMillis() : 0;
    long startTime = initStartTime;
    long stopTime;
    long interval;
    ServiceDeploymentReader deploymentReader = null;

    DOReader reader = m_manager.getReader(asOfDateTime == null, context, PID);
    String authzAux_objState = reader.GetObjectState();

    // DYNAMIC!! If service deployment is defined as dynamic, then
    // perform the dissemination via the DynamicAccess module.
    if (m_dynamicAccess.isDynamicService(context, PID, sDefPID)) {
        m_authorizationModule.enforceGetDissemination(context, PID, sDefPID, methodName, asOfDateTime,
                authzAux_objState, "A", "fedora-system:4", "A", "A");
        MIMETypedStream retVal = m_dynamicAccess.getDissemination(context, PID, sDefPID, methodName, userParms,
                asOfDateTime);
        if (logger.isDebugEnabled()) {
            stopTime = System.currentTimeMillis();
            interval = stopTime - startTime;
            logger.debug("Roundtrip DynamicDisseminator: {} milliseconds.", interval);
        }
        return retVal;
    }

    /*
     * Find the service deployment that is contractor for a model this
     * object has, and deploys the requested service. If object<->model
     * mappings are ever stored in the registry, this may be simplified.
     */
    String serviceDeploymentPID = null;
    for (String cModelURI : reader.getContentModels()) {
        String cModelPID = cModelURI.substring("info:fedora/".length());

        String foundDeploymentPID = m_manager.lookupDeploymentForCModel(cModelPID, sDefPID);

        if (foundDeploymentPID != null) {
            if (serviceDeploymentPID != null && !foundDeploymentPID.equals(serviceDeploymentPID)) {
                throw new DisseminationException("More than one deployment (" + foundDeploymentPID + ", "
                        + serviceDeploymentPID + ") found for service " + sDefPID + " in model " + cModelPID);

            }

            serviceDeploymentPID = foundDeploymentPID;
        } else {
            logger.debug("No deployment for ({}, {})", cModelPID, sDefPID);
        }
    }

    if (serviceDeploymentPID != null) {
        deploymentReader = m_manager.getServiceDeploymentReader(false, context, serviceDeploymentPID);
    }

    ServiceDefinitionReader sDefReader = m_manager.getServiceDefinitionReader(asOfDateTime == null, context,
            sDefPID);

    String authzAux_sdefState = sDefReader.GetObjectState();

    String authzAux_dissState = "unknown";

    /*
     * if reader is null, it means that no suitable deployments have been
     * found. This can happen if (a), the object does not have any models
     * that have that service, or (b) the object has a suitable model, but
     * no implementation of that service has been deployed. We do a bit of
     * checking here to determine which case this represents, as the error
     * message could be very useful.
     */
    if (deploymentReader == null) {

        boolean suitableModelFound = false;
        String cModelPID = null;
        String message = null;

        models: for (String cm : reader.getContentModels()) {
            cModelPID = cm.substring(12);

            /* Skip over system models */
            if (Models.contains("info:fedora/" + cModelPID)) {
                continue;
            }

            /* Open up each model and peek at its sDefs for a match */
            for (RelationshipTuple r : m_manager.getReader(false, context, cModelPID)
                    .getRelationships(MODEL.HAS_SERVICE, null)) {
                if (sDefPID.equals(r.getObjectPID())) {
                    suitableModelFound = true;
                    break models;
                }
            }
        }

        if (suitableModelFound) {
            message = "Unable to find deployment for service " + sDefPID + " on " + reader.GetObjectPID()
                    + " in model " + cModelPID;
        } else {
            message = reader.GetObjectPID() + " does not have a model with service " + sDefPID;
        }
        throw new DisseminatorNotFoundException(message);
    }
    if (logger.isDebugEnabled()) {
        stopTime = System.currentTimeMillis();
        interval = stopTime - startTime;
        logger.debug("Roundtrip Looping Diss: {} milliseconds.", interval);
    }
    // Check deployment object state
    String authzAux_sDepState = deploymentReader.GetObjectState();
    String authzAux_sDepPID = deploymentReader.GetObjectPID();

    m_authorizationModule.enforceGetDissemination(context, PID, sDefPID, methodName, asOfDateTime,
            authzAux_objState, authzAux_sdefState, authzAux_sDepPID, authzAux_sDepState, authzAux_dissState);

    // Get method parms
    Hashtable<String, String> h_userParms = new Hashtable<String, String>();
    MIMETypedStream dissemination = null;
    MethodParmDef[] defaultMethodParms = null;

    startTime = new Date().getTime();
    // Put any user-supplied method parameters into hash table
    if (userParms != null) {
        for (Property element : userParms) {
            h_userParms.put(element.name, element.value);
        }
    }
    // Validate user-supplied parameters
    validateUserParms(context, PID, sDefPID, deploymentReader, methodName, h_userParms, asOfDateTime);

    if (logger.isDebugEnabled()) {
        stopTime = System.currentTimeMillis();
        interval = stopTime - startTime;
        logger.debug("Roundtrip Get/Validate User Parms:  milliseconds.", interval);

        startTime = System.currentTimeMillis();
    }
    // SDP: GET INFO FROM DEPLOYMENT READER:
    // Add any default method parameters to validated user parm list
    defaultMethodParms = deploymentReader.getServiceMethodParms(methodName, asOfDateTime);
    for (int i = 0; i < defaultMethodParms.length; i++) {
        if (!defaultMethodParms[i].parmType.equals(MethodParmDef.DATASTREAM_INPUT)) {
            if (!h_userParms.containsKey(defaultMethodParms[i].parmName)) {
                logger.debug("addedDefaultName: {}", defaultMethodParms[i].parmName);
                String pdv = defaultMethodParms[i].parmDefaultValue;
                try {
                    // here we make sure the PID is decoded so that encoding
                    // later won't doubly-encode it
                    if (pdv.equalsIgnoreCase("$pid")) {
                        pdv = URLDecoder.decode(PID, "UTF-8");
                    } else if (pdv.equalsIgnoreCase("$objuri")) {
                        pdv = "info:fedora/" + URLDecoder.decode(PID, "UTF-8");
                    }
                } catch (UnsupportedEncodingException uee) {
                }
                logger.debug("addedDefaultValue: {}", pdv);
                h_userParms.put(defaultMethodParms[i].parmName, pdv);
            }
        }
    }

    if (logger.isDebugEnabled()) {
        stopTime = System.currentTimeMillis();
        interval = stopTime - startTime;
        logger.debug("Roundtrip Get Deployment Parms: {} milliseconds.", interval);
        startTime = System.currentTimeMillis();
    }

    DisseminationBindingInfo[] dissBindInfo;
    dissBindInfo = getDisseminationBindingInfo(context, reader, deploymentReader, methodName, asOfDateTime);

    // Assemble and execute the dissemination request from the binding info.
    DisseminationService dissService = new DisseminationService(getServer());
    dissemination = dissService.assembleDissemination(context, PID, h_userParms, dissBindInfo, authzAux_sDepPID,
            deploymentReader, methodName);

    if (logger.isDebugEnabled()) {
        stopTime = System.currentTimeMillis();
        interval = stopTime - startTime;
        logger.debug("Roundtrip Assemble Dissemination: {} milliseconds.", interval);

        interval = stopTime - initStartTime;
        logger.debug("Roundtrip GetDissemination: {} milliseconds.", interval);
    }
    return dissemination;
}

From source file:com.cyberway.issue.crawler.Heritrix.java

public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
    this.mbeanServer = server;
    @SuppressWarnings("unchecked")
    Hashtable<String, String> ht = name.getKeyPropertyList();
    if (!ht.containsKey(JmxUtils.NAME)) {
        throw new IllegalArgumentException("Name property required" + name.getCanonicalName());
    }/*from   ww w  .  java  2  s. c o m*/
    if (!ht.containsKey(JmxUtils.TYPE)) {
        ht.put(JmxUtils.TYPE, JmxUtils.SERVICE);
        name = new ObjectName(name.getDomain(), ht);
    }
    this.mbeanName = addGuiPort(addVitals(name));
    Heritrix.instances.put(this.mbeanName.getCanonicalKeyPropertyListString(), this);
    return this.mbeanName;
}

From source file:edu.eurac.commul.pepperModules.mmax2.MMAX22SaltMapper.java

/**
 * Maps a {@link SaltExtendedDocument} document to an {@link SDocument} sDocument
 * @param document The {@link SaltExtendedDocument} document to map
 * @param sDocument the {@link SDocument} to which the data is being mapped to 
 *//*  w  w  w .  j a va  2s.c  om*/
public void mapSDocument(SaltExtendedDocument document, SDocument sDocument) {
    this.sNodesHash = new Hashtable<SaltExtendedMarkable, SNode>();
    this.sRelationsHash = new Hashtable<SaltExtendedMarkable, SRelation>();
    this.sLayerHash = new Hashtable<String, SLayer>();
    this.sTextualDsOfset = new Hashtable<STextualDS, Integer>();
    this.sTokensHash = new Hashtable<String, SToken>();
    this.saltExtendedMarkableHash = new Hashtable<String, Hashtable<String, SaltExtendedMarkable>>();
    this.sTextualDsBaseDataUnitCorrespondance = new Hashtable<String, STextualDS>();
    this.claimSContainer = new Hashtable<SaltExtendedMarkable, SaltExtendedMarkable>();
    this.saltIds = new Hashtable<String, IdentifiableElement>();
    this.saltIdsCpt = new Hashtable<String, Integer>();

    SDocumentGraph sDocumentGraph = sDocument.getDocumentGraph();
    sDocumentGraph.setName(document.getDocumentId() + "_graph");

    ArrayList<SaltExtendedMarkable> markables = document.getAllSaltExtendedMarkables();
    Hashtable<String, SaltExtendedMarkable> baseDataUnitInTextualDS = new Hashtable<String, SaltExtendedMarkable>();
    for (SaltExtendedMarkable markable : markables) {
        if (markable.hasSaltInformation()
                && (markable.getSType().equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STEXTUALDS))) {
            String[] markableSpans = markable.getSpan().split(",");
            for (int i = 0; i < markableSpans.length; i++) {
                ArrayList<String> baseDataUnits = getBaseUnitIds(markableSpans[i]);
                for (String baseDataUnit : baseDataUnits) {
                    if (baseDataUnitInTextualDS.containsKey(baseDataUnit)) {
                        throw new PepperModuleDataException(this,
                                "Two textualDS covers one same basedata unit: markables '" + markable.getId()
                                        + "' and '" + baseDataUnitInTextualDS.get(baseDataUnit).getId()
                                        + "' both covers '" + baseDataUnit + "'");
                    } else {
                        baseDataUnitInTextualDS.put(baseDataUnit, markable);
                    }
                }
            }

        }
    }

    int nbBaseDataUnits = 0;

    Hashtable<String, int[]> indicesTokens = new Hashtable<String, int[]>();
    Hashtable<SaltExtendedMarkable, ArrayList<BaseDataUnit>> sTextualDSBaseDataUnits = new Hashtable<SaltExtendedMarkable, ArrayList<BaseDataUnit>>();
    SaltExtendedMarkable lastTextualDsMarkable = null;
    ArrayList<BaseDataUnit> bufferBaseDataUnit = new ArrayList<BaseDataUnit>();
    ArrayList<BaseDataUnit> baseDataUnits = document.getBaseDataUnits();
    {
        int indice = 0;
        Hashtable<SaltExtendedMarkable, String> previouslySeenTextualDs = new Hashtable<SaltExtendedMarkable, String>();

        nbBaseDataUnits = baseDataUnits.size();
        for (BaseDataUnit baseDataUnit : baseDataUnits) {
            int newIndice = indice + baseDataUnit.getText().length();
            int[] indices = { indice, newIndice };
            indicesTokens.put(baseDataUnit.getId(), indices);
            indice = newIndice;

            bufferBaseDataUnit.add(baseDataUnit);
            if (baseDataUnitInTextualDS.containsKey(baseDataUnit.getId())) {
                SaltExtendedMarkable textualDsMarkable = baseDataUnitInTextualDS.get(baseDataUnit.getId());
                if ((textualDsMarkable != lastTextualDsMarkable)
                        && (previouslySeenTextualDs.containsKey(textualDsMarkable))) {
                    throw new PepperModuleDataException(this,
                            "The spans of textualDs markables '" + textualDsMarkable.getId() + "' and '"
                                    + lastTextualDsMarkable + "' overlap one another.");
                }

                lastTextualDsMarkable = textualDsMarkable;
                previouslySeenTextualDs.put(lastTextualDsMarkable, "");
                ArrayList<BaseDataUnit> localBaseDataUnits = sTextualDSBaseDataUnits.get(lastTextualDsMarkable);
                if (localBaseDataUnits == null) {
                    localBaseDataUnits = new ArrayList<BaseDataUnit>();
                    sTextualDSBaseDataUnits.put(lastTextualDsMarkable, localBaseDataUnits);
                }
                localBaseDataUnits.addAll(bufferBaseDataUnit);
                bufferBaseDataUnit = new ArrayList<BaseDataUnit>();
            }
        }

    }

    if (bufferBaseDataUnit.size() != 0) {
        if (lastTextualDsMarkable != null) {
            sTextualDSBaseDataUnits.get(lastTextualDsMarkable).addAll(bufferBaseDataUnit);
        } else {
            createSTextualDS(sDocumentGraph, null, bufferBaseDataUnit, indicesTokens);
        }
    }

    ArrayList<SSpanningRelation> sSpanRelNodes = new ArrayList<SSpanningRelation>();
    ArrayList<SaltExtendedMarkable> sSpanRelMarkables = new ArrayList<SaltExtendedMarkable>();

    ArrayList<SDominanceRelation> sDomRelNodes = new ArrayList<SDominanceRelation>();
    ArrayList<SaltExtendedMarkable> sDomRelMarkables = new ArrayList<SaltExtendedMarkable>();

    ArrayList<STextualRelation> sTextRelNodes = new ArrayList<STextualRelation>();
    ArrayList<SaltExtendedMarkable> sTextRelMarkables = new ArrayList<SaltExtendedMarkable>();

    ArrayList<SPointingRelation> sPointerNodes = new ArrayList<SPointingRelation>();
    ArrayList<SaltExtendedMarkable> sPointerMarkables = new ArrayList<SaltExtendedMarkable>();

    ArrayList<SaltExtendedMarkable> sContainerMarkables = new ArrayList<SaltExtendedMarkable>();

    ArrayList<SaltExtendedMarkable> sAnnotationMarkables = new ArrayList<SaltExtendedMarkable>();
    Hashtable<String, SAnnotationContainer> correspondanceSAnnotations = new Hashtable<String, SAnnotationContainer>();

    ArrayList<SaltExtendedMarkable> sMetaAnnotationMarkables = new ArrayList<SaltExtendedMarkable>();
    Hashtable<String, SAnnotationContainer> correspondanceSMetaAnnotations = new Hashtable<String, SAnnotationContainer>();

    ArrayList<SaltExtendedMarkable> sLayerLinkMarkables = new ArrayList<SaltExtendedMarkable>();
    ArrayList<SaltExtendedMarkable> sTypeLinkMarkables = new ArrayList<SaltExtendedMarkable>();

    Hashtable<Scheme, ArrayList<SaltExtendedMarkable>> newMarkables = new Hashtable<Scheme, ArrayList<SaltExtendedMarkable>>();
    SaltExtendedMarkable sDocumentMarkable = null;
    SaltExtendedMarkable sDocumentGraphMarkable = null;
    for (SaltExtendedMarkable markable : markables) {
        registerMarkable(markable);
        if (!markable.hasSaltInformation()) { // new markable originally produced with Mmax2   
            ArrayList<SaltExtendedMarkable> markableOfScheme = newMarkables
                    .get(markable.getFactory().getScheme());
            if (markableOfScheme == null) {
                markableOfScheme = new ArrayList<SaltExtendedMarkable>();
                newMarkables.put(markable.getFactory().getScheme(), markableOfScheme);
            }
            markableOfScheme.add(markable);
        } else { // markables originally produced (exported) from SAlt
            String sType = markable.getSType();
            String key = markable.getSId();

            if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOCUMENT)) {
                if (sDocumentMarkable != null) {
                    throw new PepperModuleDataException(this,
                            "Two SDocument markable have been found: markables '" + markable.getId() + "' and '"
                                    + sDocumentMarkable.getId() + "'");
                }
                sDocumentMarkable = markable;
                correspondanceSAnnotations.put(key, sDocument);
                correspondanceSMetaAnnotations.put(key, sDocument);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOCUMENT_GRAPH)) {
                if (sDocumentGraphMarkable != null) {
                    throw new PepperModuleDataException(this,
                            "Two SDocumentGraph markable have been found: markables '" + markable.getId()
                                    + "' and '" + sDocumentGraphMarkable.getId() + "'");
                }
                sDocumentGraphMarkable = markable;
                correspondanceSAnnotations.put(key, sDocumentGraph);
                correspondanceSMetaAnnotations.put(key, sDocumentGraph);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SLAYER)) {
                SLayer sLayer = createSLayer(sDocumentGraph, markable);
                correspondanceSAnnotations.put(key, sLayer);
                correspondanceSMetaAnnotations.put(key, sLayer);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STEXTUALDS)) {
                STextualDS sTextualDS = createSTextualDS(sDocumentGraph, markable,
                        sTextualDSBaseDataUnits.get(markable), indicesTokens);
                correspondanceSAnnotations.put(key, sTextualDS);
                correspondanceSMetaAnnotations.put(key, sTextualDS);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STOKEN)) {
                SToken sToken = createSToken(sDocumentGraph, markable);
                correspondanceSAnnotations.put(key, sToken);
                correspondanceSMetaAnnotations.put(key, sToken);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSTRUCT)) {
                SStructure sStruct = createSStruct(sDocumentGraph, markable);
                correspondanceSAnnotations.put(key, sStruct);
                correspondanceSMetaAnnotations.put(key, sStruct);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSPAN)) {
                SSpan sSpan = createSSPan(sDocumentGraph, markable);
                correspondanceSAnnotations.put(key, sSpan);
                correspondanceSMetaAnnotations.put(key, sSpan);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STEXTUAL_REL)) {
                sTextRelMarkables.add(markable);
                STextualRelation sTextualRelation = createSTextualRelation(sDocumentGraph, markable);
                sTextRelNodes.add(sTextualRelation);
                correspondanceSAnnotations.put(key, sTextualRelation);
                correspondanceSMetaAnnotations.put(key, sTextualRelation);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSPANNING_REL)) {
                sSpanRelMarkables.add(markable);
                SSpanningRelation sSpanningRelation = createSSpanningRelation(sDocumentGraph, markable);
                sSpanRelNodes.add(sSpanningRelation);
                correspondanceSAnnotations.put(key, sSpanningRelation);
                correspondanceSMetaAnnotations.put(key, sSpanningRelation);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOMINANCE_REL)) {
                sDomRelMarkables.add(markable);
                SDominanceRelation sDomRel = createSDomRel(sDocumentGraph, markable);
                sDomRelNodes.add(sDomRel);
                correspondanceSAnnotations.put(key, sDomRel);
                correspondanceSMetaAnnotations.put(key, sDomRel);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SPOINTING_REL)) {
                sPointerMarkables.add(markable);
                SPointingRelation sPointer = createSPointer(sDocumentGraph, markable);
                sPointerNodes.add(sPointer);
                correspondanceSAnnotations.put(key, sPointer);
                correspondanceSMetaAnnotations.put(key, sPointer);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SANNOTATION)) {
                sAnnotationMarkables.add(markable);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SMETAANNOTATION)) {
                sMetaAnnotationMarkables.add(markable);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SLAYER_LINK)) {
                sLayerLinkMarkables.add(markable);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STYPE_LINK)) {
                sTypeLinkMarkables.add(markable);
            } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SCONTAINER)) {
                sContainerMarkables.add(markable);
            } else {
                throw new PepperModuleException("Developper error:Unknown type '" + sType + "'");
            }
        }
    }

    if (sDocumentMarkable != null) {
        sDocument.setName(sDocumentMarkable.getSName());
    }

    if (sDocumentGraphMarkable != null) {
        sDocumentGraph.setName(sDocumentGraphMarkable.getSName());
    }

    for (SaltExtendedMarkable markable : sContainerMarkables) {
        handleSContainer(markable);
    }

    /* Setting up the SAnnotations and SMetaAnnotations on the nodes and edges */
    for (SaltExtendedMarkable markable : sAnnotationMarkables) {
        createSAnnotation(sDocumentGraph, correspondanceSAnnotations.get(markable.getSId()), markable);
    }

    for (SaltExtendedMarkable markable : sMetaAnnotationMarkables) {
        createSMetaAnnotation(sDocumentGraph, correspondanceSMetaAnnotations.get(markable.getSId()), markable);
    }

    for (SaltExtendedMarkable markable : sLayerLinkMarkables) {
        createSLayerLink(sDocumentGraph, markable);
    }

    /* linking all nodes and edges together */

    for (int i = 0; i < sTextRelNodes.size(); i++) {
        completeSTextualRelation(sTextRelNodes.get(i), sTextRelMarkables.get(i), indicesTokens);
    }

    for (int i = 0; i < sDomRelNodes.size(); i++) {
        completeSDomRel(sDomRelNodes.get(i), sDomRelMarkables.get(i));
    }

    for (int i = 0; i < sSpanRelNodes.size(); i++) {
        completeSPanningRelation(sSpanRelNodes.get(i), sSpanRelMarkables.get(i));
    }

    for (int i = 0; i < sPointerNodes.size(); i++) {
        completeSPointer(sPointerNodes.get(i), sPointerMarkables.get(i));
    }

    for (SaltExtendedMarkable markable : sTypeLinkMarkables) {
        createSTypeLink(markable);
    }

    /* Creating new SSpans */

    SLayer mmaxSLayer = null;
    if (newMarkables.keySet().size() != 0) { // => means "new Markables created since export from salt"
        for (SLayer sLayer : this.sLayerHash.values()) {
            if (sLayer.getName().equals("Mmax2_SLayer")) {
                mmaxSLayer = sLayer;
                break;
            }
        }
        if (mmaxSLayer == null) {
            mmaxSLayer = SaltFactory.createSLayer();
            mmaxSLayer.setName("Mmax2_SLayer");
            mmaxSLayer.setId("Mmax2_SLayer");
            sDocumentGraph.addLayer(mmaxSLayer);
        }

        for (Scheme scheme : newMarkables.keySet()) {
            String schemeName = scheme.getName();
            ArrayList<SaltExtendedMarkable> markablesToIgnore = new ArrayList<SaltExtendedMarkable>();
            ArrayList<SaltExtendedMarkable> schemeMarkables = newMarkables.get(scheme);
            for (SaltExtendedMarkable markable : schemeMarkables) {
                String span = markable.getSpan();
                String[] spans = span.split(",");
                ArrayList<String> baseDateUnitIds = new ArrayList<String>();
                for (int i = 0; i < spans.length; i++) {
                    baseDateUnitIds.addAll(getBaseUnitIds(spans[i]));
                }

                boolean containsNoPointers = true;
                for (MarkableAttribute markableAttribute : markable.getAttributes()) {
                    String attributeType = markableAttribute.getFactory().getAttributeType();
                    if (attributeType.equals(MarkablePointerAttributeFactory.pointerType)) {
                        containsNoPointers = false;
                    }
                }
                boolean isMetaMarkable = false;
                if (containsNoPointers) {
                    if (baseDateUnitIds.size() >= nbBaseDataUnits - 1) {// To remove someday...
                        isMetaMarkable = true;
                    }
                }

                if (isMetaMarkable == false) {
                    SSpan sSpan = SaltFactory.createSSpan();
                    sSpan.setName(schemeName);
                    sSpan.setId(getNewSid(schemeName));

                    sDocumentGraph.addNode(sSpan);
                    registerSNode(markable, sSpan);

                    SAnnotation sAnnotation = SaltFactory.createSAnnotation();
                    sAnnotation.setNamespace("Mmax2");
                    sAnnotation.setName("markable_scheme");
                    sAnnotation.setValue(schemeName);
                    sSpan.addAnnotation(sAnnotation);

                    mmaxSLayer.addNode(sSpan);

                    for (String baseDataUnitId : baseDateUnitIds) {
                        SToken sToken = getSToken(baseDataUnitId, indicesTokens);

                        SSpanningRelation sSpanRel = SaltFactory.createSSpanningRelation();
                        sSpanRel.setSource(sSpan);
                        sSpanRel.setTarget(sToken);

                        sDocumentGraph.addRelation(sSpanRel);
                        mmaxSLayer.addRelation(sSpanRel);
                    }
                } else {
                    for (MarkableAttribute markableAttribute : markable.getAttributes()) {
                        SMetaAnnotation sMetaAnnotation = SaltFactory.createSMetaAnnotation();
                        sMetaAnnotation.setName(markableAttribute.getName());
                        sMetaAnnotation.setNamespace("Mmax2");

                        String value = markableAttribute.getValue();
                        value = value.replaceAll("\n", "");
                        sMetaAnnotation.setValue(value);
                        sDocument.addMetaAnnotation(sMetaAnnotation);

                        markablesToIgnore.add(markable);
                    }
                }
            }
            schemeMarkables.removeAll(markablesToIgnore);
        }
    }

    /* handling all attributes on newly produced (i.e non-exported) markables */

    if (newMarkables.keySet().size() != 0) { // => means "new Markables created since export from salt"
        for (Scheme scheme : newMarkables.keySet()) {
            for (SaltExtendedMarkable markable : newMarkables.get(scheme)) {
                SSpan sSpan = (SSpan) getSNode(markable);

                for (MarkableAttribute markableAttribute : markable.getAttributes()) {
                    String attributeType = markableAttribute.getFactory().getAttributeType();

                    if (attributeType.equals(MarkableFreetextAttributeFactory.freetextType)
                            || attributeType.equals(MarkableNominalAttributeFactory.nominalType)
                            || attributeType.equals(MarkableSetAttributeFactory.setType)) {
                        SAnnotation sAnnotation = SaltFactory.createSAnnotation();
                        String value = markableAttribute.getValue();
                        value = value.replaceAll("\n", "");
                        if (markableAttribute.getName().equals("markable_sheme")) {
                            sAnnotation.setName(value);
                        } else {
                            sAnnotation.setName(scheme.getName() + "_" + markableAttribute.getName());
                        }
                        sAnnotation.setNamespace("Mmax2");
                        sAnnotation.setValue(value);
                        sSpan.addAnnotation(sAnnotation);
                    } else if (attributeType.equals(MarkablePointerAttributeFactory.pointerType)) {
                        MarkablePointerAttributeFactory factory = (MarkablePointerAttributeFactory) markableAttribute
                                .getFactory();
                        String markablePointerValue = markableAttribute.getValue();
                        String[] markablePointerValues = markablePointerValue.split(";");

                        if (markablePointerValues.length == 0) {
                            throw new PepperModuleDataException(this,
                                    "The target of the pointer '" + markableAttribute.getName()
                                            + "' within markable '" + markable + "' is empty...");
                        }

                        for (int i = 0; i < markablePointerValues.length; i++) {
                            SPointingRelation sPointingRelation = SaltFactory.createSPointingRelation();
                            sPointingRelation.setName(markableAttribute.getName());
                            sDocumentGraph.addRelation(sPointingRelation);
                            sPointingRelation.setType(markableAttribute.getName());
                            sPointingRelation.setSource(sSpan);

                            SaltExtendedMarkable targetMarkable = getMarkable(markablePointerValues[i],
                                    factory.getTargetSchemeName());
                            if (targetMarkable == null)
                                throw new PepperModuleDataException(this,
                                        "An unknown markable of id '" + markablePointerValues[i]
                                                + "' belonging to scheme '" + factory.getTargetSchemeName()
                                                + "' is referenced as the target of the pointer '"
                                                + markableAttribute.getName() + "' within markable '" + markable
                                                + "'");
                            SNode sTarget = getSNode(targetMarkable);
                            sPointingRelation.setTarget((SStructuredNode) sTarget);
                            mmaxSLayer.addRelation(sPointingRelation);
                            sPointingRelation.getLayers().add(mmaxSLayer);
                        }
                    } else {
                        throw new PepperModuleException("Developper error: unknown type of markable attribute '"
                                + attributeType + "'...");
                    }
                }
            }
        }
    }

    // to force creation of STokens for all Base Data units
    for (BaseDataUnit baseDataUnit : baseDataUnits) {
        getSToken(baseDataUnit.getId(), indicesTokens);
    }
}

From source file:com.rhfung.P2PDictionary.DataConnection.java

private boolean DetectBrowser(Hashtable<String, String> headers) {
    boolean browserRequest = false; // detect browser
    browserRequest = !headers.containsKey(HEADER_SPECIAL);

    if (this.state == ConnectionState.NewConnection) {

        // assign remote UID
        if (headers.containsKey(HEADER_SPECIAL)) {
            int remoteID = Integer.parseInt(headers.get(HEADER_SPECIAL));

            // stop duplicate connections
            if (controller.isConnected(remoteID) || remoteID == this.local_uid) {
                WriteDebug("Detected loopback connection");

                //force close
                this.remote_uid = remoteID;
                this.state = ConnectionState.Closing;
                browserRequest = true;/*from   w  ww. j  av  a2  s  .co  m*/
            } else {
                WriteDebug("Hello " + remoteID);

                // finish the connection
                this.remote_uid = remoteID;
                this.state = ConnectionState.PeerNodeConnected;

                controller.onConnected(this);
            }
        } else {
            WriteDebug("Hello web browser");
            this.state = ConnectionState.WebClientConnected;
        }
    }

    return browserRequest;
}