Example usage for java.util LinkedHashMap containsKey

List of usage examples for java.util LinkedHashMap containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.finra.herd.service.impl.BusinessObjectFormatServiceImpl.java

/**
 * Validates a list of schema columns.//from   w ww. j  a  va  2 s  .  c  o  m
 *
 * @param schemaColumns the list of schema columns.
 * @param schemaEqualityValidationMap a map of schema column names to their schema column. This is used to check equality across all data schema columns as
 * well as partition schema columns.
 */
private void validateSchemaColumns(List<SchemaColumn> schemaColumns,
        LinkedHashMap<String, SchemaColumn> schemaEqualityValidationMap) {
    // Validate schema columns if they are specified.
    if (!CollectionUtils.isEmpty(schemaColumns)) {
        // Create a schema column name map that we will use to check for duplicate
        // columns for the specified list of schema columns (i.e. data or partition).
        LinkedHashMap<String, SchemaColumn> schemaColumnNameValidationMap = new LinkedHashMap<>();

        // Loop through each schema column in the list.
        for (SchemaColumn schemaColumn : schemaColumns) {
            // Perform validation.
            Assert.hasText(schemaColumn.getName(), "A schema column name must be specified.");
            Assert.hasText(schemaColumn.getType(), "A schema column data type must be specified.");

            // Remove leading and trailing spaces.
            schemaColumn.setName(schemaColumn.getName().trim());
            schemaColumn.setType(schemaColumn.getType().trim());
            schemaColumn.setSize(schemaColumn.getSize() == null ? null : schemaColumn.getSize().trim());
            schemaColumn.setDefaultValue(
                    schemaColumn.getDefaultValue() == null ? null : schemaColumn.getDefaultValue().trim());
            // Check if schema column is prone to CSV Injection attack
            checkSchemaColumnCsvInjection(schemaColumn);

            // Ensure the column name isn't a duplicate within this list only by using a map.
            String lowercaseSchemaColumnName = schemaColumn.getName().toLowerCase();
            if (schemaColumnNameValidationMap.containsKey(lowercaseSchemaColumnName)) {
                throw new IllegalArgumentException(
                        String.format("Duplicate schema column name \"%s\" found.", schemaColumn.getName()));
            }
            schemaColumnNameValidationMap.put(lowercaseSchemaColumnName, schemaColumn);

            // Ensure a partition column and a data column are equal (i.e. contain the same configuration).
            SchemaColumn existingSchemaColumn = schemaEqualityValidationMap.get(lowercaseSchemaColumnName);
            if ((existingSchemaColumn != null) && !schemaColumn.equals(existingSchemaColumn)) {
                throw new IllegalArgumentException(
                        "Schema data and partition column configurations with name \"" + schemaColumn.getName()
                                + "\" have conflicting values. All column values are case sensitive and must be identical.");
            }
            schemaEqualityValidationMap.put(lowercaseSchemaColumnName, schemaColumn);
        }
    }
}

From source file:org.cerberus.servlet.crud.testexecution.ReadTestCaseExecution.java

private AnswerItem findExecutionListByTag(ApplicationContext appContext, HttpServletRequest request, String Tag)
        throws CerberusException, ParseException, JSONException {
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);

    int startPosition = Integer
            .valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayStart"), "0"));
    int length = Integer
            .valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayLength"), "0"));

    String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
    String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"),
            "test,testCase,application,priority,status,description,bugId,function");
    String columnToSort[] = sColumns.split(",");

    //Get Sorting information
    int numberOfColumnToSort = Integer
            .parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortingCols"), "1"));
    int columnToSortParameter = 0;
    String sort = "asc";
    StringBuilder sortInformation = new StringBuilder();
    for (int c = 0; c < numberOfColumnToSort; c++) {
        columnToSortParameter = Integer
                .parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortCol_" + c), "0"));
        sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_" + c), "asc");
        String columnName = columnToSort[columnToSortParameter];
        sortInformation.append(columnName).append(" ").append(sort);

        if (c != numberOfColumnToSort - 1) {
            sortInformation.append(" , ");
        }//from  w w w . j  a  v a  2  s  . co  m
    }

    Map<String, List<String>> individualSearch = new HashMap<String, List<String>>();
    for (int a = 0; a < columnToSort.length; a++) {
        if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
            List<String> search = new ArrayList(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
            individualSearch.put(columnToSort[a], search);
        }
    }

    List<TestCaseExecution> testCaseExecutions = readExecutionByTagList(appContext, Tag, startPosition, length,
            sortInformation.toString(), searchParameter, individualSearch);

    JSONArray executionList = new JSONArray();
    JSONObject statusFilter = getStatusList(request);
    JSONObject countryFilter = getCountryList(request, appContext);
    LinkedHashMap<String, JSONObject> ttc = new LinkedHashMap<String, JSONObject>();

    String globalStart = "";
    String globalEnd = "";
    String globalStatus = "Finished";

    /**
     * Find the list of labels
     */
    AnswerList testCaseLabelList = testCaseLabelService.readByTestTestCase(null, null);

    for (TestCaseExecution testCaseExecution : testCaseExecutions) {
        try {
            if (testCaseExecution.getStart() != 0) {
                if ((globalStart.isEmpty())
                        || (globalStart.compareTo(String.valueOf(testCaseExecution.getStart())) > 0)) {
                    globalStart = String.valueOf(testCaseExecution.getStart());
                }
            }
            if (testCaseExecution.getEnd() != 0) {
                if ((globalEnd.isEmpty())
                        || (globalEnd.compareTo(String.valueOf(testCaseExecution.getEnd())) < 0)) {
                    globalEnd = String.valueOf(testCaseExecution.getEnd());
                }
            }
            if (testCaseExecution.getControlStatus().equalsIgnoreCase("PE")) {
                globalStatus = "Pending...";
            }
            String controlStatus = testCaseExecution.getControlStatus();
            if (statusFilter.get(controlStatus).equals("on")
                    && countryFilter.get(testCaseExecution.getCountry()).equals("on")) {
                JSONObject execution = testCaseExecutionToJSONObject(testCaseExecution);
                String execKey = testCaseExecution.getEnvironment() + " " + testCaseExecution.getCountry() + " "
                        + testCaseExecution.getBrowser();
                String testCaseKey = testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase();
                JSONObject execTab = new JSONObject();

                executionList.put(testCaseExecutionToJSONObject(testCaseExecution));
                JSONObject ttcObject = new JSONObject();

                if (ttc.containsKey(testCaseKey)) {
                    ttcObject = ttc.get(testCaseKey);
                    execTab = ttcObject.getJSONObject("execTab");
                    execTab.put(execKey, execution);
                    ttcObject.put("execTab", execTab);
                } else {
                    ttcObject.put("test", testCaseExecution.getTest());
                    ttcObject.put("testCase", testCaseExecution.getTestCase());
                    ttcObject.put("function", testCaseExecution.getTestCaseObj().getFunction());
                    ttcObject.put("shortDesc", testCaseExecution.getTestCaseObj().getDescription());
                    ttcObject.put("status", testCaseExecution.getStatus());
                    ttcObject.put("application", testCaseExecution.getApplication());
                    ttcObject.put("priority", testCaseExecution.getTestCaseObj().getPriority());
                    ttcObject.put("bugId",
                            new JSONObject(
                                    "{\"bugId\":\"" + testCaseExecution.getTestCaseObj().getBugID()
                                            + "\",\"bugTrackerUrl\":\""
                                            + testCaseExecution.getApplicationObj().getBugTrackerUrl().replace(
                                                    "%BUGID%", testCaseExecution.getTestCaseObj().getBugID())
                                            + "\"}"));
                    ttcObject.put("comment", testCaseExecution.getTestCaseObj().getComment());
                    execTab.put(execKey, execution);
                    ttcObject.put("execTab", execTab);

                    /**
                     * Iterate on the label retrieved and generate HashMap
                     * based on the key Test_TestCase
                     */
                    LinkedHashMap<String, JSONArray> testCaseWithLabel = new LinkedHashMap();
                    for (TestCaseLabel label : (List<TestCaseLabel>) testCaseLabelList.getDataList()) {
                        String key = label.getTest() + "_" + label.getTestcase();

                        if (testCaseWithLabel.containsKey(key)) {
                            JSONObject jo = new JSONObject().put("name", label.getLabel().getLabel())
                                    .put("color", label.getLabel().getColor())
                                    .put("description", label.getLabel().getDescription());
                            testCaseWithLabel.get(key).put(jo);
                        } else {
                            JSONObject jo = new JSONObject().put("name", label.getLabel().getLabel())
                                    .put("color", label.getLabel().getColor())
                                    .put("description", label.getLabel().getDescription());
                            testCaseWithLabel.put(key, new JSONArray().put(jo));
                        }
                    }
                    ttcObject.put("labels", testCaseWithLabel
                            .get(testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase()));
                }
                ttc.put(testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase(), ttcObject);
            }
        } catch (JSONException ex) {
            Logger.getLogger(ReadTestCaseExecution.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    JSONObject jsonResponse = new JSONObject();

    jsonResponse.put("globalEnd", globalEnd.toString());
    jsonResponse.put("globalStart", globalStart.toString());
    jsonResponse.put("globalStatus", globalStatus);

    jsonResponse.put("testList", ttc.values());
    jsonResponse.put("iTotalRecords", ttc.size());
    jsonResponse.put("iTotalDisplayRecords", ttc.size());

    answer.setItem(jsonResponse);
    answer.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    return answer;
}

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

@SuppressWarnings("unchecked")
private List<ImportantTerm> getImportantTerms(FullTextQuery fullTextQuery, int count, boolean filterStopWords) {
    final Long start = System.currentTimeMillis();
    final List<Object[]> results = fullTextQuery.list();
    final LinkedHashMap<String, Tuple<Integer, Float>> termCountMap = new LinkedHashMap<String, Tuple<Integer, Float>>();

    final FullTextSession fullTextSession = Search.getFullTextSession((Session) this.em.getDelegate());
    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    final IndexReaderAccessor ira = searchFactory.getIndexReaderAccessor();
    final IndexReader reader = ira.open(com.mothsoft.alexis.domain.Document.class);
    final IndexSearcher searcher = new IndexSearcher(reader);

    final List<ImportantTerm> importantTerms;
    final int numDocs;
    try {//from w ww. ja  v a2 s.  c om
        numDocs = reader.numDocs();
        Term luceneTerm = new Term(CONTENT_TEXT_FIELD_NAME);

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Found %d matching Lucene documents of %d in reader", results.size(),
                    numDocs));
        }

        // loop over all the matching documents
        for (final Object[] ith : results) {
            int docId = ((Number) ith[0]).intValue();
            final TermFreqVector tfv = reader.getTermFreqVector(docId, CONTENT_TEXT_FIELD_NAME);

            if (tfv == null) {
                continue;
            }

            final String[] terms = tfv.getTerms();
            final int[] freqs = tfv.getTermFrequencies();

            // total document size
            int size = 0;

            for (int freq : freqs) {
                size += freq;
            }

            if (logger.isDebugEnabled()) {
                logger.debug(
                        String.format("Lucene document %d has %d terms, to be merged with running count %d",
                                docId, size, termCountMap.size()));
            }

            // loop over the terms and aggregate the counts and tf-idf
            int i = 0;
            for (final String term : terms) {
                if (StopWords.ENGLISH.contains(term)) {
                    continue;
                }

                luceneTerm = luceneTerm.createTerm(term);
                final int termCount = freqs[i++];

                final Tuple<Integer, Float> countScore;
                if (termCountMap.containsKey(term)) {
                    countScore = termCountMap.get(term);
                    countScore.t1 += termCount;
                    countScore.t2 += (TFIDF.score(term, termCount, size, numDocs,
                            searcher.docFreq(luceneTerm)));
                } else {
                    countScore = new Tuple<Integer, Float>();
                    countScore.t1 = termCount;
                    countScore.t2 = (TFIDF.score(term, termCount, size, numDocs, searcher.docFreq(luceneTerm)));
                    termCountMap.put(term, countScore);
                }
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Completed Lucene document processing.");
        }

        importantTerms = new ArrayList<ImportantTerm>(termCountMap.size());

        // find max TF-IDF
        float maxTfIdf = 0.0f;
        for (final Tuple<Integer, Float> ith : termCountMap.values()) {
            if (ith.t2 > maxTfIdf) {
                maxTfIdf = ith.t2;
            }
        }

        for (final Map.Entry<String, Tuple<Integer, Float>> entry : termCountMap.entrySet()) {
            final int ithCount = entry.getValue().t1;
            final float ithTfIdf = entry.getValue().t2;
            importantTerms.add(new ImportantTerm(entry.getKey(), ithCount, ithTfIdf, maxTfIdf));
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Completed term aggregation, will clear term map");
        }

        termCountMap.clear();

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            searcher.close();
        } catch (IOException e) {
            logger.warn("Failed to close searcher: " + e, e);
        }
        ira.close(reader);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Sorting terms");
    }

    Collections.sort(importantTerms, new Comparator<ImportantTerm>() {
        @Override
        public int compare(ImportantTerm term1, ImportantTerm term2) {
            return -1 * term1.getTfIdf().compareTo(term2.getTfIdf());
        }
    });

    if (logger.isDebugEnabled()) {
        logger.debug("Term sort complete");
    }

    if (importantTerms.isEmpty() || importantTerms.size() < count) {
        if (logger.isDebugEnabled()) {
            logger.debug("Will return full list.");
        }
        logger.debug("Timer: " + (System.currentTimeMillis() - start));
        return importantTerms;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Will return sublist containing " + count + " of " + importantTerms.size() + " terms.");
        }

        logger.debug("Timer: " + (System.currentTimeMillis() - start));
        return importantTerms.subList(0, count);
    }
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

@Override
public List<Restriction> getForeignKeyPolymTypeList(String xpathForeignKey, String language)
        throws ServiceException {
    try {//  w  w  w  .  j ava 2 s . c om
        String fkEntityType;
        ReusableType entityReusableType = null;
        List<Restriction> ret = new ArrayList<Restriction>();

        if (xpathForeignKey != null && xpathForeignKey.length() > 0) {
            if (xpathForeignKey.startsWith("/")) { //$NON-NLS-1$
                xpathForeignKey = xpathForeignKey.substring(1);
            }
            String fkEntity;
            if (xpathForeignKey.contains("/")) {//$NON-NLS-1$
                fkEntity = xpathForeignKey.substring(0, xpathForeignKey.indexOf("/"));//$NON-NLS-1$
            } else {
                fkEntity = xpathForeignKey;
            }

            fkEntityType = SchemaWebAgent.getInstance().getBusinessConcept(fkEntity).getCorrespondTypeName();
            if (fkEntityType != null) {
                entityReusableType = SchemaWebAgent.getInstance().getReusableType(fkEntityType);
            }
            if (entityReusableType != null) {
                entityReusableType.load();
            }
            List<ReusableType> subtypes = SchemaWebAgent.getInstance().getMySubtypes(fkEntityType, true);
            if (fkEntityType != null && entityReusableType != null && !entityReusableType.isAbstract()) {
                subtypes.add(0, entityReusableType);
            }
            List<BusinessConcept> list = SchemaWebAgent.getInstance().getAllBusinessConcepts();
            LinkedHashMap<String, String> businessConceptMap = new LinkedHashMap<String, String>();
            if (list != null) {
                for (BusinessConcept businessConcept : list) {
                    if (businessConcept.getCorrespondTypeName() != null
                            && businessConcept.getCorrespondTypeName().trim().length() > 0) {
                        businessConceptMap.put(businessConcept.getCorrespondTypeName(),
                                businessConcept.getName());
                    }
                }
            }
            for (ReusableType reusableType : subtypes) {
                if (businessConceptMap.containsKey(reusableType.getName())) {
                    Restriction re = new Restriction();
                    EntityModel entityModel = getEntityModel(businessConceptMap.get(reusableType.getName()),
                            language);
                    re.setName(entityModel.getConceptLabel(language));
                    re.setValue(entityModel.getConceptName());
                    ret.add(re);
                }
            }
        }

        return ret;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new ServiceException(e.getLocalizedMessage());
    }
}

From source file:com.sonicle.webtop.contacts.ContactsManager.java

@Override
public Map<Integer, ShareFolderCategory> listIncomingCategoryFolders(String rootShareId) throws WTException {
    CoreManager coreMgr = WT.getCoreManager(getTargetProfileId());
    LinkedHashMap<Integer, ShareFolderCategory> folders = new LinkedHashMap<>();

    for (Integer folderId : shareCache.getFolderIdsByShareRoot(rootShareId)) {
        final String shareFolderId = shareCache.getShareFolderIdByFolderId(folderId);
        if (StringUtils.isBlank(shareFolderId))
            continue;
        SharePermsFolder fperms = coreMgr.getShareFolderPermissions(shareFolderId);
        SharePermsElements eperms = coreMgr.getShareElementsPermissions(shareFolderId);
        if (folders.containsKey(folderId)) {
            final ShareFolderCategory shareFolder = folders.get(folderId);
            if (shareFolder == null)
                continue;
            shareFolder.getPerms().merge(fperms);
            shareFolder.getElementsPerms().merge(eperms);
        } else {// w  w  w.j a v  a2s  .  c om
            final Category category = getCategory(folderId);
            if (category == null)
                continue;
            folders.put(folderId, new ShareFolderCategory(shareFolderId, fperms, eperms, category));
        }
    }
    return folders;
}

From source file:org.bimserver.charting.Algorithms.Binning.java

public void handlePointAndIndex(Vector2d point, Vector2d worldSpacePoint,
        LinkedHashMap<String, Bin> existingBins) {
    // Distance formula: c^2 = a^2 + b^2
    // Calculate world space y as a ratio to the delta y.
    double py = worldSpacePoint.y() / Delta.y();
    // Derivisions from py.
    int pj = (int) Math.round(py);
    // Indent row if y value is not even.
    boolean pjIsNotEvenAtThisPoint = (Math.abs(pj % 2) == 1);
    // "b" of distance formula.
    //double bOfWorldSpaceRoundingDeviation = py - pj;
    // Calculate world space x as a ratio to the delta x.
    double px = worldSpacePoint.x() / Delta.x() - (pjIsNotEvenAtThisPoint ? .5 : 0);
    // Derivisions from px.
    int pi = (int) Math.round(px);
    // TODO: Figure out what this case represents. It's less of a priority because it destroys the syntactical notion of the variable "pi" (not to be confused with Math.PI) as an integer.
    /*if (Math.abs(bOfWorldSpaceRoundingDeviation) * 3 > 1) {
       // "a" of distance formula.//from www  . j ava  2s .co  m
       double aOfWorldSpaceRoundingDeviation = px - pi;
       // Figure out if the world space values were rounded up.
       boolean xWasRoundedUp = (px < pi) ? true : false;
       boolean yWasRoundedUp = (py < pj) ? true : false;
       //
       double pi2 = pi + (xWasRoundedUp ? -0.5 : 0.5);
       int pj2 = pj + (yWasRoundedUp ? -1 : 1);
       double aOfWorldSpaceRecentering = px - pi2;
       double bOfWorldSpaceRecentering = py - pj2;
       // The penultimate step of the distance function to the rounded coordinates, left as-is for comparison.
       double cSquaredOfWorldSpaceRoundingDeviation = Math.pow(aOfWorldSpaceRoundingDeviation, 2) + Math.pow(bOfWorldSpaceRoundingDeviation, 2);
       // The penultimate step of the distance function to the recentered coordinates, left as-is for comparison.
       double cSquaredOfWorldSpaceRecentering = Math.pow(aOfWorldSpaceRecentering, 2) + Math.pow(bOfWorldSpaceRecentering, 2);
       // ADDITION: Avoid denaturing integer.
       double piNot = pi;
       // If the rounded coordinates are farther away, use the recentered ones.
       if (cSquaredOfWorldSpaceRoundingDeviation > cSquaredOfWorldSpaceRecentering) {
    piNot = (pjIsNotEvenAtThisPoint) ? pi2 + 0.5 : pi2 - 0.5;
    pj = pj2;
    pjIsNotEvenAtThisPoint = (pj % 2 == 1);
       }
       // Create ID for bin in format of WorldSpaceX-WorldSpaceY.
       String id = String.format("%s-%s", piNot, pj);
       // If ID a already exists, add the point.
       if (existingBins.containsKey(id)) {
    Bin bin = existingBins.get(id);
    bin.add(point);
       }
       // Otherwise, create a bin and set the appropriate locations.
       else {
    Bin thisBin = new Bin(Arrays.asList(point));
    // Center in world space.
    thisBin.WorldSpaceLocation = new Vector2d(piNot, pj);
    // Center in raw data as (cx, cy).
    double modifier = (pjIsNotEvenAtThisPoint) ? 0.5 : 0;
    double cx = (piNot + modifier) * Delta.x();
    double cy = pj * Delta.y();
    thisBin.Location = new Vector2d(cx, cy);
    // Add bin.
    existingBins.put(id, thisBin);
       }
    } else {*/
    // Create ID for bin in format of WorldSpaceX-WorldSpaceY.
    String id = String.format("%s-%s", pi, pj);
    // If ID a already exists, add the point.
    if (existingBins.containsKey(id)) {
        Bin bin = existingBins.get(id);
        bin.add(point);
    }
    // Otherwise, create a bin and set the appropriate locations.
    else {
        Bin thisBin = new Bin(Arrays.asList(point));
        // Center in world space.
        thisBin.WorldSpaceLocation = new Vector2d(pi, pj);
        // Center in raw data as (cx, cy).
        double modifier = (pjIsNotEvenAtThisPoint) ? 0.5 : 0;
        double cx = (pi + modifier) * Delta.x();
        double cy = pj * Delta.y();
        thisBin.Location = new Vector2d(cx, cy);
        // Add bin.
        existingBins.put(id, thisBin);
    }
    //}
}

From source file:ubic.gemma.visualization.ExperimentalDesignVisualizationServiceImpl.java

/**
 * @param experiment//from  ww w .  ja va 2s.c om
 * @param bd
 * @return map of bioassays to map of factors to doubles that represent the position in the layout.
 */
private LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> getExperimentalDesignLayout(
        ExpressionExperiment experiment, BioAssayDimensionValueObject bd) {
    LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> result = new LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>();

    /*
     * This is FAST - 2 ms
     */
    ExpressionDataMatrix<Object> mat = new EmptyExpressionMatrix(bd.getEntity());

    List<BioMaterial> bms = ExpressionDataMatrixColumnSort.orderByExperimentalDesign(mat);

    Map<Long, Double> fvV = new HashMap<Long, Double>();

    assert experiment != null;
    assert experiment.getExperimentalDesign() != null;
    if (experiment.getExperimentalDesign().getExperimentalFactors().size() == 0) {

        ExperimentalFactor dummyFactor = ExperimentalFactor.Factory.newInstance();
        dummyFactor.setName("No factors");
        for (BioMaterial bm : bms) {
            int j = mat.getColumnIndex(bm);

            Collection<BioAssay> bas = mat.getBioAssaysForColumn(j);

            for (BioAssay ba : bas) {
                BioAssayValueObject bavo = new BioAssayValueObject(ba);
                result.put(bavo, new LinkedHashMap<ExperimentalFactor, Double>());
                result.get(bavo).put(dummyFactor, 0.0);
            }

        }

        return result;
    }

    assert !experiment.getExperimentalDesign().getExperimentalFactors().isEmpty();
    for (ExperimentalFactor ef : experiment.getExperimentalDesign().getExperimentalFactors()) {
        // Double i = 0.0;
        assert !ef.getFactorValues().isEmpty();
        for (FactorValue fv : ef.getFactorValues()) {
            // i = i + 1.0;
            // fvV.put( fv, i ); // just for now, a placeholder value.
            if (fv.getId() == null) {
                log.warn("FactorValue has null id, this shouldn't happen!" + fv.toString());
            }
            assert fv.getId() != null;
            fvV.put(fv.getId(), new Double(fv.getId())); // try using the factorValue id
        }
    }

    assert !fvV.isEmpty();
    assert !bms.isEmpty();
    for (BioMaterial bm : bms) {
        int j = mat.getColumnIndex(bm);

        Collection<BioAssay> bas = mat.getBioAssaysForColumn(j);

        Collection<FactorValue> fvs = bm.getFactorValues();

        for (BioAssay ba : bas) {
            BioAssayValueObject bavo = new BioAssayValueObject(ba);
            result.put(bavo, new LinkedHashMap<ExperimentalFactor, Double>(fvs.size()));
            for (FactorValue fv : fvs) {
                assert fv.getId() != null;
                assert fvV.containsKey(fv.getId());
                ExperimentalFactor ef = fv.getExperimentalFactor();

                Double value = null;
                if (fv.getMeasurement() != null) {
                    try {
                        value = Double.parseDouble(fv.getMeasurement().getValue());
                    } catch (NumberFormatException e) {
                        value = fvV.get(fv.getId()); // not good.
                    }
                } else {
                    value = fvV.get(fv.getId());
                }
                assert result.containsKey(bavo);
                assert value != null;
                result.get(bavo).put(ef, value);

            }
        }

    }
    return result;
}

From source file:io.personium.core.bar.BarFileReadRunner.java

private boolean setBulkRequests(String entryName, PersoniumODataProducer producer,
        LinkedHashMap<String, BulkRequest> bulkRequests, Map<String, String> fileNameMap) {
    BulkRequest bulkRequest = new BulkRequest();
    String key = PersoniumUUID.randomUUID();
    try {//w w  w  . java2  s .  c  om
        // entityType????
        String entityTypeName = getEntityTypeName(entryName);
        if (producer.getMetadata().findEdmEntitySet(entityTypeName) == null) {
            throw PersoniumCoreException.OData.NO_SUCH_ENTITY_SET;
        }

        // ZipArchiveImputStream??JSONStringReader????
        StringReader stringReader = getStringReaderFromZais();

        // ??
        ODataResource odataResource = odataEntityResource.getOdataResource();
        ODataEntitiesResource resource = new ODataEntitiesResource(odataResource, entityTypeName);
        OEntity oEntity = resource.getOEntityWrapper(stringReader, odataResource, producer.getMetadata());

        UserDataODataProducer userDataProducer = (UserDataODataProducer) producer;
        EntitySetDocHandler docHandler = producer.getEntitySetDocHandler(entityTypeName, oEntity);
        String docType = UserDataODataProducer.USER_ODATA_NAMESPACE;
        docHandler.setType(docType);
        docHandler.setEntityTypeId(userDataProducer.getEntityTypeId(oEntity.getEntitySetName()));

        odataEntityResource.setOdataProducer(userDataProducer);

        // ??ID??
        // TODO ?????NTKP
        key = oEntity.getEntitySetName() + ":" + (String) docHandler.getStaticFields().get("__id");

        if (bulkRequests.containsKey(key)) {
            throw PersoniumCoreException.OData.ENTITY_ALREADY_EXISTS;
        }

        // ID?????UUID??
        if (docHandler.getId() == null) {
            docHandler.setId(PersoniumUUID.randomUUID());
        }
        bulkRequest.setEntitySetName(entityTypeName);
        bulkRequest.setDocHandler(docHandler);
    } catch (Exception e) {
        writeOutputStream(true, "PL-BI-1004", entryName, e.getMessage());
        log.info(entryName + " : " + e.getMessage());
        bulkRequest.setError(e);
        return false;
    }
    bulkRequests.put(key, bulkRequest);
    fileNameMap.put(key, entryName);
    return true;
}

From source file:com.fujitsu.dc.core.bar.BarFileReadRunner.java

private boolean setBulkRequests(String entryName, DcODataProducer producer,
        LinkedHashMap<String, BulkRequest> bulkRequests, Map<String, String> fileNameMap) {
    BulkRequest bulkRequest = new BulkRequest();
    String key = DcUUID.randomUUID();
    try {//from  ww w .  j a v a2 s .  co m
        // entityType????
        String entityTypeName = getEntityTypeName(entryName);
        if (producer.getMetadata().findEdmEntitySet(entityTypeName) == null) {
            throw DcCoreException.OData.NO_SUCH_ENTITY_SET;
        }

        // ZipArchiveImputStream??JSONStringReader????
        StringReader stringReader = getStringReaderFromZais();

        // ??
        ODataResource odataResource = odataEntityResource.getOdataResource();
        ODataEntitiesResource resource = new ODataEntitiesResource(odataResource, entityTypeName);
        OEntity oEntity = resource.getOEntityWrapper(stringReader, odataResource, producer.getMetadata());

        UserDataODataProducer userDataProducer = (UserDataODataProducer) producer;
        EntitySetDocHandler docHandler = producer.getEntitySetDocHandler(entityTypeName, oEntity);
        String docType = UserDataODataProducer.USER_ODATA_NAMESPACE;
        docHandler.setType(docType);
        docHandler.setEntityTypeId(userDataProducer.getEntityTypeId(oEntity.getEntitySetName()));

        odataEntityResource.setOdataProducer(userDataProducer);

        // ??ID??
        // TODO ?????NTKP
        key = oEntity.getEntitySetName() + ":" + (String) docHandler.getStaticFields().get("__id");

        if (bulkRequests.containsKey(key)) {
            throw DcCoreException.OData.ENTITY_ALREADY_EXISTS;
        }

        // ID?????UUID??
        if (docHandler.getId() == null) {
            docHandler.setId(DcUUID.randomUUID());
        }
        bulkRequest.setEntitySetName(entityTypeName);
        bulkRequest.setDocHandler(docHandler);
    } catch (Exception e) {
        writeOutputStream(true, "PL-BI-1004", entryName, e.getMessage());
        log.info(entryName + " : " + e.getMessage());
        bulkRequest.setError(e);
        return false;
    }
    bulkRequests.put(key, bulkRequest);
    fileNameMap.put(key, entryName);
    return true;
}

From source file:ubic.gemma.core.visualization.ExperimentalDesignVisualizationServiceImpl.java

/**
 * @param bds a BioAssayDimension that represents the BioAssayDimensionValueObject. This is only needed to avoid
 *            making ExpressionMatrix use value objects, otherwise we could use the BioAssayDimensionValueObject
 * @return A "Layout": a map of bioassays to map of factors to doubles that represent the position in the layout.
 *//*from   w  w  w . ja  v  a2  s . com*/
private LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> getExperimentalDesignLayout(
        ExpressionExperiment experiment, Collection<BioAssayDimension> bds) {

    LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> result = new LinkedHashMap<>();

    ExpressionDataMatrix<Object> mat = new EmptyExpressionMatrix(bds);

    // This is the place the actual sort order is determined.
    List<BioMaterial> bms = ExpressionDataMatrixColumnSort.orderByExperimentalDesign(mat);

    Map<Long, Double> fvV = new HashMap<>();

    assert experiment != null;
    assert experiment.getExperimentalDesign() != null;
    if (experiment.getExperimentalDesign().getExperimentalFactors().isEmpty()) {
        // Case of no experimental design; just put in a dummy factor.
        ExperimentalFactor dummyFactor = ExperimentalFactor.Factory.newInstance();
        dummyFactor.setName("No factors");
        for (BioMaterial bm : bms) {
            int j = mat.getColumnIndex(bm);

            Collection<BioAssay> bas = mat.getBioAssaysForColumn(j);

            for (BioAssay ba : bas) {
                BioAssayValueObject baVo = new BioAssayValueObject(ba, false);
                result.put(baVo, new LinkedHashMap<ExperimentalFactor, Double>());
                result.get(baVo).put(dummyFactor, 0.0);
            }

        }

        return result;
    }

    assert !experiment.getExperimentalDesign().getExperimentalFactors().isEmpty();
    /*
     * Choose values to use as placeholders.
     */
    // Map<ExperimentalFactor, Map<FactorValue, Double>> continuousRanges = new HashMap<>();
    for (ExperimentalFactor ef : experiment.getExperimentalDesign().getExperimentalFactors()) {
        if (ef.getFactorValues().isEmpty()) {
            // this can happen if the design isn't complete.
            continue;
        }

        for (FactorValue fv : ef.getFactorValues()) {
            assert fv.getId() != null;
            // the id is just used as a convenience.
            fvV.put(fv.getId(), new Double(fv.getId()));

        }

    }

    assert !fvV.isEmpty();
    assert !bms.isEmpty();

    // if the same biomaterial was used in more than one bioassay (thus more than one bioassay dimension), and they
    // are in the same column, this is resolved here; we assign the same layout value for both bioassays, so the
    // ordering is the same for vectors coming from
    // either bioassay dimension.
    for (BioMaterial bm : bms) {
        int j = mat.getColumnIndex(bm);

        Collection<BioAssay> bas = mat.getBioAssaysForColumn(j);

        Collection<FactorValue> fvs = bm.getFactorValues();

        for (BioAssay ba : bas) {
            BioAssayValueObject baVo = new BioAssayValueObject(ba, false);
            result.put(baVo, new LinkedHashMap<ExperimentalFactor, Double>(fvs.size()));
            for (FactorValue fv : fvs) {
                assert fv.getId() != null;
                assert fvV.containsKey(fv.getId());
                ExperimentalFactor ef = fv.getExperimentalFactor();
                Double value;
                if (fv.getMeasurement() != null) {
                    try {
                        value = Double.parseDouble(fv.getMeasurement().getValue());
                    } catch (NumberFormatException e) {
                        value = fvV.get(fv.getId()); // not good.
                    }
                } else {
                    value = fvV.get(fv.getId());
                }
                assert result.containsKey(baVo);
                assert value != null;
                result.get(baVo).put(ef, value);

            }
        }

    }
    return result;
}