Example usage for java.util Hashtable keySet

List of usage examples for java.util Hashtable keySet

Introduction

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

Prototype

Set keySet

To view the source code for java.util Hashtable keySet.

Click Source Link

Document

Each of these fields are initialized to contain an instance of the appropriate view the first time this view is requested.

Usage

From source file:edu.ku.brc.specify.tasks.InteractionsTask.java

/**
 * @param existingLoan//from   w  ww.  j a va2  s . co  m
 * @param infoRequest
 * @param prepsHash
 */
protected void addPrepsToLoan(final OneToManyProviderIFace existingLoanArg, final InfoRequest infoRequest,
        final Hashtable<Integer, Integer> prepsHash, final Viewable srcViewable) {
    Loan existingLoan = (Loan) existingLoanArg;
    Loan loan;

    if (existingLoan == null) {
        loan = new Loan();
        loan.initialize();

        Calendar dueDate = Calendar.getInstance();
        dueDate.add(Calendar.MONTH, 6); // XXX PREF Due Date
        loan.setCurrentDueDate(dueDate);

        Shipment shipment = new Shipment();
        shipment.initialize();

        // Get Defaults for Certain fields
        //SpecifyAppContextMgr appContextMgr     = (SpecifyAppContextMgr)AppContextMgr.getInstance();

        // Comment out defaults for now until we can manage them
        //PickListItemIFace    defShipmentMethod = appContextMgr.getDefaultPickListItem("ShipmentMethod", getResourceString("SHIPMENT_METHOD"));
        //if (defShipmentMethod != null)
        //{
        //     shipment.setShipmentMethod(defShipmentMethod.getValue());
        //}

        //FormDataObjIFace shippedBy = appContextMgr.getDefaultObject(Agent.class, "ShippedBy", getResourceString("SHIPPED_BY"), true, false);
        //if (shippedBy != null)
        //{
        //    shipment.setShippedBy((Agent)shippedBy);
        //}

        if (infoRequest != null && infoRequest.getAgent() != null) {
            shipment.setShippedTo(infoRequest.getAgent());
        }

        loan.addReference(shipment, "shipments");
    } else {
        loan = existingLoan;
    }

    Hashtable<Integer, LoanPreparation> prepToLoanPrepHash = null;
    if (existingLoan != null) {
        prepToLoanPrepHash = new Hashtable<Integer, LoanPreparation>();
        for (LoanPreparation lp : existingLoan.getLoanPreparations()) {
            prepToLoanPrepHash.put(lp.getPreparation().getId(), lp);
        }
    }

    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        for (Integer prepId : prepsHash.keySet()) {
            Preparation prep = session.get(Preparation.class, prepId);
            Integer count = prepsHash.get(prepId);
            if (prepToLoanPrepHash != null) {
                LoanPreparation lp = prepToLoanPrepHash.get(prep.getId());
                if (lp != null) {
                    int lpCnt = lp.getQuantity();
                    lpCnt += count;
                    lp.setQuantity(lpCnt);
                    continue;
                }
            }

            LoanPreparation lpo = new LoanPreparation();
            lpo.initialize();
            lpo.setPreparation(prep);
            lpo.setQuantity(count);
            lpo.setLoan(loan);
            loan.getLoanPreparations().add(lpo);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(InteractionsTask.class, ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (existingLoan == null) {
        if (srcViewable != null) {
            srcViewable.setNewObject(loan);

        } else {
            DataEntryTask dataEntryTask = (DataEntryTask) TaskMgr.getTask(DataEntryTask.DATA_ENTRY);
            if (dataEntryTask != null) {
                DBTableInfo loanTableInfo = DBTableIdMgr.getInstance().getInfoById(loan.getTableId());
                dataEntryTask.openView(this, null, loanTableInfo.getDefaultFormName(), "edit", loan, true);
            }
        }
    } else {
        CommandDispatcher
                .dispatch(new CommandAction(INTERACTIONS, LoanPreparationBusRules.REFRESH_PREPS, loan));
    }
}

From source file:fr.paris.lutece.plugins.search.solr.business.SolrSearchEngine.java

/**
 * Return the result with facets. Does NOT support authentification yet.
 * @param strQuery the query/*from   w w  w  .j  a  va2  s .com*/
 * @param facetQueries The selected facets
 * @param sortName The facet name to sort by
 * @param sortOrder "asc" or "desc"
 * @param nLimit Maximal number of results.
 * @return the result with facets
 */
public SolrFacetedResult getFacetedSearchResults(String strQuery, String[] facetQueries, String sortName,
        String sortOrder, int nLimit, int nCurrentPageIndex, int nItemsPerPage, Boolean bSpellCheck) {
    SolrFacetedResult facetedResult = new SolrFacetedResult();

    SolrClient solrServer = SolrServerService.getInstance().getSolrServer();
    List<SolrSearchResult> results = new ArrayList<SolrSearchResult>();
    Hashtable<Field, List<String>> myValuesList = new Hashtable<Field, List<String>>();

    if (solrServer != null) {
        SolrQuery query = new SolrQuery(strQuery);
        query.setHighlight(true);
        query.setHighlightSimplePre(SOLR_HIGHLIGHT_PRE);
        query.setHighlightSimplePost(SOLR_HIGHLIGHT_POST);
        query.setHighlightSnippets(SOLR_HIGHLIGHT_SNIPPETS);
        query.setHighlightFragsize(SOLR_HIGHLIGHT_FRAGSIZE);
        query.setFacet(true);
        query.setFacetLimit(SOLR_FACET_LIMIT);
        //            query.setFacetMinCount( 1 );

        for (Field field : SolrFieldManager.getFacetList().values()) {
            //Add facet Field
            if (field.getEnableFacet()) {
                if (field.getName().equalsIgnoreCase("date")
                        || field.getName().toLowerCase().endsWith("_date")) {
                    query.setParam("facet.date", field.getName());
                    query.setParam("facet.date.start", SOLR_FACET_DATE_START);
                    query.setParam("facet.date.gap", SOLR_FACET_DATE_GAP);
                    query.setParam("facet.date.end", SOLR_FACET_DATE_END);
                    query.setParam("facet.date.mincount", "0");
                } else {
                    query.addFacetField(field.getSolrName());
                    query.setParam("f." + field.getSolrName() + ".facet.mincount",
                            String.valueOf(field.getFacetMincount()));
                }
                myValuesList.put(field, new ArrayList<String>());
            }
        }

        //Facet intersection
        List<String> treeParam = new ArrayList<String>();

        for (FacetIntersection intersect : SolrFieldManager.getIntersectionlist()) {
            treeParam.add(intersect.getField1().getSolrName() + "," + intersect.getField2().getSolrName());
        }

        //(String []) al.toArray (new String [0]);
        query.setParam("facet.tree", (String[]) treeParam.toArray(new String[0]));
        query.setParam("spellcheck", bSpellCheck);

        //sort order
        if ((sortName != null) && !"".equals(sortName)) {
            if (sortOrder.equals("asc")) {
                query.setSort(sortName, ORDER.asc);
            } else {
                query.setSort(sortName, ORDER.desc);
            }
        } else {
            for (Field field : SolrFieldManager.getSortList()) {
                if (field.getDefaultSort()) {
                    query.setSort(field.getName(), ORDER.desc);
                }
            }
        }

        //Treat HttpRequest
        //FacetQuery
        if (facetQueries != null) {
            for (String strFacetQuery : facetQueries) {
                //                    if ( strFacetQuery.contains( DATE_COLON ) )
                //                    {
                //                        query.addFilterQuery( strFacetQuery );
                //                    }
                //                    else
                //                    {
                String myValues[] = strFacetQuery.split(":", 2);
                if (myValues != null && myValues.length == 2) {
                    myValuesList = getFieldArrange(myValues, myValuesList);
                }
                //strFacetQueryWithColon = strFacetQuery.replaceFirst( SolrConstants.CONSTANT_COLON, COLON_QUOTE );
                //strFacetQueryWithColon += SolrConstants.CONSTANT_QUOTE;
                //                        query.addFilterQuery( strFacetQuery );
                //                    }
            }

            for (Field tmpFieldValue : myValuesList.keySet()) {
                List<String> strValues = myValuesList.get(tmpFieldValue);
                String strFacetString = "";
                if (strValues.size() > 0) {
                    strFacetString = extractQuery(strValues, tmpFieldValue.getOperator());
                    if (tmpFieldValue.getName().equalsIgnoreCase("date")
                            || tmpFieldValue.getName().toLowerCase().endsWith("_date")) {
                        strFacetString = strFacetString.replaceAll("\"", "");
                    }
                    query.addFilterQuery(tmpFieldValue.getName() + ":" + strFacetString);
                }
            }
        }

        try {

            // count query
            query.setRows(0);
            QueryResponse response = solrServer.query(query);

            int nResults = (int) response.getResults().getNumFound();
            facetedResult.setCount(nResults > nLimit ? nLimit : nResults);

            query.setStart((nCurrentPageIndex - 1) * nItemsPerPage);
            query.setRows(nItemsPerPage > nLimit ? nLimit : nItemsPerPage);

            query.setParam("defType", DEF_TYPE);
            String strWeightValue = generateQueryWeightValue();
            query.setParam("qf", strWeightValue);

            response = solrServer.query(query);

            //HighLight
            Map<String, Map<String, List<String>>> highlightsMap = response.getHighlighting();
            SolrHighlights highlights = null;

            if (highlightsMap != null) {
                highlights = new SolrHighlights(highlightsMap);
            }

            //resultList
            List<SolrItem> itemList = response.getBeans(SolrItem.class);
            results = SolrUtil.transformSolrItemsToSolrSearchResults(itemList, highlights);

            //set the spellcheckresult
            facetedResult.setSolrSpellCheckResponse(response.getSpellCheckResponse());

            //Date facet
            if ((response.getFacetDates() != null) && !response.getFacetDates().isEmpty()) {
                facetedResult.setFacetDateList(response.getFacetDates());
            }

            //FacetField
            facetedResult.setFacetFields(response.getFacetFields());

            //Facet intersection (facet tree)
            NamedList<Object> resp = (NamedList<Object>) response.getResponse().get("facet_counts");

            if (resp != null) {
                NamedList<NamedList<NamedList<Integer>>> trees = (NamedList<NamedList<NamedList<Integer>>>) resp
                        .get("trees");
                Map<String, ArrayList<FacetField>> treesResult = new HashMap<String, ArrayList<FacetField>>();

                if (trees != null) {
                    for (Entry<String, NamedList<NamedList<Integer>>> selectedFacet : trees) { //Selected Facet (ex : type,categorie )
                                                                                               //System.out.println(selectedFacet.getKey());

                        ArrayList<FacetField> facetFields = new ArrayList<FacetField>(
                                selectedFacet.getValue().size());

                        for (Entry<String, NamedList<Integer>> facetField : selectedFacet.getValue()) {
                            FacetField ff = new FacetField(facetField.getKey());

                            //System.out.println("\t" + facetField.getKey());
                            for (Entry<String, Integer> value : facetField.getValue()) { // Second Level
                                ff.add(value.getKey(), value.getValue());

                                //System.out.println("\t\t" + value.getKey() + " : " + value.getValue());
                            }

                            facetFields.add(ff);
                        }

                        treesResult.put(selectedFacet.getKey(), facetFields);
                    }
                }

                facetedResult.setFacetIntersection(treesResult);
            }
        } catch (SolrServerException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        }
    } else {
        facetedResult.setFacetFields(new ArrayList<FacetField>());
    }

    facetedResult.setSolrSearchResults(results);

    return facetedResult;
}

From source file:edu.ku.brc.specify.tasks.WorkbenchTask.java

/**
 * This filters out all non-image files per the image filter and adds them to the Vector.
 * @param files the list of files/*ww w.  j a v a2  s. com*/
 * @param fileList the returned Vector of image files
 * @param imageFilter the filter to use to weed out non-image files
 * @return true if it should continue, false to stop
 */
protected boolean filterSelectedFileNames(final File[] files, final Vector<File> fileList,
        final ImageFilter imageFilter) {
    if (files == null || files.length == 0) {
        return false;
    }

    Hashtable<String, Boolean> badFileExts = new Hashtable<String, Boolean>();

    for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
            String fileName = files[i].getName();
            if (imageFilter.isImageFile(fileName)) {
                fileList.add(files[i]);
            } else {
                badFileExts.put(FilenameUtils.getExtension(fileName), true);
            }
        }
    }

    // No check to see if we had any bad files and warn the user about them
    if (badFileExts.size() > 0) {
        StringBuffer badExtStrBuf = new StringBuffer();
        for (String ext : badFileExts.keySet()) {
            if (badExtStrBuf.length() > 0)
                badExtStrBuf.append(", ");
            badExtStrBuf.append(ext);
        }

        // Now, if none of the files were good we tell them and then quit the import task
        if (fileList.size() == 0) {
            JOptionPane.showMessageDialog(UIRegistry.getMostRecentWindow(),
                    String.format(getResourceString("WB_WRONG_IMG_NO_IMAGES"),
                            new Object[] { badExtStrBuf.toString() }),
                    UIRegistry.getResourceString("WARNING"), JOptionPane.ERROR_MESSAGE);
            return false;

        }

        // So we know we have at least one good image file type
        // So let them choose if they want to continue.
        Object[] options = { getResourceString("Continue"), getResourceString("Stop") };

        if (JOptionPane.showOptionDialog(UIRegistry.getMostRecentWindow(),
                String.format(getResourceString("WB_WRONG_IMG_SOME_IMAGES"),
                        new Object[] { badExtStrBuf.toString() }),
                title, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[1]) == JOptionPane.NO_OPTION) {
            return false;
        }
    }
    return true;
}

From source file:org.lexevs.system.ResourceManager.java

public String getInternalVersionStringForTag(String externalCodeSystemName, String tag)
        throws LBParameterException {
    if (externalCodeSystemName == null || externalCodeSystemName.length() == 0) {
        throw new LBParameterException("The parameter is required", SQLTableConstants.TBLCOL_CODINGSCHEMENAME);
    }// w  w  w .  ja va  2  s .com

    // I'm going to cache this, because it is kind of expensive, and may be
    // a frequent operation
    String key = "internalVersionStringForTag:" + externalCodeSystemName + ":"
            + (tag == null || tag.length() == 0 ? KnownTags.PRODUCTION.toString() : tag);

    String version = (String) cache_.get(key);

    if (version != null) {
        return version;
    }

    // not in the cache, find it.

    Hashtable<String, String> temp = codingSchemeLocalNamesToInternalNameMap_.get(externalCodeSystemName);
    if (temp == null) {
        throw new LBParameterException("No coding scheme could be located for the values you provided",
                SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                externalCodeSystemName + ", " + tag);
    }

    // The hashtable that is returned is a mapping of versions to the
    // internal code system names.
    // it is likely but not guaranteed that all of the code system names
    // will be identical.
    // They should all map to the SAME urn however, so get the URN for the
    // first one.
    // ask the registry for the version number associated with the given tag
    // on the (found) urn.

    Enumeration<String> e = temp.elements();
    String urn = "";
    if (e.hasMoreElements()) {
        Set<String> uris = getAllURNsForInternalCodingSchemeName(e.nextElement());
        if (uris.size() == 1) {
            urn = uris.iterator().next();
        } else {
            if (uris.contains(externalCodeSystemName)) {
                for (String uri : uris) {
                    if (uri.equals(externalCodeSystemName)) {
                        urn = uri;
                    }
                }
            }
        }
    } else {
        throw new LBParameterException("No coding scheme could be located for the values you provided",
                SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                externalCodeSystemName + ", " + tag);
    }

    // if the tag is missing or null, then we should use "PRODUCTION"
    version = registry_.getVersionForTag(urn,
            (tag == null || tag.length() == 0 ? KnownTags.PRODUCTION.toString() : tag));

    if (version == null) {
        if (tag != null && !tag.equals(KnownTags.PRODUCTION.toString())) {
            // if they specified a tag, and it wasn't the production tag,
            // and we didn't find it
            // then the tag is invalid.
            throw new LBParameterException(
                    "No version of the code system " + externalCodeSystemName + " is tagged as " + tag);
        }
        // they didn't specify a tag, or the specified production, but
        // nothing it tagged
        // as production. If we only have one that matches, return it. Else,
        // ask for clairification.
        else if (temp.size() > 1) {

            throw new LBParameterException(
                    "Multiple code systems matched the values you provided - please be more specific (or designate one of the code systems as 'PRODUCTION'",
                    SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                    externalCodeSystemName + ", " + tag);
        } else {
            version = temp.keySet().toArray(new String[temp.size()])[0];
        }
    }

    cache_.put(key, version);
    return version;
}

From source file:pt.iflow.flows.FlowData.java

@Deprecated
private InstantiationResult instantiateSubFlow(UserInfoInterface ui, XmlBlock xmlblock, int anFlowId,
        List<FlowSetting> alSettings, Hashtable<Integer, Block> htBlocks, int offset) throws Exception {
    Class<?>[] argsClass = new Class[] { int.class, int.class, int.class, String.class };
    String subflow = null;//from   w w  w .  ja v a2s  .  c  o m
    Attribute attrActiv = null;
    final int FLOW = 0;
    final int SUBFLOW = 1;
    final int TYPE = 2;

    offset += iOFFSET;

    int size = (xmlblock.getXmlAttributeCount() - 1) / 4; // raio de conta

    String[][] saInVars = new String[size][3];
    String[][] saOutVars = new String[size][3];

    // Attributes do block In & Out
    for (int attrNumber = 0; attrNumber < xmlblock.getXmlAttributeCount(); attrNumber++) {
        XmlAttribute xmlAttribute = xmlblock.getXmlAttribute(attrNumber);
        String name = xmlAttribute.getName();

        int pos = -1;
        try {
            pos = Integer.parseInt(name.substring(8, 9));
        } catch (NumberFormatException nfe) {
        }

        if (name.charAt(0) == 'I') {
            if (name.substring(1, 8).equals("bigflow")) {
                saInVars[pos][FLOW] = xmlAttribute.getValue();
            } else {
                saInVars[pos][SUBFLOW] = xmlAttribute.getValue();
            }
        } else if (name.charAt(0) == 'O') {
            if (name.substring(1, 8).equals("bigflow")) {
                saOutVars[pos][FLOW] = xmlAttribute.getValue();
            } else {
                saOutVars[pos][SUBFLOW] = xmlAttribute.getValue();
            }
        } else if (name.charAt(0) == 'M') {
            subflow = xmlAttribute.getValue();
        } else if (name.charAt(0) == 'A') {
            attrActiv = new Attribute(xmlAttribute.getName(), xmlAttribute.getValue());
        } else if (name.charAt(0) == 'T') {
            saInVars[pos][TYPE] = xmlAttribute.getValue();
            saOutVars[pos][TYPE] = xmlAttribute.getValue();
        }
    }

    if (!this.hasSubFlow(subflow)) {
        this._htSubFlows.put(subflow, subflow);
    } else {
        throw new Exception("Recursividade de Fluxos encontrada!");
    }
    byte[] sXml = BeanFactory.getFlowHolderBean().readSubFlowData(ui, subflow);
    XmlFlow xmlSubFlow = FlowMarshaller.unmarshal(sXml);
    InstantiationResult flowResult = instantiateFlow(ui, xmlSubFlow, anFlowId, alSettings, htBlocks, offset);

    if (flowResult == null) {
        throw new Exception("N&atilde;o foi possivel instanciar o subfluxo " + subflow);
    } else if (flowResult.start == null) {
        throw new Exception("O subfluxo " + subflow + " n&atilde;o tem BlockStart");
    } else if (flowResult.end == null || flowResult.end.size() == 0) {
        throw new Exception("O subfluxo " + subflow + " n&atilde;o tem BlockEnd");
    }

    if (!_htSubFlowEndPorts.containsKey(subflow)) {
        Hashtable<Integer, Object[]> htPorts = new Hashtable<Integer, Object[]>();
        this.buildConnEndPorts(ui, htBlocks, htPorts, flowResult.start);
        _htSubFlowEndPorts.put(subflow, htPorts);
    }

    // remove the start & end blocks
    // replace them by BlockSubFlowIn & BlockSubFlowOut
    htBlocks.remove(new Integer(flowResult.start.getId()));
    this._vFlow.remove(flowResult.start);
    Iterator<Block> it = flowResult.getEndIterator();
    while (it.hasNext()) {
        Block bEnd = it.next();
        htBlocks.remove(new Integer(bEnd.getId()));
        this._vFlow.remove(bEnd);
    }

    // BlockSubFlowIn
    Integer blockIdIn = new Integer(flowResult.start.getId() - 100000);
    Object[] args = new Object[] { new Integer(anFlowId), blockIdIn, new Integer(0), new String(subflow) };
    String className = "pt.iflow.blocks.BlockSubFlowIn";
    Class<? extends Block> blockClassIn = loadBlockClass(ui, className);
    Constructor<? extends Block> argsConstructor = blockClassIn.getConstructor(argsClass);
    Block bBlockIn = argsConstructor.newInstance(args);

    // attributes
    for (int i = 0; i < saInVars.length; i++) {
        if (StringUtils.isEmpty(saInVars[i][FLOW]) || StringUtils.isEmpty(saInVars[i][SUBFLOW]))
            continue;
        Attribute attr = new Attribute();
        attr.setName(saInVars[i][FLOW]);
        attr.setValue(saInVars[i][SUBFLOW]);
        bBlockIn.addAttribute(attr);
        attr = new Attribute("Type_" + saInVars[i][FLOW], saInVars[i][TYPE]);
        bBlockIn.addAttribute(attr);
    }

    // BlockSubFlowOut
    Integer blockIdOut = new Integer(flowResult.end.get(0).getId() - 100000);
    args = new Object[] { new Integer(anFlowId), blockIdOut, new Integer(0), new String(subflow) };
    className = "pt.iflow.blocks.BlockSubFlowOut";
    Class<? extends Block> blockClassOut = loadBlockClass(ui, className);
    argsConstructor = blockClassOut.getConstructor(argsClass);
    Block bBlockOut = argsConstructor.newInstance(args);

    for (int i = 0; i < saOutVars.length; i++) {
        if (saOutVars[i][FLOW] == null || saOutVars[i][FLOW].equals("") || saOutVars[i][SUBFLOW] == null
                || saOutVars[i][SUBFLOW].equals(""))
            continue;
        Attribute attr = new Attribute();
        attr.setName(saOutVars[i][FLOW]);
        attr.setValue(saOutVars[i][SUBFLOW]);
        bBlockOut.addAttribute(attr);
        attr = new Attribute("Type_" + saOutVars[i][FLOW], saOutVars[i][TYPE]);
        bBlockOut.addAttribute(attr);
    }
    if (attrActiv != null)
        bBlockOut.addAttribute(attrActiv);

    // portos do BlockSubFlowIn
    Port port = null;
    try {
        XmlPort xmlPort = xmlblock.getXmlPort(0); // portIn -> portIn
        port = new Port();
        port.setName("portIn");
        port.setConnectedBlockId(xmlPort.getConnectedBlockId() + (offset - iOFFSET));
        port.setConnectedPortName(xmlPort.getConnectedPortName());
        Field fPort = blockClassIn.getField("portIn");
        fPort.set(bBlockIn, port);

        port = new Port(); // portOutThread
        port.setName("portOutThread");
        port.setConnectedBlockId(bBlockOut.getId());
        port.setConnectedPortName("portInThread");
        fPort = blockClassIn.getField("portOutThread");
        fPort.set(bBlockIn, port);

        port = new Port(); // portOut
        port.setName("portOut");
        fPort = blockClassIn.getField("portOut");
        fPort.set(bBlockIn, port);

        Port[] patmp = flowResult.start.getOutPorts(ui);
        for (int p = 0; patmp != null && p < patmp.length; p++) {
            if (patmp[p] == null)
                continue;

            Integer iBId = new Integer(patmp[p].getConnectedBlockId());
            Block bInnerBlock = (Block) htBlocks.get(iBId);
            if (bInnerBlock == null)
                continue;

            bInnerBlock.getInPorts(ui)[0].setConnectedBlockId(bBlockIn.getId());
            bBlockIn.getOutPorts(ui)[0].setConnectedBlockId(patmp[p].getConnectedBlockId());
            bBlockIn.getOutPorts(ui)[0].setConnectedPortName(patmp[p].getConnectedPortName());
        }

        //       xmlPort = xmlblock.getXmlPort(2); // portError -> portError
        //       port = new Port();
        //       port.setName("portError");
        //       port.setConnectedBlockId(xmlPort.getConnectedBlockId()
        //           + (offset - iOFFSET));
        //       port.setConnectedPortName(xmlPort.getConnectedPortName());
        //       fPort = blockClassIn.getField("portError");
        //       fPort.set(bBlockIn, port);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Erro ao criar porto " + port.getName() + " para o bloco SubFlowIn");
    }

    // portos do BlockSubFlowOut
    try {
        port = new Port(); // portIn
        port.setName("portIn");
        Field fPort = blockClassOut.getField("portIn");
        fPort.set(bBlockOut, port);

        Hashtable<Integer, Object[]> htPorts = _htSubFlowEndPorts.get(subflow);
        Iterator<Integer> portIt = htPorts.keySet().iterator();
        while (portIt.hasNext()) {
            Integer itmp = portIt.next();
            Object[] otmp = (Object[]) htPorts.get(itmp);
            Port outPort = (Port) otmp[0];

            outPort.setConnectedBlockId(bBlockOut.getId());
            outPort.setConnectedPortName(port.getName());

            bBlockOut.getInPorts(ui)[0].setConnectedBlockId(itmp.intValue());
            bBlockOut.getInPorts(ui)[0].setConnectedPortName(outPort.getName());
        }

        port = new Port(); // portInThread
        port.setName("portInThread");
        port.setConnectedBlockId(bBlockIn.getId());
        port.setConnectedPortName("portOutThread");
        fPort = blockClassOut.getField("portInThread");
        fPort.set(bBlockOut, port);

        XmlPort xmlPort = xmlblock.getXmlPort(1); // portSuccess -> portOut
        port = new Port();
        port.setName("portOut");
        port.setConnectedBlockId(xmlPort.getConnectedBlockId() + (offset - iOFFSET));
        port.setConnectedPortName(xmlPort.getConnectedPortName());
        fPort = blockClassOut.getField("portOut");
        fPort.set(bBlockOut, port);

        //       xmlPort = xmlblock.getXmlPort(2); // portError
        //       port = new Port();
        //       port.setName("portError");
        //       port.setConnectedBlockId(xmlPort.getConnectedBlockId()
        //           + (offset - iOFFSET));
        //       port.setConnectedPortName(xmlPort.getConnectedPortName());
        //       fPort = blockClassOut.getField("portError");
        //       fPort.set(bBlockOut, port);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Erro ao criar porto " + port.getName() + " para o bloco SubFlowOut");
    }

    this._vFlow.add(bBlockIn);
    this._vFlow.add(bBlockOut);

    htBlocks.put(blockIdIn, bBlockIn);
    htBlocks.put(blockIdOut, bBlockOut);

    ArrayList<Block> altmp = new ArrayList<Block>();
    altmp.add(bBlockOut);

    return new InstantiationResult(bBlockIn, altmp);
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * PROPPATCH Method./*from   w  ww . j a  v  a  2 s  .  c  o m*/
 */
@SuppressWarnings("deprecation")
protected void doProppatch(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Check that the resource is not locked
    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
    }

    // we can't actually do this, but MS requires us to. Say we did.
    // I'm trying to be as close to valid here, so I generate an OK
    // for all the properties they tried to set. This is really hairy because
    // it gets into name spaces. But if we ever try to implement this for real,
    // we'll have to do this. So might as well start now.
    //    During testing I found by mistake that it's actually OK to send
    // an empty multistatus return, so I don't actually  need all of this stuff.
    //    The big problem is that the properties are typically not in the dav namespace
    // we build a hash table of namespaces, with the prefix we're going to use
    // since D: is used for dav, we start with E:, actually D+1

    DocumentBuilder documentBuilder = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

        documentBuilder = factory.newDocumentBuilder();
    } catch (Exception e) {
        resp.sendError(SakaidavStatus.SC_METHOD_FAILURE);
        return;
    }

    int contentLength = req.getContentLength();

    // a list of the properties with the new prefix
    List<String> props = new ArrayList<String>();
    // hash of namespace, prefix
    Hashtable<String, String> spaces = new Hashtable<String, String>();

    // read the xml document
    if (contentLength > MAX_XML_STREAM_LENGTH) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } else if (contentLength > 0) {

        byte[] byteContent = new byte[contentLength];
        InputStream inputStream = req.getInputStream();

        int lenRead = 0;

        try {
            while (lenRead < contentLength) {
                int read = inputStream.read(byteContent, lenRead, contentLength - lenRead);
                if (read <= 0)
                    break;
                lenRead += read;
            }
        } catch (Exception ignore) {
        }

        // Parse the input XML to see what they really want
        if (lenRead > 0)
            try {
                // if we got here, "is" is the xml document
                InputStream is = new ByteArrayInputStream(byteContent, 0, lenRead);
                Document document = documentBuilder.parse(new InputSource(is));

                // Get the root element of the document
                Element rootElement = document.getDocumentElement();
                // find all the property nodes
                NodeList childList = rootElement.getElementsByTagNameNS("DAV:", "prop");

                int nextChar = 1;

                for (int i = 0; i < childList.getLength(); i++) {

                    // this should be a prop node
                    Node currentNode = childList.item(i);
                    // this should be the actual property
                    NodeList names = currentNode.getChildNodes();
                    // this should be the name
                    for (int j = 0; j < names.getLength(); j++) {
                        String namespace = names.item(j).getNamespaceURI();
                        String prefix = spaces.get(namespace);
                        // see if we know about this namespace. If not add it and
                        // generate a prefix
                        if (prefix == null) {
                            prefix = "" + Character.toChars('D' + nextChar)[0];
                            spaces.put(namespace, prefix);
                        }
                        props.add(prefix + ":" + names.item(j).getLocalName());
                    }
                }
            } catch (Exception ignore) {
            }
    }

    resp.setStatus(SakaidavStatus.SC_MULTI_STATUS);
    resp.setContentType("text/xml; charset=UTF-8");

    Writer writer = resp.getWriter();

    writer.write("<D:multistatus xmlns:D=\"DAV:\"");
    // dump all the name spaces and their prefix
    for (String namespace : spaces.keySet())
        writer.write(" xmlns:" + spaces.get(namespace) + "=\"" + namespace + "\"");
    writer.write("><D:response><D:href>" + javax.servlet.http.HttpUtils.getRequestURL(req) + "</D:href>");
    // now output properties, claiming we did it
    for (String pname : props) {
        writer.write("<D:propstat><D:prop><" + pname
                + "/></D:prop><D:status>HTTP/1.1 201 OK</D:status></D:propstat>");
    }
    writer.write("</D:response></D:multistatus>");
    writer.close();

}

From source file:ome.formats.OMEROMetadataStoreClient.java

/**
 * Creates a temporary file on disk containing all metadata in the
 * Bio-Formats metadata hash table for the current series.
 * @param suffix String that will be appended to the end of the temporary
 * file path./*ww  w  . jav  a  2s. co  m*/
 * @return Temporary file created.
 */
private File createSeriesMetadataFile(String suffix) {
    Hashtable<?, ?> globalMetadata = reader.getGlobalMetadata();
    Hashtable<?, ?> seriesMetadata = reader.getSeriesMetadata();
    if (globalMetadata.size() == 0 && seriesMetadata.size() == 0) {
        return null;
    }
    FileOutputStream stream = null;
    OutputStreamWriter writer = null;
    try {
        File metadataFile = TempFileManager.createTempFile(ORIGINAL_METADATA_KEY, suffix);
        stream = new FileOutputStream(metadataFile);
        writer = new OutputStreamWriter(stream);
        metadataFile.deleteOnExit();
        writer.write("[GlobalMetadata]\n");
        for (Object key : globalMetadata.keySet()) {
            String s = key.toString() + "=" + globalMetadata.get(key).toString() + "\n";
            writer.write(s);
        }
        writer.write("[SeriesMetadata]\n");
        for (Object key : seriesMetadata.keySet()) {
            String s = key.toString() + "=" + seriesMetadata.get(key).toString() + "\n";
            writer.write(s);
        }
        return metadataFile;
    } catch (IOException e) {
        log.error("Unable to create series metadata file.", e);
        return null;
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            log.error("Unable to close writer or stream.", e);
        }
    }
}

From source file:pt.iflow.flows.FlowData.java

private InstantiationResult instantiateFlow(UserInfoInterface ui, XmlFlow aXmlFlow, int anFlowId,
        List<FlowSetting> alSettings, Hashtable<Integer, Block> htBlocks, int offset) throws Exception {

    Block blockStart = null;//from w w w.ja v  a  2  s. c o m
    ArrayList<Block> alBlockEnd = null;
    Hashtable<Integer, Integer> htPortMapIn = new Hashtable<Integer, Integer>();
    Hashtable<Integer, Integer> htPortMapOut = new Hashtable<Integer, Integer>();
    Class<? extends Block> blockClass = null;
    LicenseService licService = LicenseServiceFactory.getLicenseService();

    for (int b = 0; b < aXmlFlow.getXmlBlockCount(); b++) {
        XmlBlock block = aXmlFlow.getXmlBlock(b);
        String blockType = block.getType();

        try {
            licService.canInstantiateBlock(ui, blockType);
        } catch (LicenseServiceException e) {
            throw new ForbiddenBlockException(blockType);
        }

        // 10/01/2012 - P.Ussman - No longer used due to issue 578 solution  
        //       if (blockType.equals("BlockSubFlow")) {
        //         InstantiationResult subflowResult = this.instantiateSubFlow(ui,
        //             block, anFlowId, alSettings, htBlocks, offset);
        //         htPortMapIn.put(new Integer(block.getId()), new Integer(
        //             subflowResult.start.getId()));
        //         Iterator<Block> it = subflowResult.getEndIterator();
        //         while (it.hasNext()) {
        //           Block bEnd = it.next();
        //           htPortMapOut.put(new Integer(block.getId()), new Integer(
        //               bEnd.getId()));
        //         }

        //         continue;
        //       }

        Integer blockId = new Integer(block.getId() + offset);

        try {
            String stmp = BLOCK_PACKAGE + blockType;
            blockClass = loadBlockClass(ui, stmp);
        } catch (ClassNotFoundException cnfe) {
            throw new Exception("Erro ao criar bloco " + blockType, cnfe);
        }

        Logger.debug(null, this, "constructor", "Processing block " + blockClass.getName());
        Constructor<? extends Block> argsConstructor = blockClass.getConstructor(int.class, int.class,
                int.class, String.class);
        Block bBlock = argsConstructor.newInstance(anFlowId, blockId, block.getId(), aXmlFlow.getName());

        XmlPort xmlPort = null;
        try {
            // Ports
            for (int portNumber = 0; portNumber < block.getXmlPortCount(); portNumber++) {
                xmlPort = block.getXmlPort(portNumber);
                Logger.debug(null, this, "constructor", "Processing port " + xmlPort.getName());

                Port port = new Port();
                port.setName(xmlPort.getName());
                port.setConnectedBlockId(xmlPort.getConnectedBlockId() + offset);
                port.setConnectedPortName(xmlPort.getConnectedPortName());
                if (xmlPort.getName().equals("portEvent"))
                    bBlock.setHasEvent(true);

                Field fPort = blockClass.getField(xmlPort.getName());
                fPort.set(bBlock, port);
            }
        } catch (Exception e) {
            throw new Exception("Erro ao criar porto " + xmlPort.getName() + " para o bloco " + block.getType(),
                    e);
        }

        HashMap<String, String> hmtmp = new HashMap<String, String>();
        // Attributes
        for (int attrNumber = 0; attrNumber < block.getXmlAttributeCount(); attrNumber++) {
            XmlAttribute xmlAttribute = block.getXmlAttribute(attrNumber);

            String name = xmlAttribute.getName();
            String value = xmlAttribute.getValue();

            if (value == null)
                value = "";

            if (name.startsWith(IFlowData.sSETTING) || name.startsWith(IFlowData.sSETTING_DESC)) {
                hmtmp.put(name, value);
                continue;
            }

            try {
                Logger.debug(null, this, "constructor", "Processing attribute " + name + "=" + value);

                Attribute attribute = new Attribute();
                attribute.setName(name);
                attribute.setValue(value);
                bBlock.addAttribute(attribute);
            } catch (Exception e) {
                throw new Exception("Erro ao criar atributo " + name + " para o bloco " + blockType, e);
            }
        }

        HashSet<String> hsSettings = new HashSet<String>();
        Iterator<String> iter = hmtmp.keySet().iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next();
            if (!name.startsWith(IFlowData.sSETTING))
                continue;

            String stmp = name.substring(IFlowData.sSETTING.length());
            name = hmtmp.get(name);
            if (hsSettings.contains(name))
                continue;

            try {
                String value = hmtmp.get(IFlowData.sSETTING_DESC + stmp);
                Logger.debug(null, this, "constructor", "Processing setting " + name + " (" + value + ")");
                alSettings.add(new FlowSetting(anFlowId, name, value));
                hsSettings.add(name);
            } catch (Exception e) {
                throw new Exception("Erro ao criar propriedade " + name + " para o bloco " + blockType, e);
            }
        }

        //Updates PopUp flow conected block id
        bBlock.setBlockRunningInPopup(block.getPopupReturnBlockId());

        // refresh block's cache
        bBlock.refreshCache(ui);

        // Add the block to the vector
        this._vFlow.add(bBlock);

        // keeps a reference to Start Block to build ForkJoin dependency
        // path
        if (bBlock.isStartBlock()) {
            blockStart = bBlock;
        } else if (bBlock.isEndBlock()) {
            if (alBlockEnd == null)
                alBlockEnd = new ArrayList<Block>();
            alBlockEnd.add(bBlock);
        }

        htBlocks.put(blockId, bBlock);
    } // for

    Iterator<Integer> it = htPortMapIn.keySet().iterator();
    while (it.hasNext()) {
        Integer key = (Integer) it.next();
        Integer substId = (Integer) htPortMapIn.get(key);
        Block bBlock = (Block) htBlocks.get(substId); // blockIn

        Port[] inPorts = bBlock.getInPorts(ui);
        for (int ip = 0; inPorts != null && ip < inPorts.length; ip++) {
            if (inPorts[ip] == null)
                continue;
            Integer iConId = new Integer(inPorts[ip].getConnectedBlockId());
            Block btmp = (Block) htBlocks.get(iConId);

            Port[] outPorts = btmp.getOutPorts(ui);
            for (int op = 0; outPorts != null && op < outPorts.length; op++) {
                if (outPorts[op] == null)
                    continue;

                int iOutBlockId = outPorts[op].getConnectedBlockId();
                if (iOutBlockId == (key.intValue() + offset)) {
                    outPorts[op].setConnectedBlockId(substId.intValue());
                }
            }
        }
    }

    it = htPortMapOut.keySet().iterator();
    while (it.hasNext()) {
        Integer key = (Integer) it.next();
        Integer substId = (Integer) htPortMapOut.get(key);
        Block bBlock = (Block) htBlocks.get(substId); // blockOut

        Port[] outPorts = bBlock.getOutPorts(ui);
        for (int op = 0; outPorts != null && op < outPorts.length; op++) {
            if (outPorts[op] == null)
                continue;
            Integer iConId = new Integer(outPorts[op].getConnectedBlockId());
            Block btmp = (Block) htBlocks.get(iConId);

            Port[] inPorts = btmp.getInPorts(ui);
            for (int ip = 0; inPorts != null && ip < inPorts.length; ip++) {
                if (inPorts[ip] == null)
                    continue;

                int iInBlockId = inPorts[ip].getConnectedBlockId();
                if (iInBlockId == (key.intValue() + offset)) {
                    inPorts[ip].setConnectedBlockId(substId.intValue());
                }
            }
        }
    }

    // uncomment to check Port Mapping
    if (Const.CHECK_PORT_MAPPING) {

        // should return a warning if any bad block port exist

        Logger.debug("", this, "", "\n******* Checking Port Mapping *******\n");
        it = htBlocks.keySet().iterator();
        while (it.hasNext()) {
            Integer key = (Integer) it.next();
            Block bBlock = (Block) htBlocks.get(key);

            Logger.debug("", this, "", "\nBlockId: " + key + "  block: " + bBlock);
            if (bBlock == null)
                continue;

            Port[] ports = bBlock.getInPorts(ui);
            for (int i = 0; ports != null && i < ports.length; i++) {
                if (ports[i] == null)
                    Logger.debug("", this, "", "  null -> b");
                else
                    Logger.debug("", this, "", "  " + ports[i].getConnectedPortName() + ": "
                            + ports[i].getConnectedBlockId() + " -> b " + ports[i].getName());
            }
            ports = bBlock.getOutPorts(ui);
            for (int i = 0; ports != null && i < ports.length; i++) {
                if (ports[i] == null)
                    Logger.debug("", this, "", "  b -> null");
                else
                    Logger.debug("", this, "",
                            " " + ports[i].getName() + " b -> " + ports[i].getConnectedBlockId());
            }
        }
    }
    return new InstantiationResult(blockStart, alBlockEnd);
}

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 
 *///from ww w  .j  av a2s  . c  o m
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.joliciel.jochre.graphics.SegmenterImpl.java

/**
 * Split rows if they're particularly high, and contain considerable white space in the middle.
 * Shapes causing the join will be removed if too high, or attached to the closest row otherwise.
 * @param sourceImage/*from   ww w  .  j a  v a 2 s  . c  o  m*/
 * @param regressions
 * @return
 */
void splitRows(SourceImage sourceImage) {
    LOG.debug("########## splitRows #########");

    // Calculate the min row height to be considered for splitting
    double minHeightForSplit = sourceImage.getAverageShapeHeight();
    LOG.debug("minHeightForSplit: " + minHeightForSplit);

    double slopeMean = sourceImage.getMeanHorizontalSlope();

    List<RowOfShapes> candidateRows = new ArrayList<RowOfShapes>();
    for (RowOfShapes row : sourceImage.getRows()) {
        if (row.getRight() == row.getLeft())
            continue;
        int height = row.getBottom() - row.getTop();
        if (height >= minHeightForSplit) {
            LOG.debug("Adding candidate " + row.toString());
            candidateRows.add(row);
        }
    }

    // For each row to be considered for splitting, see if there are lines of white space inside it.
    Hashtable<RowOfShapes, List<RowOfShapes>> splitRows = new Hashtable<RowOfShapes, List<RowOfShapes>>();
    for (RowOfShapes row : candidateRows) {
        SimpleRegression regression = new SimpleRegression();
        // y = intercept + slope * x 
        LOG.debug("Left point: (" + row.getLeft() + " , " + row.getTop() + ")");
        regression.addData(row.getLeft(), row.getTop());
        double rightHandY = row.getTop() + ((double) (row.getRight() - row.getLeft()) * slopeMean);
        LOG.debug("Right point: (" + row.getRight() + " , " + rightHandY + ")");
        regression.addData(row.getRight(), rightHandY);

        int yDelta = (int) Math.ceil(Math.abs(rightHandY - (double) row.getTop()));
        int yInterval = yDelta + (row.getBottom() - row.getTop() + 1) + yDelta;

        LOG.debug("yDelta: " + yDelta);
        LOG.debug("yInterval: " + yInterval);
        // let's get pixel counts shape by shape, and leave out the rest (in case rows overlap vertically)
        int[] pixelCounts = new int[yInterval];
        for (Shape shape : row.getShapes()) {
            LOG.trace("Shape " + shape);
            int yDeltaAtLeft = (int) Math.round(regression.predict(shape.getLeft()));
            LOG.trace("yDeltaAtLeft: " + yDeltaAtLeft);
            // the shape offset + the offset between the regression line and the row top
            // + the delta we left at the start in case the line slopes upwards to the right
            int topIndex = (shape.getTop() - row.getTop()) + (row.getTop() - yDeltaAtLeft) + yDelta;
            LOG.trace("topIndex: (" + shape.getTop() + " - " + row.getTop() + ") + (" + row.getTop() + " - "
                    + yDeltaAtLeft + ") + " + yDelta + " = " + topIndex);
            for (int x = 0; x < shape.getWidth(); x++) {
                for (int y = 0; y < shape.getHeight(); y++) {
                    if (shape.isPixelBlack(x, y, sourceImage.getBlackThreshold())) {
                        pixelCounts[topIndex + y]++;
                    }
                }
            }
        }

        Mean pixelCountMean = new Mean();
        StandardDeviation pixelCountStdDev = new StandardDeviation();
        for (int i = 0; i < yInterval; i++) {
            LOG.debug("Pixel count " + i + ": " + pixelCounts[i]);
            pixelCountMean.increment(pixelCounts[i]);
            pixelCountStdDev.increment(pixelCounts[i]);
        }
        LOG.debug("pixel count mean: " + pixelCountMean.getResult() + ", std dev: "
                + pixelCountStdDev.getResult());

        // If there's a split required, we're going to go considerably above and below the mean several times
        double lowThreshold = pixelCountMean.getResult() / 2.0;
        double highThreshold = pixelCountMean.getResult() * 2.0;
        boolean inRow = false;
        List<Integer> switches = new ArrayList<Integer>();
        for (int i = 0; i < yInterval; i++) {
            if (!inRow && pixelCounts[i] > highThreshold) {
                LOG.debug("In row at " + i + ", pixel count " + pixelCounts[i]);
                inRow = true;
                switches.add(i);
            } else if (inRow && pixelCounts[i] < lowThreshold) {
                LOG.debug("Out of row at " + i + ", pixel count " + pixelCounts[i]);
                inRow = false;
                switches.add(i);
            }
        }
        if (switches.size() > 2) {
            // we have more than one row
            List<Integer> rowSeparations = new ArrayList<Integer>();

            // find the row separators
            for (int switchIndex = 1; switchIndex < switches.size() - 2; switchIndex = switchIndex + 2) {
                int outOfRow = switches.get(switchIndex);
                int intoRow = switches.get(switchIndex + 1);
                int minPixelCount = (int) Math.ceil(highThreshold);
                int minIndex = -1;
                // find the row with the lowest pixel count
                for (int i = outOfRow; i <= intoRow; i++) {
                    if (pixelCounts[i] < minPixelCount) {
                        minPixelCount = pixelCounts[i];
                        minIndex = i;
                    }
                }
                rowSeparations.add(minIndex);
            }

            // separate the shapes among the rows
            List<RowOfShapes> newRows = new ArrayList<RowOfShapes>(rowSeparations.size() + 1);
            for (int i = 0; i <= rowSeparations.size(); i++) {
                newRows.add(graphicsService.getEmptyRow(sourceImage));
            }

            // add a separator at the beginning and end
            rowSeparations.add(0, 0);
            rowSeparations.add(yInterval + 1);
            for (Shape shape : row.getShapes()) {
                int yDeltaAtLeft = (int) Math.round(regression.predict(shape.getLeft()));
                int topIndex = (shape.getTop() - row.getTop()) + (row.getTop() - yDeltaAtLeft) + yDelta;
                int firstSepAfterShapeBottom = rowSeparations.size();
                int lastSepBeforeShapeTop = -1;

                for (int i = rowSeparations.size() - 1; i >= 0; i--) {
                    int rowSeparation = rowSeparations.get(i);
                    if (rowSeparation <= topIndex) {
                        lastSepBeforeShapeTop = i;
                        break;
                    }
                }

                for (int i = 0; i < rowSeparations.size(); i++) {
                    int rowSeparation = rowSeparations.get(i);
                    if (rowSeparation >= topIndex + shape.getHeight()) {
                        firstSepAfterShapeBottom = i;
                        break;
                    }
                }

                if (lastSepBeforeShapeTop == firstSepAfterShapeBottom - 1) {
                    // shape clearly belongs to one row
                    RowOfShapes newRow = newRows.get(lastSepBeforeShapeTop);
                    newRow.addShape(shape);
                } else {
                    // is the shape much closer to one row than another?
                    // if yes, add it to then add it to this row
                    int[] yPixelsPerRow = new int[newRows.size()];
                    for (int i = 0; i < newRows.size(); i++) {
                        int separatorTop = rowSeparations.get(i);
                        int separatorBottom = rowSeparations.get(i + 1);
                        int top = topIndex < separatorTop ? separatorTop : topIndex;
                        int bottom = topIndex + shape.getHeight() < separatorBottom
                                ? topIndex + shape.getHeight()
                                : separatorBottom;
                        yPixelsPerRow[i] = bottom - top;
                    }

                    int pixelsInMaxRow = 0;
                    int maxPixelRowIndex = -1;
                    for (int i = 0; i < newRows.size(); i++) {
                        if (yPixelsPerRow[i] > pixelsInMaxRow) {
                            pixelsInMaxRow = yPixelsPerRow[i];
                            maxPixelRowIndex = i;
                        }
                    }
                    double minPercentage = 0.8;
                    if (((double) pixelsInMaxRow / (double) shape.getHeight()) >= minPercentage) {
                        RowOfShapes newRow = newRows.get(maxPixelRowIndex);
                        newRow.addShape(shape);
                    } else {
                        // otherwise, the shape needs to be got rid of
                        // as it's causing massive confusion
                        // do this by simply not adding it anywhere
                    }
                } // is the shape in one row exactly?
            } // next shape
            splitRows.put(row, newRows);
        } // do we have more than one row?
    } // next row

    for (RowOfShapes row : splitRows.keySet()) {
        List<RowOfShapes> newRows = splitRows.get(row);
        sourceImage.replaceRow(row, newRows);
    }
}