Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:maui.main.MauiTopicExtractor.java

/**
 * Prints out a plain-text representation of a graph representing the main topics of the document.
 * The nodes are the topics and the edges are relations between them as computed using the Wikipedia Miner.
 * Only possible if Wikipedia data is provided.
 * /*w  w  w  .  j  a v a  2s . c  o  m*/
 * @param topics
 * @param root
 * @param outputFile
 */
public void computeGraph(HashMap<Article, Integer> topics, String root, String outputFile) {
    FileOutputStream out;
    PrintWriter printer;
    try {

        if (debugMode) {
            System.err.println("Printing graph information into " + outputFile);
        }

        out = new FileOutputStream(outputFile);
        printer = new PrintWriter(out);

        printer.print("graph G {\n");

        printer.print("graph [root=\"" + root + "\", outputorder=\"depthfirst\"];\n");

        HashSet<String> done = new HashSet<String>();
        double relatedness = 0;
        for (Article a : topics.keySet()) {
            int count = topics.get(a).intValue();
            if (count < 1) {
                printer.print("\"" + a.getTitle() + "\" [fontsize=22];\n");
            } else if (count < 3) {
                printer.print("\"" + a.getTitle() + "\" [fontsize = 18];\n");
            } else if (count < 6) {
                printer.print("\"" + a.getTitle() + "\" [fontsize = 14];\n");
            } else {
                printer.print("\"" + a.getTitle() + "\" [fontsize = 12];\n");
            }

            for (Article c : topics.keySet()) {
                if (!c.equals(a)) {
                    try {
                        relatedness = a.getRelatednessTo(c);
                        String relation = "\"" + a.getTitle() + "\" -- \"" + c.getTitle();
                        String relation2 = "\"" + c.getTitle() + "\" -- \"" + a.getTitle();

                        if (!done.contains(relation2) && !done.contains(relation)) {
                            done.add(relation2);
                            done.add(relation);

                            if (relatedness < 0.2) {
                                printer.print(relation + "\"[style=invis];\n");
                            } else {
                                printer.print(relation + "\" [penwidth = \"" + (int) (relatedness * 10 - 0.2)
                                        + "\"];\n");
                            }
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        printer.print("}\n");
        printer.close();
        out.close();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:com.almarsoft.GroundhogReader.MessageListActivity.java

private void fillListNonRecursive(Article root, int depth, String replyto) {

    Stack<MiniHeader> stack = new Stack<MiniHeader>();

    boolean markReplies = mPrefs.getBoolean("markReplies", true);
    boolean finished = false;

    String clean_subject;/*from   w w  w.  j  av a2 s.  com*/
    MiniHeader tmpMiniItem;
    HeaderItemClass ih = null;
    String[] refsArray;
    String msgId;

    ArrayList<HeaderItemClass> nonStarredItems = new ArrayList<HeaderItemClass>();
    HashSet<String> bannedTrollsSet = DBUtils.getBannedTrolls(getApplicationContext());
    HashSet<String> starredSet = DBUtils.getStarredSubjectsSet(getApplicationContext());

    // Proxy for speed
    HashSet<String> myPostsSetProxy = mMyPostsSet;
    ArrayList<HeaderItemClass> headerItemsListProxy = new ArrayList<HeaderItemClass>();
    int refsArrayLen;

    while (!finished) {

        if (root == null)
            finished = true;

        root.setReplyTo(replyto);

        if (!root.isDummy()) {
            ih = new HeaderItemClass(root, depth);

            // Don't feed the troll
            if (!bannedTrollsSet.contains(root.getFrom())) {

                // Put the replies in red (if configured)
                if (markReplies) {
                    refsArray = root.getReferences();
                    refsArrayLen = refsArray.length;
                    msgId = null;

                    if (refsArray != null && refsArrayLen > 0) {
                        msgId = refsArray[refsArrayLen - 1];
                    }

                    if (msgId != null && myPostsSetProxy != null && myPostsSetProxy.contains(msgId))
                        ih.myreply = true;
                    else
                        ih.myreply = false;
                }

                clean_subject = root.simplifiedSubject();
                if (starredSet.contains(clean_subject)) {
                    ih.starred = true;
                    headerItemsListProxy.add(ih); // Starred items first
                } else {
                    // Nonstarred items will be added to mHeaderItemsList at the end
                    nonStarredItems.add(ih);
                }
            }
        }

        if (root.next != null) {
            tmpMiniItem = new MiniHeader(root.next, depth, replyto);
            stack.push(tmpMiniItem);
        }

        if (root.kid != null) {

            replyto = root.getFrom();
            if (!root.isDummy())
                ++depth;
            root = root.kid;

        } else if (!stack.empty()) {

            tmpMiniItem = stack.pop();
            root = tmpMiniItem.article;
            depth = tmpMiniItem.depth;
            replyto = tmpMiniItem.replyto;

        } else
            finished = true;

    }

    // Now add the non starred items after the starred ones
    int nonStarredItemsLen = nonStarredItems.size();
    for (int i = 0; i < nonStarredItemsLen; i++) {
        headerItemsListProxy.add(nonStarredItems.get(i));
    }

    mHeaderItemsList = headerItemsListProxy;
    nonStarredItems = null;
}

From source file:cz.cas.lib.proarc.webapp.server.rest.DigitalObjectResource.java

/**
 * Moves members from a source object to a destination object.
 * @param srcParentPid PID of source/*from  www . j  a  v  a  2  s . c  om*/
 * @param dstParentPid PID of destination
 * @param batchId optional batch import ID
 * @param movePids member PIDs to move
 * @return the list of updated members
 */
@PUT
@Path(DigitalObjectResourceApi.MEMBERS_PATH + '/' + DigitalObjectResourceApi.MEMBERS_MOVE_PATH)
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_JSON })
public SmartGwtResponse<Item> moveMembers(
        @FormParam(DigitalObjectResourceApi.MEMBERS_MOVE_SRCPID) String srcParentPid,
        @FormParam(DigitalObjectResourceApi.MEMBERS_MOVE_DSTPID) String dstParentPid,
        @FormParam(DigitalObjectResourceApi.MEMBERS_ITEM_BATCHID) Integer batchId,
        @FormParam(DigitalObjectResourceApi.MEMBERS_ITEM_PID) List<String> movePids)
        throws IOException, DigitalObjectException, FedoraClientException {

    if (srcParentPid == null) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing source PID!");
    }
    if (dstParentPid == null) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing target PID!");
    }
    if (srcParentPid.equals(dstParentPid)) {
        throw RestException.plainText(Status.BAD_REQUEST, "src == dst!");
    }
    if (movePids == null || movePids.isEmpty()) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing children PIDs!");
    }

    HashSet<String> movePidSet = new HashSet<String>(movePids);
    if (movePidSet.isEmpty()) {
        return new SmartGwtResponse<Item>(Collections.<Item>emptyList());
    } else if (movePidSet.size() != movePids.size()) {
        throw RestException.plainText(Status.BAD_REQUEST, "Duplicate children in the request!");
    }
    if (movePidSet.contains(dstParentPid)) {
        throw RestException.plainText(Status.BAD_REQUEST, "The target parent listed as child!");
    }

    Batch batch = batchId == null ? null : importManager.get(batchId);
    DigitalObjectHandler srcHandler = findHandler(srcParentPid, batch, false);
    deleteMembers(srcHandler, movePidSet);

    // XXX loadLocalSearchItems
    Map<String, Item> memberSearchMap = loadSearchItems(movePidSet);
    DigitalObjectHandler dstHandler = findHandler(dstParentPid, batch, false);
    List<Item> added = addMembers(dstHandler, movePids, memberSearchMap);

    srcHandler.commit();
    dstHandler.commit();
    SmartGwtResponse<Item> result = new SmartGwtResponse<Item>(added);
    return result;
}

From source file:edu.ku.brc.specify.config.init.secwiz.UserPanel.java

/**
 * @param isInitial/*from   w  w  w .  j a va  2s .  c o  m*/
 */
private void loadData(final boolean isInitial) {
    label.setText("");

    String hostName = properties.getProperty("hostName");
    String dbUserName = properties.getProperty("dbUserName");
    String dbPassword = properties.getProperty("dbPassword");

    int index = 0;
    List<String> dbNamesList = masterPanel.getDbNamesForMaster();
    List<String> otherNamesList = masterPanel.getDbNameList();

    if (dbNamesList == null || dbNamesList.size() == 0) {
        return;
    }

    //dbNamesList.clear();
    //otherNamesList.clear();
    //dbNamesList.add("testfish");

    Vector<String> items = new Vector<String>(dbNamesList);
    Collections.sort(items);

    if (!isInitial) {
        index = dbList.getSelectedIndex();
        if (index == -1) {
            return;
        }
    }

    databaseName = isInitial ? items.get(0) : (String) dbList.getSelectedValue();

    DBMSUserMgr mgr = DBMSUserMgr.getInstance();
    do {
        if (mgr.connect(dbUserName, dbPassword, hostName, databaseName)) {
            if (isInitial) {
                HashSet<String> dbNameHashSet = new HashSet<String>();
                DefaultListModel model = new DefaultListModel();
                for (String nm : items) {
                    model.addElement(nm);
                    dbNameHashSet.add(nm);
                }
                dbList.setModel(model);

                model = new DefaultListModel();
                for (String nm : otherNamesList) {
                    if (!dbNameHashSet.contains(nm)) {
                        model.addElement(nm);
                    }
                }
                otherDBList.setModel(model);
            }

            label.setText(getFormattedResStr("MSTR_USR_DB", databaseName));

            if (!mgr.doesDBHaveTable(databaseName, "specifyuser")) {
                items.remove(0);
                databaseName = isInitial ? items.get(0) : (String) dbList.getSelectedValue();
                continue;
            }

            Vector<UserData> userDataList = new Vector<UserData>();
            String sql = "SELECT SpecifyUserId, Name, Password, EMail FROM specifyuser";
            Vector<Object[]> data = BasicSQLUtils.query(mgr.getConnection(), sql);

            for (Object[] c : data) {
                UserData ud = new UserData((Integer) c[0], (String) c[1], (String) c[2], "(On user's machine)",
                        (String) c[3]);
                userDataList.add(ud);

                sql = String.format(
                        "SELECT LastName, FirstName, EMail FROM agent WHERE SpecifyUserID = %d ORDER BY TimestampModified, TimestampCreated LIMIT 0,1",
                        ud.getId());
                Vector<Object[]> uData = BasicSQLUtils.query(mgr.getConnection(), sql);
                if (uData.size() > 0) {
                    Object[] d = uData.get(0);
                    ud.setLastName((String) d[0]);
                    ud.setFirstName((String) d[1]);

                    String email = (String) d[2];
                    if (StringUtils.isNotEmpty(email) && StringUtils.isEmpty(ud.getEmail())) {
                        ud.setEmail(email);
                    }
                } else {
                    // error
                }
            }
            mgr.close();
            userModel.setUserData(userDataList);
            UIHelper.calcColumnWidths(userTable);

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Window window = getTopWindow();
                    Insets screenInsets = Toolkit.getDefaultToolkit()
                            .getScreenInsets(window.getGraphicsConfiguration());
                    Rectangle screenRect = window.getGraphicsConfiguration().getBounds();

                    screenRect.height -= screenInsets.top + screenInsets.bottom;
                    screenRect.width -= screenInsets.left + screenInsets.right;

                    Rectangle rect = window.getBounds();
                    Dimension size = window.getPreferredSize();

                    // Make sure the window isn't larger than the screen
                    size.width = Math.min(size.width, screenRect.width);
                    size.height = Math.min(size.height, screenRect.height);

                    if (size.height > rect.height || size.width > rect.width) {
                        window.setBounds(rect.x, rect.y, size.width, size.height);
                        UIHelper.centerWindow(getTopWindow());

                    }
                }
            });

            if (isInitial && items.size() > 0) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        dbList.setSelectedIndex(0);
                    }
                });
            }

            break;
        } else if (items.size() > 1) {
            items.remove(0);
            databaseName = isInitial ? items.get(0) : (String) dbList.getSelectedValue();
        } else {
            break;
        }

    } while (true);

}

From source file:hms.hwestra.interactionrebuttal.InteractionRebuttal.java

public void prepareDataForCelltypeSpecificEQTLMapping(DoubleMatrixDataset<String, String> rawExpressionDataset,
        String inexpraw, String outdirectory, Double correlationThreshold, String celltypeSpecificProbeFile,
        String mdsComponentFile, String cellCountFile, String gte, Integer threads) throws IOException {
    String rawExpressionDataFile = inexpraw;
    // 7. select Cell type specific probes
    System.out.println("Loading list of cell type specific probes from: " + celltypeSpecificProbeFile);
    HashSet<String> cellTypeSpecificProbeSet = new HashSet<String>();
    TextFile cellSpecificProbeTF = new TextFile(celltypeSpecificProbeFile, TextFile.R);
    cellTypeSpecificProbeSet.addAll(cellSpecificProbeTF.readAsArrayList());
    cellSpecificProbeTF.close();// ww  w .ja va  2  s  .c om

    if (cellTypeSpecificProbeSet.isEmpty()) {
        System.err.println("Error: " + celltypeSpecificProbeFile + " is empty!");
        System.exit(-1);
    } else {
        System.out.println(cellTypeSpecificProbeSet.size() + " cell type specific probes loaded.");
    }

    // 1. load gene expression data
    System.out.println("Loading gene expression data.");

    double[][] rawExpressionData = rawExpressionDataset.getRawData();

    // determine the number of cell type specific probes in this dataset
    int probeCounter = 0;
    List<String> probes = rawExpressionDataset.rowObjects;
    for (int i = 0; i < probes.size(); i++) {
        if (cellTypeSpecificProbeSet.contains(probes.get(i))) {
            probeCounter++;
        }
    }

    if (probeCounter == 0) {
        System.err
                .println("Error: none of the cell type specific probes defined in " + celltypeSpecificProbeFile
                        + " are present in expression dataset: " + rawExpressionDataset.fileName);
        System.exit(-1);
    } else {
        System.out.println(probeCounter + " of the cell type specific probes are in your dataset.");
    }

    System.out.println("Now reloading the gene expression data for the samples that passed the QC.");
    // 6. Remove samples with r < 0.9 for PC1
    // reload expression file, include only samples that pass QC...
    //        rawExpressionDataset = new DoubleMatrixDataset<String, String>(rawExpressionDataFile);
    //        rawExpressionData = rawExpressionDataset.getRawData();

    //        // quantile normalize, log2 transform again, because the number of samples might have been changed..
    //        QuantileNormalization.quantilenormalize(rawExpressionData);
    //        Log2Transform.log2transform(rawExpressionData);
    rawExpressionData = rawExpressionDataset.rawData;

    // collect data for cell type specific probes
    double[][] probeData = new double[probeCounter][rawExpressionDataset.colObjects.size()];
    probeCounter = 0;
    ArrayList<String> cellTypeSpecificProbeDatasetRowNames = new ArrayList<String>();
    for (int i = 0; i < probes.size(); i++) {
        if (cellTypeSpecificProbeSet.contains(probes.get(i))) {
            probeData[probeCounter] = rawExpressionData[i];
            cellTypeSpecificProbeDatasetRowNames.add(probes.get(i));
            probeCounter++;
        }
    }

    // initiate cell type specific probe correlation matrix
    double[][] celltypeSpecificCorrelationMatrix = new double[probeCounter][probeCounter];
    for (int i = 0; i < probeCounter; i++) {
        for (int j = i + 1; j < probeCounter; j++) {
            double r = Correlation.correlate(probeData[i], probeData[j]);
            celltypeSpecificCorrelationMatrix[i][j] = r;
            celltypeSpecificCorrelationMatrix[j][i] = r;
        }
        celltypeSpecificCorrelationMatrix[i][i] = 1;
    }

    // save the correlation matrix
    DoubleMatrixDataset<String, String> probeCorrelationMatrixOut = new DoubleMatrixDataset<String, String>();
    probeCorrelationMatrixOut.colObjects = cellTypeSpecificProbeDatasetRowNames;
    probeCorrelationMatrixOut.rowObjects = cellTypeSpecificProbeDatasetRowNames;
    probeCorrelationMatrixOut.rawData = celltypeSpecificCorrelationMatrix;
    probeCorrelationMatrixOut.recalculateHashMaps();
    //        probeCorrelationMatrixOut.save(outdirectory + "CelltypeSpecificProbeCorrelationMatrix.txt.gz");

    // 9. PCA over cell specific probe correlation matrix
    DoubleMatrixDataset<String, String> cellTypeSpecificDataset = new DoubleMatrixDataset<String, String>(
            probeData);
    cellTypeSpecificDataset.colObjects = rawExpressionDataset.colObjects;
    cellTypeSpecificDataset.rowObjects = cellTypeSpecificProbeDatasetRowNames;
    //        cellTypeSpecificDataset.save(expressionOutputDirectory + "CellTypeSpecificProbeExpression.txt.gz");
    cellTypeSpecificDataset.transposeDataset();
    Normalizer n = new Normalizer();
    // calculate first Principal Component over the cell type specific probe matrix...
    Pair<DoubleMatrixDataset<String, String>, DoubleMatrixDataset<String, String>> PCAResults = n.calculatePCA(
            cellTypeSpecificDataset, celltypeSpecificCorrelationMatrix,
            outdirectory + "CellTypeSpecificProbePCA", 1);

    // 10. PC1 scores: cell specific proxy -- write to file for future use...
    DoubleMatrixDataset<String, String> cellSpecificPCScores = PCAResults.getLeft();

    //Ensure that the cellTypeSpecificPCScores correlate positively with the set of probes that we have used to determine this component:
    double[] pcScoresSamples = new double[cellSpecificPCScores.nrRows];
    for (int i = 0; i < cellSpecificPCScores.nrRows; i++) {
        pcScoresSamples[i] = cellSpecificPCScores.rawData[i][0];
    }
    cellTypeSpecificDataset.transposeDataset();
    int nrProbesCorrelatingPositively = 0;
    for (int i = 0; i < cellTypeSpecificDataset.rawData.length; i++) {
        double corr = JSci.maths.ArrayMath.correlation(pcScoresSamples, cellTypeSpecificDataset.rawData[i]);
        if (corr >= 0) {
            nrProbesCorrelatingPositively++;
        } else {
            nrProbesCorrelatingPositively--;
        }
    }
    if (nrProbesCorrelatingPositively < 0) {
        for (int i = 0; i < cellSpecificPCScores.nrRows; i++) {
            cellSpecificPCScores.rawData[i][0] = -cellSpecificPCScores.rawData[i][0];
        }
    }

    TextFile tfOutCellSpecific = new TextFile(outdirectory + "CellTypeProxyFile.txt", TextFile.W);
    tfOutCellSpecific.writeln("Sample\tCellCountProxyValue");
    for (int i = 0; i < cellSpecificPCScores.nrRows; i++) {
        tfOutCellSpecific
                .writeln(cellSpecificPCScores.rowObjects.get(i) + "\t" + cellSpecificPCScores.rawData[i][0]);
    }
    tfOutCellSpecific.close();

    File f = new File(outdirectory + "CellTypeSpecificProbePCA.PCAOverSamplesEigenvalues.txt.gz");
    f.delete();
    f = new File(outdirectory + "CellTypeSpecificProbePCA.PCAOverSamplesEigenvectors.txt.gz");
    f.delete();
    f = new File(outdirectory + "CellTypeSpecificProbePCA.PCAOverSamplesEigenvectorsTransposed.txt.gz");
    f.delete();
    f = new File(outdirectory + "CellTypeSpecificProbePCA.PCAOverSamplesPrincipalComponents.txt.gz");
    f.delete();

}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.AddAssociatedConceptsPreprocessor.java

private void addConceptSemanticTypeLabelAndURIInputs(int numberConcepts) {
    String[] labels = convertDelimitedStringToArray(conceptSemanticTypeLabelValues);
    HashSet<String> uniqueLabelValues = new HashSet<String>();
    if (labels != null && labels.length == numberConcepts) {
        int i;//  w w w . j av a 2  s.  c om
        for (i = 0; i < numberConcepts; i++) {
            String thisLabel = labels[i];
            int suffix = i + 1;
            String labelInputName = conceptSemanticTypeLabelBase + suffix;
            String[] labelValues = new String[1];
            labelValues[0] = thisLabel;
            //TODO: Check if there are no funky typed information also stored
            //At this point the field should already have been added to edit configuration
            FieldVTwo labelField = editConfiguration.getField(labelInputName);
            //TODO: Also check to see whether the label is actually populate or will n3 editing take care of that?
            if (labelField != null) {
                submission.addLiteralToForm(editConfiguration, labelField, labelInputName, labelValues);
                //Associate URI
                if (!uniqueLabelValues.contains(thisLabel)) {
                    uniqueLabelValues.add(thisLabel);
                    this.addConceptSemanticTypeURIInputForLabel(labelInputName, suffix);
                }
            } else {
                log.error("Corresponding field for " + labelInputName + " was not added to edit configuration");
            }

        }
    } else if (labels != null && labels.length != numberConcepts) {
        log.error("Number of concept semantic type labels did not match the number of concepts to be added");
    } else {
        log.error("Concept labels returned were null");
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.AddAssociatedConceptsPreprocessor.java

private void addConceptSemanticTypeURIResources(int numberConcepts) {
    //Iterate through the labels and get the corresponding uris
    HashSet<String> urisToAdd = new HashSet<String>();
    String[] conceptSemanticTypeLabels = convertDelimitedStringToArray(conceptSemanticTypeLabelValues);
    //the number of existing values may not match up, or at least existing populated ones
    //Now we can't determine whether all concepts will have semantic types - at some point what if
    //we ran a search across all external vocabularies? So we can't compare labels to number of concepts
    //but we can ensure that it isn't greater than then number of concepts
    if (conceptSemanticTypeLabels != null && conceptSemanticTypeLabels.length <= numberConcepts) {
        int i;/*w w  w. java  2 s  . c om*/
        for (i = 0; i < numberConcepts; i++) {
            int suffix = i + 1;
            String conceptSemanticTypeLabelVar = conceptSemanticTypeLabelBase + suffix;
            if (this.labelVarToUriVarHash.containsKey(conceptSemanticTypeLabelVar)) {
                String newResourceName = this.labelVarToUriVarHash.get(conceptSemanticTypeLabelVar);
                if (!urisToAdd.contains(newResourceName)) {
                    urisToAdd.add(newResourceName);
                    editConfiguration.addNewResource(newResourceName, null);
                }
            }

        }
    } else if (conceptSemanticTypeLabels != null && conceptSemanticTypeLabels.length > numberConcepts) {
        log.error("Number of concept semantic type labels is greater than number of concepts");
    } else {
        log.error("Concept semantic type labels returned are null");
    }

}

From source file:gov.nih.nci.rembrandt.web.xml.ClassComparisonReport.java

public static Document getReportXML(Finding finding, Map filterMapParams, boolean allAnnotations,
        ArrayList reporterIdFilter) {

    DecimalFormat resultFormat = new DecimalFormat("0.0000");
    DecimalFormat sciFormat = new DecimalFormat("0.00E0");
    DecimalFormat tmpsciFormat = new DecimalFormat("###0.0000#####################");

    /*/*ww w  . jav a  2 s  .c  o m*/
     *  this is for filtering, we will want a p-value filter for CC
     */
    ArrayList filter_string = new ArrayList(); // hashmap of genes | reporters | cytobands
    String filter_type = "show"; // show | hide
    String filter_element = "none"; // none | gene | reporter | cytoband

    if (filterMapParams.containsKey("filter_string") && filterMapParams.get("filter_string") != null)
        filter_string = (ArrayList) filterMapParams.get("filter_string");
    if (filterMapParams.containsKey("filter_type") && filterMapParams.get("filter_type") != null)
        filter_type = (String) filterMapParams.get("filter_type");
    if (filterMapParams.containsKey("filter_element") && filterMapParams.get("filter_element") != null)
        filter_element = (String) filterMapParams.get("filter_element");

    String defaultV = "--";
    String delim = " | ";

    Document document = DocumentHelper.createDocument();

    Element report = document.addElement("Report");
    Element cell = null;
    Element data = null;
    Element dataRow = null;
    //add the atts
    report.addAttribute("reportType", "Class Comparison");
    report.addAttribute("helpLink", ContextSensitiveHelpTag.getHelpLink("Class Comparison"));
    //fudge these for now
    report.addAttribute("groupBy", "none");
    String queryName = "none";
    queryName = finding.getTaskId();

    //set the queryName to be unique for session/cache access
    report.addAttribute("queryName", queryName);
    report.addAttribute("sessionId", "the session id");
    report.addAttribute("creationTime", "right now");

    StringBuffer sb = new StringBuffer();

    int recordCount = 0;
    int totalSamples = 0;

    //TODO: instance of
    ClassComparisonFinding ccf = (ClassComparisonFinding) finding;

    //process the query details
    ArrayList<String> queryDetails = new ArrayList();
    ClassComparisonQueryDTO ccdto = (ClassComparisonQueryDTO) ccf.getQueryDTO();

    if (ccdto != null) {
        String tmp = "";
        tmp = ccdto.getQueryName() != null ? ccdto.getQueryName() : "";
        queryDetails.add("Query Name: " + tmp);
        tmp = ccdto.getArrayPlatformDE() != null ? ccdto.getArrayPlatformDE().getValue().toString() : "";
        queryDetails.add("Array Platform: " + tmp);

        tmp = "";
        List<ClinicalQueryDTO> grps = ccdto.getComparisonGroups() != null ? ccdto.getComparisonGroups()
                : new ArrayList();
        Collection grs = new ArrayList();
        for (ClinicalQueryDTO cdto : grps) {
            if (cdto.getQueryName() != null)
                grs.add(cdto.getQueryName());
        }

        tmp += StringUtils.join(grs.toArray(), ", ") + " (baseline)";
        queryDetails.add("Groups: " + tmp);
        /*
        noHTMLString = noHTMLString.replaceAll("<", "{");
        noHTMLString = noHTMLString.replaceAll(">", "}");
        noHTMLString = noHTMLString.replaceAll("&nbsp;", " ");
        */
        tmp = ccdto.getExprFoldChangeDE() != null ? ccdto.getExprFoldChangeDE().getValue().toString() : "";
        queryDetails.add("Fold Change: " + tmp);
        //queryDetails.add("Institutions: " + ccdto.getInstitutionDEs());
        tmp = ccdto.getMultiGroupComparisonAdjustmentTypeDE() != null
                ? ccdto.getMultiGroupComparisonAdjustmentTypeDE().getValue().toString()
                : "";
        queryDetails.add("Multi Group: " + tmp);
        tmp = ccdto.getStatisticalSignificanceDE() != null
                ? ccdto.getStatisticalSignificanceDE().getValue().toString()
                : "";
        queryDetails.add("Stat Sig.: " + tmp);
        tmp = ccdto.getStatisticTypeDE() != null ? ccdto.getStatisticTypeDE().getValue().toString() : "";
        queryDetails.add("Stat Type: " + tmp);
    }
    /*
    queryDetails.add("Analysis Result name: " + ccform.getAnalysisResultName());
    queryDetails.add("Array Platform: " + ccform.getArrayPlatform());
    queryDetails.add("Baseline group: " + ccform.getBaselineGroup());
    queryDetails.add("Comparison Groups: " + ccform.getSelectedGroups()[0].toString());
    queryDetails.add("Comparison Adjustment: " + ccform.getComparisonAdjustment());
    //queryDetails.add("Comp. Adj. Coll: " + ccform.getComparisonAdjustmentCollection());
    //queryDetails.add("Existing Groups: " + ccform.getExistingGroups());
    //queryDetails.add("Existing group list: " + ccform.getExistingGroupsList());
    //queryDetails.add("Fold Change: " + ccform.getFoldChange());
    queryDetails.add("Fold Change auto: " + ccform.getFoldChangeAuto());
    //queryDetails.add("Fold change auto list: " + ccform.getFoldChangeAutoList());
    //queryDetails.add("Fold change manual: " + ccform.getFoldChangeManual());
    queryDetails.add("Stastic: " + ccform.getStatistic());
    queryDetails.add("Stastical method: " + ccform.getStatisticalMethod());
    //queryDetails.add("Stastical method coll.: " + ccform.getStatisticalMethodCollection());
    queryDetails.add("Stastical significance: " + ccform.getStatisticalSignificance());
    */
    String qd = "";
    for (String q : queryDetails) {
        qd += q + " ||| ";
    }

    if (ccf != null) {

        Element details = report.addElement("Query_details");
        cell = details.addElement("Data");
        cell.addText(qd);
        cell = null;

        Element headerRow = report.addElement("Row").addAttribute("name", "headerRow");
        cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header")
                .addAttribute("group", "header");
        data = cell.addElement("Data").addAttribute("type", "header").addText("Reporter");
        data = null;
        cell = null;

        //pvalue is fixed in the second column, essential for XSL
        cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header")
                .addAttribute("group", "header");
        String isAdj = ccf.arePvaluesAdjusted() ? " (Adjusted) " : "";
        data = cell.addElement("Data").addAttribute("type", "header")
                .addText(RembrandtConstants.PVALUE + isAdj);
        data = null;
        cell = null;

        cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header")
                .addAttribute("group", "header");
        data = cell.addElement("Data").addAttribute("type", "header").addText("Group Avg");
        data = null;
        cell = null;

        cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header")
                .addAttribute("group", "header");
        data = cell.addElement("Data").addAttribute("type", "header").addText("Fold Change");
        data = null;
        cell = null;

        cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header")
                .addAttribute("group", "header");
        data = cell.addElement("Data").addAttribute("type", "header").addText("Gene Symbol");
        data = null;
        cell = null;

        //starting annotations...get them only if allAnnotations == true
        if (allAnnotations) {
            cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv")
                    .addAttribute("group", "header");
            data = cell.addElement("Data").addAttribute("type", "header").addText("GenBank Acc");
            data = null;
            cell = null;
            cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv")
                    .addAttribute("group", "header");
            data = cell.addElement("Data").addAttribute("type", "header").addText("Locus link");
            data = null;
            cell = null;
            cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv")
                    .addAttribute("group", "header");
            data = cell.addElement("Data").addAttribute("type", "header").addText("GO Id");
            data = null;
            cell = null;
            cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv")
                    .addAttribute("group", "header");
            data = cell.addElement("Data").addAttribute("type", "header").addText("Pathways");
            data = null;
            cell = null;
        }

        /* done with the headerRow and SampleRow Elements, time to add data rows */

        /*
        Map<String,ReporterResultset> reporterResultsetMap = null;
        reporterResultsetMap = ccf.getReporterAnnotationsMap();
        */

        List<ClassComparisonResultEntry> classComparisonResultEntrys = ccf.getResultEntries();
        List<String> reporterIds = new ArrayList<String>();
        HashSet<String> reporterIdSet = null;

        if (reporterIdFilter != null) {
            reporterIdSet = new HashSet<String>(reporterIdFilter);
        }

        int index = 0;
        if (reporterIdFilter == null) {
            for (ClassComparisonResultEntry classComparisonResultEntry : classComparisonResultEntrys) {
                if (classComparisonResultEntry.getReporterId() != null) {
                    reporterIds.add(classComparisonResultEntry.getReporterId());
                }
            }
        } else {
            reporterIds = reporterIdFilter;
        }

        Map reporterResultsetMap = null;
        ArrayPlatformType arrayPlatform = ccdto.getArrayPlatformDE() != null
                ? ccdto.getArrayPlatformDE().getValueObjectAsArrayPlatformType()
                : ArrayPlatformType.AFFY_OLIGO_PLATFORM;
        if (allAnnotations) {
            //Map<String, ReporterAnnotations> reporterResultsetMap = null;
            try {
                reporterResultsetMap = AnnotationHandler.getAllAnnotationsFor(reporterIds, arrayPlatform);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                reporterResultsetMap = AnnotationHandler.getGeneSymbolsFor(reporterIds, arrayPlatform);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /*
        //this looks like a failsafe for the old method
        if(reporterResultsetMap == null)   {
         try {
            reporterResultsetMap = GeneExprAnnotationService.getAnnotationsMapForReporters(reporterIds);
         }
         catch(Exception e){}
          }
          */

        boolean found = false;
        for (ClassComparisonResultEntry ccre : ccf.getResultEntries()) {

            if (reporterIdFilter != null) {
                found = reporterIdSet.contains(ccre.getReporterId());

                //not found, then skip
                if (!found)
                    continue;
            }

            dataRow = report.addElement("Row").addAttribute("name", "dataRow");
            cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "reporter")
                    .addAttribute("group", "data");
            data = cell.addElement("Data").addAttribute("type", "header").addText(ccre.getReporterId());
            data = null;
            cell = null;

            cell = dataRow.addElement("Cell").addAttribute("type", "pval").addAttribute("class", "data")
                    .addAttribute("group", "data");
            //String pv = (ccre.getPvalue() == null) ? String.valueOf(ccre.getPvalue()) : "N/A";
            BigDecimal bigd = new BigDecimal(ccre.getPvalue());
            data = cell.addElement("Data").addAttribute("type", "header").addText(bigd.toPlainString());
            data = null;
            cell = null;

            cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data")
                    .addAttribute("group", "data");
            data = cell.addElement("Data").addAttribute("type", "header")
                    .addText(resultFormat.format(ccre.getMeanGrp1()) + " / "
                            + resultFormat.format(ccre.getMeanBaselineGrp()));
            data = null;
            cell = null;

            cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data")
                    .addAttribute("group", "data");
            data = cell.addElement("Data").addAttribute("type", "header")
                    .addText(String.valueOf(resultFormat.format(ccre.getFoldChange())));
            data = null;
            cell = null;

            //if only showing genes
            if (!allAnnotations && reporterResultsetMap != null) {
                String reporterId = ccre.getReporterId();
                String genes = reporterResultsetMap.get(reporterId) != null
                        ? (String) reporterResultsetMap.get(reporterId)
                        : defaultV;
                cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "gene")
                        .addAttribute("group", "data");
                data = cell.addElement("Data").addAttribute("type", "header").addText(genes);
                data = null;
                cell = null;
            } else {
                //get the gene symbols for this reporter
                //ccre.getReporterId()
                String genes = defaultV;

                //start annotations
                String accIds = defaultV;
                String llink = defaultV;
                String go = defaultV;
                String pw = defaultV;

                if (reporterResultsetMap != null) { // && reporterIds != null
                    //int count = 0;
                    String reporterId = ccre.getReporterId();
                    //ReporterResultset reporterResultset = reporterResultsetMap.get(reporterId);
                    ReporterAnnotations ra = (ReporterAnnotations) reporterResultsetMap.get(reporterId);

                    //Collection<String> geneSymbols = (Collection<String>)reporterResultset.getAssiciatedGeneSymbols();
                    String geneSymbols = ra.getGeneSymbol();
                    if (geneSymbols != null)
                        genes = geneSymbols;
                    /*
                    if(geneSymbols != null){
                       genes = StringUtils.join(geneSymbols.toArray(), delim);
                    }
                    */
                    Collection<String> genBank_AccIDS = (Collection<String>) ra.getAccessions();
                    if (genBank_AccIDS != null) {
                        accIds = StringUtils.join(genBank_AccIDS.toArray(), delim);
                    }
                    Collection<String> locusLinkIDs = (Collection<String>) ra.getLocusLinks();
                    if (locusLinkIDs != null) {
                        llink = StringUtils.join(locusLinkIDs.toArray(), delim);
                    }
                    Collection<String> goIds = (Collection<String>) ra.getGoIDS();
                    if (goIds != null) {
                        go = StringUtils.join(goIds.toArray(), delim);
                    }
                    Collection<String> pathways = (Collection<String>) ra.getPathways();
                    if (pathways != null) {
                        pw = StringUtils.join(pathways.toArray(), delim);
                    }
                }

                cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "gene")
                        .addAttribute("group", "data");
                data = cell.addElement("Data").addAttribute("type", "header").addText(genes);
                data = null;
                cell = null;
                cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv")
                        .addAttribute("group", "data");
                data = cell.addElement("Data").addAttribute("type", "header").addText(accIds);
                data = null;
                cell = null;
                cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv")
                        .addAttribute("group", "data");
                data = cell.addElement("Data").addAttribute("type", "header").addText(llink);
                data = null;
                cell = null;
                cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv")
                        .addAttribute("group", "data");
                data = cell.addElement("Data").addAttribute("type", "header").addText(go);
                data = null;
                cell = null;
                cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv")
                        .addAttribute("group", "data");
                data = cell.addElement("Data").addAttribute("type", "header").addText(pw);
                data = null;
                cell = null;

            }
        }
    } else {
        //TODO: handle this error
        sb.append("<br/><br/>Class Comparison is empty<br/>");
    }

    return document;
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.AddAssociatedConceptsPreprocessor.java

private void addFields(int numberConcepts) {
    //Clear out all fields in edit configuration first
    editConfiguration.setFields(new HashMap<String, FieldVTwo>());
    int index;/* ww  w .  ja v a  2 s.  co m*/
    HashSet<String> conceptSemanticTypeUris = new HashSet<String>();
    // First one already included in generator so add additional ones here
    for (index = 1; index <= numberConcepts; index++) {
        int suffix = index;
        String conceptNode = conceptNodeBase + suffix;
        String label = labelBase + suffix;
        String source = sourceBase + suffix;
        String conceptSemanticTypeLabel = conceptSemanticTypeLabelBase + suffix;
        String conceptSemanticTypeURI = this.getConceptSemanticTypeURIFieldName(conceptSemanticTypeLabel,
                suffix);
        String conceptBroaderURI = conceptBroaderURIBase + suffix;
        String conceptNarrowerURI = conceptNarrowerURIBase + suffix;
        addConceptNodeField(conceptNode);
        addLabelField(label);
        addSourceField(source);
        //Also add fields for concept semantic type label
        addConceptSemanticTypeLabelField(conceptSemanticTypeLabel);
        //and concept semantic type URI
        if (!conceptSemanticTypeUris.contains(conceptSemanticTypeURI)) {
            conceptSemanticTypeUris.add(conceptSemanticTypeURI);
            addConceptSemanticTypeURIField(conceptSemanticTypeURI);
        }

        //add fields for concept broader and narrower uris
        addConceptBroaderURIField(conceptBroaderURI);
        addConceptNarrowerURIField(conceptNarrowerURI);
    }
}