Example usage for java.util HashMap entrySet

List of usage examples for java.util HashMap entrySet

Introduction

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

Prototype

Set entrySet

To view the source code for java.util HashMap entrySet.

Click Source Link

Document

Holds cached entrySet().

Usage

From source file:com.hanuor.sapphire.utils.intentation.IntentationPrime.java

public Intent jsonToINTENT(String JSONString) throws JSONException {

    JSONObject jsonObject = new JSONObject(JSONString.toString());
    String toArray = jsonObject.get("intentExtras").toString();
    String contextName = jsonObject.get("context").toString();
    String className = jsonObject.get("className").toString();
    Log.d("Insass", className.toString());

    Intent setIntent = new Intent();
    setIntent.setClassName(contextName, className);
    HashMap<String, String> extrasHash = new HashMap<String, String>();
    JSONObject issueObj = new JSONObject(toArray);
    for (int i = 0; i < issueObj.length(); i++) {
        extrasHash.put(issueObj.names().getString(i), issueObj.get(issueObj.names().getString(i)).toString());
    }/*w  ww.j a v  a 2s .co  m*/
    Iterator it = extrasHash.entrySet().iterator();
    while (it.hasNext()) {
        //add conditions  and checks here

        Map.Entry pair = (Map.Entry) it.next();
        String currentKey = (String) pair.getKey();
        Log.d("HAHA", "" + currentKey);
        String[] getValuethroughSplit = pair.getValue().toString().split(LibraryDatabase.JSONSEPERATOR);
        String dataType = getValuethroughSplit[0];
        String value = (String) getValuethroughSplit[2];
        Log.d("Insamareen", getValuethroughSplit.length + " " + dataType + " " + value.toString());
        switch (dataType) {
        case "String":
            setIntent.putExtra(currentKey, (String) value);
            break;
        case "String[]":
            String comp1 = value.substring(1, value.length() - 1);
            String[] comp2 = comp1.split(",");
            setIntent.putExtra(currentKey, comp2);
            break;
        case "Integer":
            setIntent.putExtra(currentKey, Integer.parseInt(value));
            break;
        case "Double":

            setIntent.putExtra(currentKey, Double.parseDouble(value));

            break;
        case "double[]":
            String compDouble1 = value.substring(1, value.length() - 1);
            String[] compDoub2 = compDouble1.split(",");
            double[] db = new double[compDoub2.length];
            for (int i = 0; i < compDoub2.length; i++) {
                db[i] = Double.parseDouble(compDoub2[i]);
            }
            setIntent.putExtra(currentKey, db);
            break;
        case "int[]":
            String compInt1 = value.substring(1, value.length() - 1);
            String[] compInt2 = compInt1.split(",");
            int[] intVal = new int[compInt2.length];
            for (int i = 0; i < compInt2.length; i++) {
                intVal[i] = Integer.parseInt(compInt2[i]);
            }
            Log.d("Hankey", intVal.toString());
            setIntent.putExtra(currentKey, intVal);

            break;
        case "Boolean":
            setIntent.putExtra(currentKey, Boolean.valueOf(value));

            break;
        case "boolean[]":
            String compB1 = value.substring(1, value.length() - 1);
            String[] compB2 = compB1.split(",");
            boolean[] BVal = new boolean[compB2.length];
            for (int i = 0; i < compB2.length; i++) {
                BVal[i] = Boolean.parseBoolean(compB2[i]);
            }
            setIntent.putExtra(currentKey, value);

            break;
        case "Char":
            setIntent.putExtra(currentKey, value);

            break;
        case "char[]":

            String ch1 = value.substring(1, value.length() - 1);
            String[] ch2 = ch1.split(",");
            String newS = null;
            for (int i = 0; i < ch2.length; i++) {
                newS = newS + ch2[i];
            }
            setIntent.putExtra(currentKey, newS.toCharArray());

            break;
        case "CharSequence":
            setIntent.putExtra(currentKey, (CharSequence) value);

            break;
        case "Charsequence[]":
            setIntent.putExtra(currentKey, value.toString());

            break;
        case "Byte":
            setIntent.putExtra(currentKey, Byte.valueOf(value));

            break;
        case "byte[]":
            String by = value.substring(1, value.length() - 1);
            String[] by2 = by.split(",");
            byte[] by3 = new byte[by2.length];
            for (int i = 0; i < by2.length; i++) {
                by3[i] = Byte.parseByte(by2[i]);
            }
            setIntent.putExtra(currentKey, by3);

            break;
        case "Float":
            setIntent.putExtra(currentKey, Float.valueOf(value));

            break;
        case "float[]":
            String fl = value.substring(1, value.length() - 1);
            String[] fl2 = fl.split(",");
            float[] fl3 = new float[fl2.length];
            for (int i = 0; i < fl2.length; i++) {
                fl3[i] = Float.parseFloat(fl2[i]);
            }
            setIntent.putExtra(currentKey, fl3);

            break;
        case "Short":
            setIntent.putExtra(currentKey, Short.valueOf(value));

            break;
        case "short[]":
            String sh = value.substring(1, value.length() - 1);
            String[] sh2 = sh.split(",");
            short[] sh3 = new short[sh2.length];
            for (int i = 0; i < sh2.length; i++) {
                sh3[i] = Short.parseShort(sh2[i]);
            }
            setIntent.putExtra(currentKey, sh3);

            break;
        case "Long":
            setIntent.putExtra(currentKey, Long.valueOf(value));

            break;
        case "long[]":
            String ll = value.substring(1, value.length() - 1);
            String[] ll2 = ll.split(",");
            long[] ll3 = new long[ll2.length];
            for (int i = 0; i < ll2.length; i++) {
                ll3[i] = Long.parseLong(ll2[i]);
            }
            setIntent.putExtra(currentKey, ll3);

            break;

        case "ArrayListString":
            Log.d("Hankey", currentKey + " ");
            String arrL = value.substring(1, value.length() - 1);
            String[] arrl2 = arrL.split(",");
            ArrayList<String> arrStr = new ArrayList<String>();
            for (int i = 0; i < arrl2.length; i++) {
                arrStr.add(arrl2[i]);
            }
            setIntent.putStringArrayListExtra(currentKey, arrStr);

            break;
        case "ArrayListInteger":
            String arL = value.substring(1, value.length() - 1);
            String[] arl2 = arL.split(",");
            ArrayList<Integer> arrInt = new ArrayList<Integer>();
            for (int i = 0; i < arl2.length; i++) {
                arrInt.add(Integer.parseInt(arl2[i]));
            }

            setIntent.putIntegerArrayListExtra(currentKey, arrInt);

            break;
        default:
            // whatever
        }
    }
    return setIntent;
}

From source file:com.jvoid.customers.customer.service.CustomerMasterService.java

public int addCustomer(JSONObject jObj) {
    int cid = 0;//w w w  .  j a v  a  2s.c o m
    String emailId = null;
    Customer customer = new Customer();
    customer.setCreatedAt(Utilities.getCurrentDateTime());
    customer.setUpdatedAt(Utilities.getCurrentDateTime());
    try {
        customer.setCustomerGroupId(jObj.getInt("customerGroup"));
        emailId = jObj.getString("email");
        System.out.println("EMAIL ID:" + emailId);
        customer.setEmail(emailId);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (null == emailId) {
        return cid;
    } else if (isEmailAlreadyExists(emailId)) {
        return cid;
    }
    customerService.addcustomer(customer);
    cid = customer.getId();
    System.out.println("customer==>" + customer.toString());

    List<Entities> listAttributes = this.entitiesService.listAttributes();
    HashMap<Integer, String> attrs = getAttributesList(listAttributes, "Customer");
    System.out.println("attrs==>" + attrs.toString());

    for (Entry<Integer, String> entry : attrs.entrySet()) {
        Integer attrId = entry.getKey();
        String attrName = entry.getValue();

        String attrValue = null;
        try {
            attrValue = jObj.getString(attrName);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null != attrValue) {

            CustomerEntityValues custAttrValue = new CustomerEntityValues();
            custAttrValue.setCustomerId(cid);
            custAttrValue.setLanguage("enUS");
            custAttrValue.setAttributeId(attrId);
            custAttrValue.setValue(attrValue);
            customerEntityValuesService.addCustomerAttributeValues(custAttrValue);
            System.out.println("custAttrValue-->" + custAttrValue.toString());
        }

    }

    return cid;

    /* //Rest call
    final String SERVER_URI = "http://localhost:8080/jvoidattributes/listCustomerAttriburtes";
    RestTemplate restTemplate = new RestTemplate();
            
    String returnString = restTemplate.getForObject(SERVER_URI, String.class);        
      JSONObject returnJsonObj = null;
    try {
       returnJsonObj = new JSONObject(returnString);
    } catch (JSONException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }
            
      System.out.println("returnJsonObj=>"+returnJsonObj);
              
      JSONArray arr = null;
      try {
       arr = returnJsonObj.getJSONArray("Attributes");
    } catch (JSONException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }
              
      for (int i=0; i<arr.length(); i++) {
        try {
    String attrValue = arr.getJSONObject(i).getString("code");
    Integer attrId = Integer.parseInt(arr.getJSONObject(i).getString("id"));
    System.out.println("id = "+attrId+"   code = "+attrValue);
            
    CustomerAttributeValues custAttrValue = new CustomerAttributeValues();
     custAttrValue.setCustomerId(customer.getId());//get it from customer table
     custAttrValue.setLanguage("enUS");
     custAttrValue.setAttributeId(attrId);
     custAttrValue.setValue(customerMaster.toAttributedHashMap().get(attrValue));
     customerAttributeValuesService.addCustomerAttributeValues(custAttrValue);
     System.out.println("custAttrValue-->"+custAttrValue.toString());
       } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
       }
    }
    */

}

From source file:br.unicamp.cst.learning.QLearning.java

/**
* Returns the maximum Q value for sl. /*from  www .java  2  s  . c  o  m*/
* @param sl
* @return Q Value
*/
public double maxQsl(String sl) {
    double maxQinSl = 0;
    String maxAl = "";
    double val = 0;
    if (this.Q.get(sl) != null) {
        HashMap<String, Double> tempSl = this.Q.get(sl);
        ArrayList<String> tempA = new ArrayList<String>();
        tempA.addAll(this.actionsList);

        // Finds out the action with maximum value for sl
        Iterator<Entry<String, Double>> it = tempSl.entrySet().iterator();

        while (it.hasNext()) {
            Entry<String, Double> pairs = it.next();
            val = pairs.getValue();
            tempA.remove(pairs.getKey());
            if (val > maxQinSl) {
                maxAl = pairs.getKey();
                maxQinSl = val;
            }
        }
        if (!tempA.isEmpty() && maxQinSl < 0) {
            maxQinSl = 0;
        } //Assigning 0 to unknown state/action pair
    }
    return maxQinSl;
}

From source file:com.mawujun.util.ObjectUtils.java

/**
 * Find the most frequently occurring item.
 * /*from w w  w  .j  a  v  a2  s .c om*/
 * @param <T> type of values processed by this method
 * @param items to check
 * @return most populous T, {@code null} if non-unique or no items supplied
 * @since 3.0.1
 */
public static <T> T mode(T... items) {
    if (ArrayUtils.isNotEmpty(items)) {
        HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(items.length);
        for (T t : items) {
            MutableInt count = occurrences.get(t);
            if (count == null) {
                occurrences.put(t, new MutableInt(1));
            } else {
                count.increment();
            }
        }
        T result = null;
        int max = 0;
        for (Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
            int cmp = e.getValue().intValue();
            if (cmp == max) {
                result = null;
            } else if (cmp > max) {
                max = cmp;
                result = e.getKey();
            }
        }
        return result;
    }
    return null;
}

From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java

/**
 * Tests the ability to auto-cancel the requests when the StorageReadManager is closed.
 *//*from  www  . jav  a  2s  .c o m*/
@Test
public void testAutoCancelRequests() {
    final int readCount = 100;
    TestStorage storage = new TestStorage();
    storage.readImplementation = CompletableFuture::new; // Just return a Future which we will never complete - simulates a high latency read.
    @Cleanup
    StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    HashMap<StorageReadManager.Request, CompletableFuture<StorageReadManager.Result>> requestCompletions = new HashMap<>();

    for (int i = 0; i < readCount; i++) {
        CompletableFuture<StorageReadManager.Result> requestCompletion = new CompletableFuture<>();
        StorageReadManager.Request r = new StorageReadManager.Request(i * 10, 9, requestCompletion::complete,
                requestCompletion::completeExceptionally, TIMEOUT);
        reader.execute(r);
        requestCompletions.put(r, requestCompletion);
    }

    // Verify the reads aren't failed yet.
    for (val entry : requestCompletions.entrySet()) {
        Assert.assertFalse("Request is unexpectedly completed before close for request " + entry.getKey(),
                entry.getValue().isDone());
    }

    // Close the reader and verify the reads have all been cancelled.
    reader.close();
    for (val entry : requestCompletions.entrySet()) {
        Assert.assertTrue("Request is not completed with exception after close for request " + entry.getKey(),
                entry.getValue().isCompletedExceptionally());
        AssertExtensions.assertThrows(
                "Request was not failed with a CancellationException after close for request " + entry.getKey(),
                entry.getValue()::join, ex -> ex instanceof CancellationException);
    }
}

From source file:net.opentsdb.tsd.HttpSampleSerializer.java

/**
 * Parses a single Tree object/*w  ww. j  av  a2s .c o  m*/
 * <b>Note:</b> Incoming data is a hash map of strings instead of directly
 * deserializing to a tree. We do it this way because we don't want users
 * messing with the timestamp fields.
 * @return A parsed Tree
 * @throws JSONException if parsing failed
 * @throws BadRequestException if the content was missing or parsing failed
 */
public Tree parseTreeV1() {
    final String json = query.getContent();
    if (json == null || json.isEmpty()) {
        throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, "Missing message content",
                "Supply valid JSON formatted data in the body of your request");
    }
    try {
        final HashMap<String, String> properties = JSON.parseToObject(json, TR_HASH_MAP);

        final Tree tree = new Tree();
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            // skip nulls, empty is fine, but nulls are not welcome here
            if (entry.getValue() == null) {
                continue;
            }

            if (entry.getKey().toLowerCase().equals("treeid")) {
                tree.setTreeId(Integer.parseInt(entry.getValue()));
            } else if (entry.getKey().toLowerCase().equals("name")) {
                tree.setName(entry.getValue());
            } else if (entry.getKey().toLowerCase().equals("description")) {
                tree.setDescription(entry.getValue());
            } else if (entry.getKey().toLowerCase().equals("notes")) {
                tree.setNotes(entry.getValue());
            } else if (entry.getKey().toLowerCase().equals("enabled")) {
                if (entry.getValue().toLowerCase().equals("true")) {
                    tree.setEnabled(true);
                } else {
                    tree.setEnabled(false);
                }
            } else if (entry.getKey().toLowerCase().equals("strictMatch")) {
                if (entry.getValue().toLowerCase().equals("true")) {
                    tree.setStrictMatch(true);
                } else {
                    tree.setStrictMatch(false);
                }
            }
        }
        return tree;
    } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'tree' value");
    } catch (IllegalArgumentException iae) {
        throw new BadRequestException("Unable to parse the given JSON", iae);
    }
}

From source file:com.apelon.akcds.loinc.LoincToEConcepts.java

private void processDataLine(String[] fields) throws ParseException, IOException, TerminologyException {
    Integer index = fieldMap_.get("DT_LAST_CH");
    if (index == null) {
        index = fieldMap_.get("DATE_LAST_CHANGED"); // They changed this in 2.38 release
    }//from w ww.j  a v  a 2s .c  o  m
    String lastChanged = fields[index];
    long time = (StringUtils.isBlank(lastChanged) ? conceptUtility_.defaultTime_
            : sdf_.parse(lastChanged).getTime());

    UUID statusUUID = mapStatus(fields[fieldMap_.get("STATUS")]);

    String code = fields[fieldMap_.get("LOINC_NUM")];

    EConcept concept = conceptUtility_.createConcept(buildUUID(code), time, statusUUID);
    ArrayList<ValuePropertyPair> descriptions = new ArrayList<>();

    for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
        if (fields[fieldIndex] != null && fields[fieldIndex].length() > 0) {
            PropertyType pt = propertyToPropertyType_.get(fieldMapInverse_.get(fieldIndex));
            if (pt == null) {
                ConsoleUtil.printErrorln("ERROR: No property type mapping for the property "
                        + fieldMapInverse_.get(fieldIndex) + ":" + fields[fieldIndex]);
                continue;
            }

            Property p = pt.getProperty(fieldMapInverse_.get(fieldIndex));

            if (pt instanceof PT_Annotations) {
                if ((p.getSourcePropertyNameFSN().equals("COMMON_TEST_RANK")
                        || p.getSourcePropertyNameFSN().equals("COMMON_ORDER_RANK")
                        || p.getSourcePropertyNameFSN().equals("COMMON_SI_TEST_RANK"))
                        && fields[fieldIndex].equals("0")) {
                    continue; //Skip attributes of these types when the value is 0
                } else if (p.getSourcePropertyNameFSN().equals("RELATEDNAMES2")
                        || p.getSourcePropertyNameFSN().equals("RELAT_NMS")) {
                    String[] values = fields[fieldIndex].split(";");
                    TreeSet<String> uniqueValues = new TreeSet<>();
                    for (String s : values) {
                        s = s.trim();
                        if (s.length() > 0) {
                            uniqueValues.add(s);
                        }
                    }
                    for (String s : uniqueValues) {
                        conceptUtility_.addStringAnnotation(concept, s, p.getUUID(), p.isDisabled());
                    }
                } else {
                    conceptUtility_.addStringAnnotation(concept, fields[fieldIndex], p.getUUID(),
                            p.isDisabled());
                }
            } else if (pt instanceof PT_Descriptions) {
                //Gather for later
                descriptions.add(new ValuePropertyPair(fields[fieldIndex], p));
            } else if (pt instanceof PT_IDs) {
                conceptUtility_.addAdditionalIds(concept, fields[fieldIndex], p.getUUID(), p.isDisabled());
            } else if (pt instanceof PT_SkipAxis) {
                // See if this class object exists yet.
                UUID potential = ConverterUUID
                        .createNamespaceUUIDFromString(pt_SkipAxis_.getPropertyTypeDescription() + ":"
                                + fieldMapInverse_.get(fieldIndex) + ":" + fields[fieldIndex], true);

                EConcept axisConcept = concepts_.get(potential);
                if (axisConcept == null) {
                    axisConcept = conceptUtility_.createConcept(potential, fields[fieldIndex]);
                    conceptUtility_.addRelationship(axisConcept,
                            pt_SkipAxis_.getProperty(fieldMapInverse_.get(fieldIndex)).getUUID());
                    concepts_.put(axisConcept.primordialUuid, axisConcept);
                }
                // We changed these from attributes to relations
                // conceptUtility_.addAnnotation(concept, axisConcept, pt_SkipAxis_.getPropertyUUID(fieldMapInverse_.get(fieldIndex)));
                String relTypeName = "Has_" + fieldMapInverse_.get(fieldIndex);
                PropertyType relType = propertyToPropertyType_.get(relTypeName);
                conceptUtility_.addRelationship(concept, axisConcept.getPrimordialUuid(),
                        relType.getProperty(relTypeName).getUUID(), null);
            } else if (pt instanceof PT_SkipClass) {
                // See if this class object exists yet.
                UUID potential = ConverterUUID
                        .createNamespaceUUIDFromString(pt_SkipClass_.getPropertyTypeDescription() + ":"
                                + fieldMapInverse_.get(fieldIndex) + ":" + fields[fieldIndex], true);

                EConcept classConcept = concepts_.get(potential);
                if (classConcept == null) {
                    classConcept = conceptUtility_.createConcept(potential,
                            classMapping_.getMatchValue(fields[fieldIndex]));
                    if (classMapping_.hasMatch(fields[fieldIndex])) {
                        conceptUtility_
                                .addAdditionalIds(
                                        classConcept, fields[fieldIndex], propertyToPropertyType_
                                                .get("ABBREVIATION").getProperty("ABBREVIATION").getUUID(),
                                        false);
                    }
                    conceptUtility_.addRelationship(classConcept,
                            pt_SkipClass_.getProperty(fieldMapInverse_.get(fieldIndex)).getUUID());
                    concepts_.put(classConcept.primordialUuid, classConcept);
                }
                // We changed these from attributes to relations
                // conceptUtility_.addAnnotation(concept, classConcept, pt_SkipClass_.getPropertyUUID(fieldMapInverse_.get(fieldIndex)));
                String relTypeName = "Has_" + fieldMapInverse_.get(fieldIndex);
                PropertyType relType = propertyToPropertyType_.get(relTypeName);
                conceptUtility_.addRelationship(concept, classConcept.getPrimordialUuid(),
                        relType.getProperty(relTypeName).getUUID(), null);
            } else if (pt instanceof PT_Relations) {
                conceptUtility_.addRelationship(concept, buildUUID(fields[fieldIndex]),
                        pt.getProperty(fieldMapInverse_.get(fieldIndex)), null);
            } else if (pt instanceof PT_SkipOther) {
                conceptUtility_.getLoadStats().addSkippedProperty();
            } else {
                ConsoleUtil.printErrorln("oops - unexpected property type: " + pt);
            }
        }
    }

    //MAP_TO moved to a different file in 2.42.
    HashMap<String, String> mappings = mapToData.get(code);
    if (mappings != null) {
        for (Entry<String, String> mapping : mappings.entrySet()) {
            String target = mapping.getKey();
            String comment = mapping.getValue();
            TkRelationship r = conceptUtility_.addRelationship(concept, buildUUID(target),
                    propertyToPropertyType_.get("MAP_TO").getProperty("MAP_TO"), null);
            if (comment != null && comment.length() > 0) {
                conceptUtility_.addStringAnnotation(r, comment,
                        propertyToPropertyType_.get("COMMENT").getProperty("COMMENT").getUUID(), false);
            }
        }
    }

    //Now add all the descriptions
    if (descriptions.size() == 0) {
        if ("DEL".equals(fields[fieldMap_.get("CHNG_TYPE")])) {
            //They put a bunch of these in 2.44... leaving out most of the important info... just makes a mess.  Don't load them.
            skippedDeletedItems++;
            return;
        } else {
            ConsoleUtil.printErrorln("ERROR: no name for " + code);
            conceptUtility_.addFullySpecifiedName(concept, code);
        }
    } else {
        conceptUtility_.addDescriptions(concept, descriptions);
    }

    EConcept current = concepts_.put(concept.primordialUuid, concept);
    if (current != null) {
        ConsoleUtil.printErrorln("Duplicate LOINC code (LOINC_NUM):" + code);
    }
}

From source file:com.appeligo.epg.EpgIndexer.java

private void processPrograms(List<String> ids, Date modified) {
    int count = 0;
    int schedulesAdded = 0;
    LuceneIndexer indexer = LuceneIndexer.getInstance(programIndex);
    LuceneIndexer compositeIndexer = LuceneIndexer.getCompositeInstance(compositeIndex);
    while (count < ids.size()) {
        int subsetSize = (ids.size() < 100 ? ids.size() : 100);
        if (count % 1000 == 0) {
            log.info("Index programs into the Lucene Index. Current have processed " + count
                    + " programs out of " + ids.size());
        }// w  w  w .j  a va2 s  .c om
        int endIndex = (count + subsetSize > ids.size() ? ids.size() : count + subsetSize);
        List<String> subset = ids.subList(count, endIndex);
        count += subsetSize;
        HashMap<String, List<ScheduledProgram>> schedules = new HashMap<String, List<ScheduledProgram>>();
        ScheduledProgram[] programs = epg.getNextShowingPrograms(subset);
        for (ScheduledProgram program : programs) {
            if (program != null) {
                List<ScheduledProgram> schedule = schedules.get(program.getProgramId());
                if (schedule == null) {
                    schedule = new ArrayList<ScheduledProgram>();
                    schedules.put(program.getProgramId(), schedule);
                }
                schedule.add(program);
                schedulesAdded++;
            }
        }
        for (Entry<String, List<ScheduledProgram>> entry : schedules.entrySet()) {
            indexer.updateProgram(entry.getKey(), entry.getValue(), modified);
            compositeIndexer.updateCompositeProgram(entry.getKey(), entry.getValue(), modified);
        }
    }
    //Force an optimization after this large action.
    indexer.addAction(new OptimizeAction());
    compositeIndexer.addAction(new OptimizeAction());
    log.debug("added " + schedulesAdded + " schedules across the lineups.");
}

From source file:com.radicaldynamic.groupinform.services.DatabaseService.java

private void removePlaceholders(HashMap<String, JSONObject> placeholders) {
    final String tt = t + "removePlaceholders(): ";

    for (Map.Entry<String, JSONObject> entry : placeholders.entrySet()) {
        if (entry.getValue().optString("createdBy", null) == null
                || entry.getValue().optString("dateCreated", null) == null) {
            // Remove old style (unowned) placeholders immediately
            try {
                getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
                if (Collect.Log.VERBOSE)
                    Log.v(Collect.LOGTAG, tt + "removed old-style placeholder " + entry.getKey());
            } catch (Exception e) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, tt + "unable to remove old-style placeholder");
                e.printStackTrace();//ww w  .  j a  v  a2s.  c o m
            }
        } else if (entry.getValue().optString("createdBy")
                .equals(Collect.getInstance().getInformOnlineState().getDeviceId())) {
            // Remove placeholders owned by me immediately
            try {
                getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
                if (Collect.Log.VERBOSE)
                    Log.v(Collect.LOGTAG, tt + "removed my placeholder " + entry.getKey());
            } catch (Exception e) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, tt + "unable to remove my placeholder");
                e.printStackTrace();
            }
        } else {
            // Remove placeholders owned by other people if they are stale (older than a day)
            SimpleDateFormat sdf = new SimpleDateFormat(Generic.DATETIME);
            Calendar calendar = Calendar.getInstance();

            try {
                calendar.setTime(sdf.parse(entry.getValue().optString("dateCreated")));

                if (calendar.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() > TIME_24_HOURS) {
                    try {
                        getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
                        if (Collect.Log.VERBOSE)
                            Log.v(Collect.LOGTAG, tt + "removed stale placeholder " + entry.getKey());
                    } catch (Exception e) {
                        if (Collect.Log.ERROR)
                            Log.e(Collect.LOGTAG, tt + "unable to remove stale placeholder");
                        e.printStackTrace();
                    }
                }
            } catch (ParseException e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, tt + "unable to parse dateCreated: " + e1.toString());
                e1.printStackTrace();
            }
        }
    }
}