Example usage for java.util HashMap containsKey

List of usage examples for java.util HashMap containsKey

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

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

Usage

From source file:carskit.data.processor.DataTransformer.java

public String TransformationFromLooseToBinary() throws Exception {
    BufferedReader br = FileIO.getReader(dataPath);
    String line = br.readLine(); // 1st line;
    HashMap<String, HashMap<String, String>> newlines = new LinkedHashMap();
    Multimap<String, String> conditions = TreeMultimap.create(); // key=dim, value=cond, keep the order when we adding to it
    while ((line = br.readLine()) != null) {
        String[] strs = line.split(",", -1);
        String key = strs[0].trim().toLowerCase() + "," + strs[1].trim().toLowerCase() + ","
                + strs[2].trim().toLowerCase(); // key = user,item,rating
        String cond = strs[4].trim().toLowerCase();
        if (cond.equals(""))
            cond = "na";
        conditions.put(strs[3].trim().toLowerCase(), cond);
        if (newlines.containsKey(key)) {
            HashMap<String, String> ratingcontext = newlines.get(key);
            ratingcontext.put(strs[3].trim().toLowerCase(), cond);

        } else {//  w  w w  .  ja v a  2s.  c om
            HashMap<String, String> ratingcontext = new HashMap();
            ratingcontext.put(strs[3].trim().toLowerCase(), cond);
            newlines.put(key, ratingcontext);
        }
    }
    br.close();

    this.PublishNewRatingFiles(outputfolder, conditions, newlines, true);

    if (FileIO.exist(outputfolder + "ratings_binary.txt"))
        return "Data transformaton completed (from Loose to Binary format). See new rating file: "
                + outputfolder + "ratings_binary.txt";
    else
        return "Data transformation failed. See output folder: " + outputfolder;
}

From source file:com.davidgildeh.hadoop.input.simpledb.SimpleDBDAO.java

/**
 * Select a list of unique results as Hashmap. The field will specify which 
 * field to return all unique results for, and the HashMap value for that field
 * will contain a count of how many times that field value occurred in the results
 * //from ww w.  j  a v a 2s.  c om
 * @param field     The field name to get unique results for
 * @return          A HashMap of unique results with a count of how many times they
 *                  occur in the result set
 */
public HashMap<String, Integer> doSelectUniqueQuery(final String field) {

    HashMap<String, Integer> uniqueResults = new HashMap<String, Integer>();
    SelectResult results = doQuery(createQuery(false, -1), null);
    int totalCount = 0;

    while ((results.getNextToken() != null)) {

        for (Item item : results.getItems()) {

            for (Attribute attribute : item.getAttributes()) {

                // Check if the result is unique
                if (attribute.getName().equals(field)) {
                    final String value = attribute.getValue();

                    if (!uniqueResults.containsKey(value)) {

                        uniqueResults.put(value, 1);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug(String.valueOf(++totalCount) + " - " + value);
                        }

                    } else {
                        Integer count = uniqueResults.get(value);
                        uniqueResults.put(value, ++count);
                    }
                }
            }
        }

        // Get next results
        results = doQuery(createQuery(false, -1), results.getNextToken());
    }

    // Return full list of unique results
    return uniqueResults;
}

From source file:fr.paris.lutece.plugins.document.service.attributes.ListBoxManager.java

/**
 * {@inheritDoc}//ww w.  j  a  v a  2s  . c  om
 */
@Override
protected Map<String, List<String>> getParameters(int nAttributeId, Locale locale) {
    HashMap<String, List<String>> mapParameters = new HashMap<String, List<String>>();
    Collection<AttributeTypeParameter> listParameters = getAttributeParametersValues(nAttributeId, locale);

    for (AttributeTypeParameter parameter : listParameters) {
        // We sort attributes alphabetically
        List<String> listValues = parameter.getValueList();
        Collections.sort(listValues);
        mapParameters.put(parameter.getName(), listValues);
    }

    // Set all missing parameters with their default values
    for (AttributeTypeParameter parameter : getExtraParameters(locale)) {
        if (!mapParameters.containsKey(parameter.getName())) {
            mapParameters.put(parameter.getName(), parameter.getDefaultValue());
        }
    }

    return mapParameters;
}

From source file:userinterface.StateNetworkAdminRole.StateReportsJPanel.java

private CategoryDataset createDataSetForpatientDonorReports() {
    DefaultCategoryDataset barChartData = new DefaultCategoryDataset();
    ArrayList<String> array = new ArrayList<>();
    array.add("patient");
    array.add("donor");

    for (String item : array) {
        HashMap<Integer, Integer> map = new HashMap<>();
        if (item.equals("patient")) {
            for (Patient patient : patientList.getPatientDirectory()) {
                {//w w w.  j  ava2s  . co m
                    int counter = 1;
                    Date regDate = patient.getTransplantRequestDate();
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(regDate);
                    int year = cal.get(Calendar.YEAR);
                    if (map.containsKey(year)) {
                        counter = map.get(year);
                        counter++;
                        map.put(year, counter);
                    } else {
                        map.put(year, counter);
                    }
                }
            }
            for (Map.Entry<Integer, Integer> entryset : map.entrySet()) {
                barChartData.addValue(entryset.getValue(), item, entryset.getKey());
            }
        } else {
            for (Donor donor : donorDirectory.getDonorList()) {
                {
                    int counter = 1;
                    Date regDate = donor.getDonorRegisterationDate();
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(regDate);
                    int year = cal.get(Calendar.YEAR);
                    if (map.containsKey(year)) {
                        counter = map.get(year);
                        counter++;
                        map.put(year, counter);
                    } else {
                        map.put(year, counter);
                    }
                }
            }
            for (Map.Entry<Integer, Integer> entryset : map.entrySet()) {
                barChartData.addValue(entryset.getValue(), item, entryset.getKey());
            }
        }

    }

    return barChartData;
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

public void loadInitialUnitUsage() {
    final SQLiteDatabase db = getWritableDatabase();
    // load the initial table in
    final ContentValues cv = new ContentValues();

    Log.d(TAG, "init all weights hash");
    final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size());
    Log.d(TAG, "adding all known weights...");
    for (final String unitName : Unit.table.keySet()) {
        // don't add all uppercase names
        if (!unitName.toUpperCase().equals(unitName)) {
            allUnitWeights.put(unitName, 0);
        }/*from ww  w . j  a  v  a  2s  . c o m*/
    }
    Log.d(TAG, "adding all known functions...");
    for (final String functionName : BuiltInFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    //      for (final String functionName: TabularFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    //      for (final String functionName: ComputedFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    for (final String functionName : DefinedFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    Log.d(TAG, "adding common weights");
    addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights);
    Log.d(TAG, "adding regional weights");
    addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights);

    // This is so that things of common weight end up in non-random order
    // without having to do an SQL order-by.
    final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet());
    Log.d(TAG, "Sorting units...");
    Collections.sort(sortedUnits);
    Log.d(TAG, "Adding all sorted units...");

    final HashMap<String, String> fingerprints = loadFingerprints();

    db.beginTransaction();
    for (final String unitName : sortedUnits) {
        cv.put(UsageEntry._UNIT, unitName);
        cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName));

        final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName)
                : getFingerprint(unitName);

        fingerprints.put(unitName, fpr);
        cv.put(UsageEntry._FACTOR_FPRINT, fpr);
        db.insert(DB_USAGE_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

    context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null);

    // If we have the right permissons, save the fingerprints file to a JSON file
    // which can then be imported into the app to speed up initial fingerpint loading.
    if (context.checkCallingOrSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        final File externalStorage = Environment.getExternalStorageDirectory();
        final File fprintsOutput = new File(externalStorage, "units_fingerprints.json");
        final JSONObject jo = new JSONObject(fingerprints);
        try {
            final FileWriter fw = new FileWriter(fprintsOutput);
            fw.write(jo.toString(1));
            fw.close();
            Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath());

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "done!");
}

From source file:com.krawler.spring.crm.common.ImportRecordAdvisor.java

private void AfterSaveRecord(MethodInvocation mi, Object result) throws DataInvalidateException {
    Object arguments[] = mi.getArguments();
    String mode = (String) arguments[3];
    try {/*from  w w  w  .j a  v  a2 s .com*/
        HashMap<String, Object> requestParams = (HashMap<String, Object>) arguments[0];
        String companyid = requestParams.get("companyid").toString();
        String module = (String) arguments[3];
        if (mode.equalsIgnoreCase("lead")) {
            HashMap<String, Object> dataMap = (HashMap<String, Object>) arguments[1];
            String ownerid = dataMap.get("UsersByCreatedbyid").toString();
            String leadid = ((CrmLead) result).getLeadid();
            crmLeadDAOObj.setMainLeadOwner(new String[] { leadid }, ownerid);
            if (dataMap.containsKey("CrmProduct") && dataMap.get("CrmProduct") != null) {
                String productid = dataMap.get("CrmProduct").toString();
                crmLeadDAOObj.saveLeadProducts(new String[] { leadid }, productid.split(","));
            }
            JSONArray customfield = (JSONArray) arguments[7];
            if (customfield.length() > 0) {
                HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                customrequestParams.put("customarray", customfield);
                customrequestParams.put("modulename", Constants.Crm_Lead_modulename);
                customrequestParams.put("moduleprimarykey", Constants.Crm_Leadid);
                customrequestParams.put("modulerecid", leadid);
                customrequestParams.put("companyid", companyid);
                customrequestParams.put("customdataclasspath", Constants.Crm_lead_custom_data_classpath);
                //                    fieldManager.storeCustomFields(jcustomarray,"lead",true,id);
                KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                if (customDataresult.getEntityList().size() > 0) {
                    crmLeadDAOObj.setCustomData((CrmLead) result,
                            (CrmLeadCustomData) customDataresult.getEntityList().get(0));
                }
                //                    fieldManager.storeCustomFields(customfield,mode.toLowerCase(),true,leadid);
            }

            //Validate records
            //                crmCommonDAOObj.validaterecorsingledHB(module, leadid, companyid, hibernateTemplate.getSessionFactory().getCurrentSession());
        } else if (mode.equalsIgnoreCase("opportunity")) {
            HashMap<String, Object> dataMap = (HashMap<String, Object>) arguments[1];
            String ownerid = dataMap.get("UsersByCreatedbyid").toString();
            String oppid = ((CrmOpportunity) result).getOppid();
            crmOpportunityDAOObj.setMainOppOwner(new String[] { oppid }, ownerid);
            if (dataMap.containsKey("CrmProduct") && dataMap.get("CrmProduct") != null) {
                String productid = dataMap.get("CrmProduct").toString();
                crmOpportunityDAOObj.saveOpportunityProducts(new String[] { oppid }, productid.split(","));
            }
            JSONArray customfield = (JSONArray) arguments[7];
            if (customfield.length() > 0) {
                HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                customrequestParams.put("customarray", customfield);
                customrequestParams.put("modulename", Constants.Crm_Opportunity_modulename);
                customrequestParams.put("moduleprimarykey", Constants.Crm_Opportunityid);
                customrequestParams.put("modulerecid", oppid);
                customrequestParams.put("companyid", companyid);
                customrequestParams.put("customdataclasspath", Constants.Crm_opportunity_custom_data_classpath);
                KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                if (customDataresult.getEntityList().size() > 0) {
                    crmOpportunityDAOObj.setCustomData((CrmOpportunity) result,
                            (CrmOpportunityCustomData) customDataresult.getEntityList().get(0));
                }
            }

            //Validate records
            //                crmCommonDAOObj.validaterecorsingledHB(module, oppid, companyid, hibernateTemplate.getSessionFactory().getCurrentSession());
        } else if (mode.equalsIgnoreCase("account")) {
            HashMap<String, Object> dataMap = (HashMap<String, Object>) arguments[1];
            String ownerid = dataMap.get("UsersByCreatedbyid").toString();
            String accountid = ((CrmAccount) result).getAccountid();
            crmAccountDAOObj.setMainAccOwner(new String[] { accountid }, ownerid);
            if (dataMap.containsKey("CrmProduct") && dataMap.get("CrmProduct") != null) {
                String productid = dataMap.get("CrmProduct").toString();
                crmAccountDAOObj.saveAccountProducts(new String[] { accountid }, productid.split(","));
            }

            JSONArray customfield = (JSONArray) arguments[7];
            if (customfield.length() > 0) {
                HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                customrequestParams.put("customarray", customfield);
                customrequestParams.put("modulename", Constants.Crm_Account_modulename);
                customrequestParams.put("moduleprimarykey", Constants.Crm_Accountid);
                customrequestParams.put("modulerecid", accountid);
                customrequestParams.put("companyid", companyid);
                customrequestParams.put("customdataclasspath", Constants.Crm_account_custom_data_classpath);
                KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                if (customDataresult.getEntityList().size() > 0) {
                    crmAccountDAOObj.setCustomData((CrmAccount) result,
                            (CrmAccountCustomData) customDataresult.getEntityList().get(0));
                }
            }

            //Validate records
            //                crmCommonDAOObj.validaterecorsingledHB(module, accountid, companyid, hibernateTemplate.getSessionFactory().getCurrentSession());
        } else if (mode.equalsIgnoreCase("contact")) {
            HashMap<String, Object> dataMap = (HashMap<String, Object>) arguments[1];
            String ownerid = dataMap.get("UsersByCreatedbyid").toString();
            String contactid = ((CrmContact) result).getContactid();
            crmContactDAOObj.setMainContactOwner(new String[] { contactid }, ownerid);
            JSONArray customfield = (JSONArray) arguments[7];
            if (customfield.length() > 0) {
                HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                customrequestParams.put("customarray", customfield);
                customrequestParams.put("modulename", Constants.Crm_Contact_modulename);
                customrequestParams.put("moduleprimarykey", Constants.Crm_Contactid);
                customrequestParams.put("modulerecid", contactid);
                customrequestParams.put("companyid", companyid);
                customrequestParams.put("customdataclasspath", Constants.Crm_contact_custom_data_classpath);
                KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                if (customDataresult.getEntityList().size() > 0) {
                    crmContactDAOObj.setCustomData((CrmContact) result,
                            (CrmContactCustomData) customDataresult.getEntityList().get(0));
                }
            }

            //Validate records
            //                crmCommonDAOObj.validaterecorsingledHB(module, contactid, companyid, hibernateTemplate.getSessionFactory().getCurrentSession());
        } else if (mode.equalsIgnoreCase("Target")) {
            HashMap<String, Object> dataMap = (HashMap<String, Object>) arguments[1];
            TargetList targetList = (TargetList) arguments[6];

            String fname = "";
            if (dataMap.get("Firstname") != null) {
                fname = dataMap.get("Firstname").toString();
            }
            if (dataMap.get("Lastname") != null) {
                String lname = "";
                if (!StringUtil.isNullOrEmpty(dataMap.get("Lastname").toString())) {
                    lname = dataMap.get("Lastname").toString();
                }
                if (StringUtil.isNullOrEmpty(fname)) {
                    fname += lname;
                } else {
                    fname += " " + lname;
                }
            }
            crmTargetDAOObj.saveTargetListTargets(((TargetModule) result).getId(),
                    (String) dataMap.get("Email"), targetList, fname);

        }

    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw new DataInvalidateException("Failed to import records for " + mode + ": " + ex.getMessage());
    }
}

From source file:com.google.appengine.tools.mapreduce.ConfigurationTemplatePreprocessor.java

/**
 * Substitutes in the values in params for templated values. After this method
 * is called, any subsequent calls to this method for the same object result in
 * an {@link IllegalStateException}. To preprocess the template again,
 * create another {@code ConfigurationTemplatePreprocessor} from the source XML.
 *
 * @param params a map from key to value of all the template parameters
 * @return the document as an XML string with the template parameters filled
 * in/*from w  w w .j ava  2 s  . c  om*/
 * @throws MissingTemplateParameterException if any required parameter is
 * omitted
 * @throws IllegalStateException if this method has previously been called
 * on this object
 */
public String preprocess(Map<String, String> params) {
    HashMap<String, String> paramsCopy = new HashMap<String, String>(params);
    if (preprocessCalled) {
        throw new IllegalStateException("Preprocess can't be called twice for the same object");
    }
    preprocessCalled = true;

    for (Entry<String, Element> entry : nameToValueElement.entrySet()) {
        Element valueElem = entry.getValue();
        boolean isTemplateValue = valueElem.hasAttribute("template");
        if (paramsCopy.containsKey(entry.getKey()) && isTemplateValue) {
            // Modifies the map in place, but that's fine for our use.
            Text valueData = (Text) valueElem.getFirstChild();
            String newValue = paramsCopy.get(entry.getKey());
            if (valueData != null) {
                valueData.setData(newValue);
            } else {
                valueElem.appendChild(doc.createTextNode(newValue));
            }
            // Remove parameter, so we can tell if they gave us extras.
            paramsCopy.remove(entry.getKey());
        } else if (isTemplateValue) {
            String templateAttribute = valueElem.getAttribute("template");
            if ("required".equals(templateAttribute)) {
                throw new MissingTemplateParameterException(
                        "Couldn't find expected parameter " + entry.getKey());
            } else if ("optional".equals(templateAttribute)) {
                // The default value is the one already in the value text, so
                // leave it be. The one exception is if they self-closed the value tag,
                // so go ahead and add a Text child so Configuration doesn't barf.
                if (valueElem.getFirstChild() == null) {
                    valueElem.appendChild(doc.createTextNode(""));
                }
            } else {
                throw new IllegalArgumentException("Value " + templateAttribute + " is not a valid template "
                        + "attribute. Valid possibilities are: \"required\" or \"optional\".");
            }
            // Remove parameter, so we can tell if they gave us extras.
            paramsCopy.remove(entry.getKey());
        } else {
            throw new IllegalArgumentException(
                    "Configuration property " + entry.getKey() + " is not a template property");
        }

        // removeAttribute has no effect if the attributes don't exist
        valueElem.removeAttribute("template");
    }

    if (paramsCopy.size() > 0) {
        // TODO(user): Is there a good way to bubble up all bad parameters?
        throw new UnexpectedTemplateParameterException("Parameter " + paramsCopy.keySet().iterator().next()
                + " wasn't found in the configuration template.");
    }

    return getDocAsXmlString();
}

From source file:gov.nih.nci.cabig.caaers.web.admin.UserAjaxFacade.java

@SuppressWarnings("unchecked")
public List<UserAjaxableDomainObject> getResults(HashMap searchCriteriaMap) {

    List<UserAjaxableDomainObject> searchResults = new ArrayList<UserAjaxableDomainObject>();

    /*/*from  w  w  w  . ja v  a  2s.  c o  m*/
           String firstName = (String)searchCriteriaMap.get("firstName");
           String lastName = (String)searchCriteriaMap.get("lastName");
    */
    String name = (String) searchCriteriaMap.get("name");
    String userName = (String) searchCriteriaMap.get("userName");
    String personType = (String) searchCriteriaMap.get("personType");
    String personIdentifier = (String) searchCriteriaMap.get("personIdentifier");
    String organization = (String) searchCriteriaMap.get("organization");

    List<IndexEntry> permisionedOrgs = securityFacade
            .getAccessibleOrganizationIds(SecurityUtils.getUserLoginName());
    List<Integer> allowedOrgs = null;
    if (permisionedOrgs.size() > 0
            && !CaaersSecurityFacadeImpl.ALL_IDS_FABRICATED_ID.equals(permisionedOrgs.get(0).getEntityId())) {
        //Accsess to sites is limited so limit results too.
        allowedOrgs = new ArrayList<Integer>();
        for (IndexEntry idx : permisionedOrgs) {
            allowedOrgs.add(idx.getEntityId());
        }
        searchCriteriaMap.put("organizations", allowedOrgs);
    }

    //Only Organization provided
    if (StringUtils.isEmpty(name) && StringUtils.isEmpty(personIdentifier) && "Please Select".equals(personType)
            && StringUtils.isEmpty(userName) && !StringUtils.isEmpty(organization)) {
        searchResults = getResearchStaffTable(searchCriteriaMap);
        searchResults.addAll(getInvestigatorTable(searchCriteriaMap));
        return searchResults;
    }

    //Only Person Identifier provided
    if (StringUtils.isEmpty(name) && "Please Select".equals(personType) && StringUtils.isEmpty(userName)
            && StringUtils.isEmpty(organization) && !StringUtils.isEmpty(personIdentifier)) {
        searchResults = getResearchStaffTable(searchCriteriaMap);
        searchResults.addAll(getInvestigatorTable(searchCriteriaMap));
        return searchResults;
    }

    if ("ResearchStaff".equals(personType)) {
        return getResearchStaffTable(searchCriteriaMap);
    } else if ("Investigator".equals(personType)) {
        return getInvestigatorTable(searchCriteriaMap);
    } else {
        HashMap resultsMap = new HashMap<String, UserAjaxableDomainObject>();

        searchResults = getResearchStaffTable(searchCriteriaMap);
        searchResults.addAll(getInvestigatorTable(searchCriteriaMap));

        for (UserAjaxableDomainObject uado : searchResults) {
            if (StringUtils.isNotEmpty(uado.getUserName()) && !resultsMap.containsKey(uado.getUserName())) {
                resultsMap.put(uado.getUserName(), uado);
            }
        }

        List<UserAjaxableDomainObject> csmResults = getUserTable(searchCriteriaMap);
        for (UserAjaxableDomainObject uado : csmResults) {
            if (resultsMap.containsKey(uado.getUserName())) {
                //Do not add it to searchResults
            } else {
                searchResults.add(uado);
            }
        }

        return searchResults;
    }
}

From source file:com.nuxeo.intranet.jenkins.web.JenkinsJsonConverter.java

public List<Map<String, Serializable>> mergeData(List<Map<String, Serializable>> oldData,
        List<Map<String, Serializable>> newData) {
    // reset counters and merged data
    newFailingCount = 0;//  w w  w .ja va 2  s .  c o  m
    fixedCount = 0;
    unchangedCount = 0;
    mergedData = null;

    // gather up all old info, and use a map for easier reference
    HashMap<String, Map<String, Serializable>> res = new LinkedHashMap<String, Map<String, Serializable>>();
    if (oldData != null) {
        for (Map<String, Serializable> item : oldData) {
            res.put((String) item.get("job_id"), item);
        }
    }

    // add up new values and merge if already in the existing list
    if (newData != null) {
        for (Map<String, Serializable> item : newData) {
            String id = (String) item.get("job_id");
            String build_number = (String) item.get("build_number");
            if (res.containsKey(id)) {
                Map<String, Serializable> oldItem = res.get(id);
                String oldBuildNumber = String.valueOf(oldItem.get("build_number"));
                if (build_number != null && build_number.equals(oldBuildNumber)) {
                    // already the same job => update claimer and comment
                    // override claimer and comments
                    oldItem.put("claimer", item.get("claimer"));
                    oldItem.put("comment", item.get("comment"));
                    unchangedCount++;
                } else {
                    oldItem.put("updated_build_number", build_number);
                    String oldType = (String) oldItem.get("updated_type");
                    String newType = (String) item.get("type");
                    oldItem.put("updated_type", newType);
                    oldItem.put("updated_comment", item.get("comment"));
                    // only override claimer
                    oldItem.put("claimer", item.get("claimer"));
                    if ("SUCCESS".equals(newType) && !"SUCCESS".equals(oldType)) {
                        fixedCount++;
                    }
                }
                res.put(id, oldItem);
            } else {
                if (oldData != null && !oldData.isEmpty()) {
                    item.put("newly_failing", "true");
                }
                newFailingCount++;
                res.put(id, item);
            }
        }
    }

    unchangedCount = res.size() - (fixedCount + newFailingCount);

    mergedData = new ArrayList<Map<String, Serializable>>(res.values());
    return mergedData;
}

From source file:de.kbs.acavis.service.controller.CollectionManager.java

/**
 * Creates a co-authorship network using a set of publications by given publication-identifiers.
 * /* w w  w.  j a  v  a  2  s .com*/
 * @param publicationIdentifiers
 *          A set of publication-identifiers for building the network
 * @param integrationName
 *          Full package- and classname of the integration-provider to use
 * @return A co-authorship network in a suitable container
 * @throws InvalidIntegrationException
 *           If the given integration-provider is invalid
 * @throws UnimplementedFeatureException
 *           If the given provider doesn't support the necessary data-requests for retrieving publications and their authors
 * @throws IntegrationUnavailableException
 *           If the integration-provider is temporarily or permanently not available
 * @throws IdentifierException
 *           If at least one of the given identifiers couldn't be used to retrieve a publication from the given integration-provider
 */
public CoAuthorshipNetwork publicationsCoAuthors(Collection<PublicationIdentifier> publicationIdentifiers,
        String integrationName) throws InvalidIntegrationException, UnimplementedFeatureException,
        IntegrationUnavailableException, IdentifierException {
    PublicationProvider provider = IntegrationProviderFactory.createPublicationProvider(integrationName);

    CoAuthorshipNetwork network = new CoAuthorshipNetwork();
    HashMap<AuthorIdentifier, AuthorNode> nodeCache = new HashMap<AuthorIdentifier, AuthorNode>();

    Map<PublicationIdentifier, List<AuthorData>> publicationAuthors = provider
            .getPublicationsAuthors(publicationIdentifiers);

    // Add all authors first
    int id = 0;
    for (List<AuthorData> authors : publicationAuthors.values()) {
        for (AuthorData author : authors) {
            if (!nodeCache.containsKey(author.getId())) {
                AuthorNode authorNode = new AuthorNode(id++, author.getId(), author.getName());

                nodeCache.put(author.getId(), authorNode);
                network.addNode(authorNode);
            }
        }
    }

    // Add links for each publication
    id = 0;
    for (List<AuthorData> authors : publicationAuthors.values()) {
        // Nested loop for cross-product of publications' authors
        for (AuthorData author1 : authors) {
            for (AuthorData author2 : authors) {
                AuthorNode authorNode1 = nodeCache.get(author1.getId());
                AuthorNode authorNode2 = nodeCache.get(author2.getId());

                if (authorNode1 == null || authorNode2 == null)
                    continue;

                network.addLink(new CoAuthorshipLink(id++), authorNode1, authorNode2);
            }
        }
    }

    // The metrics and clustering
    network.calculateEdgeBetweennessClustering(3);
    // TODO pagerank and other metrics

    return network;
}