Example usage for java.util TreeMap lastEntry

List of usage examples for java.util TreeMap lastEntry

Introduction

In this page you can find the example usage for java.util TreeMap lastEntry.

Prototype

public Map.Entry<K, V> lastEntry() 

Source Link

Usage

From source file:edu.utexas.cs.tactex.tariffoptimization.TariffOptimizerBinaryOneShot.java

private TreeMap<Double, TariffSpecification> binarySearchOptimize(List<TariffSpecification> suggestedSpecs,
        HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>> tariffSubscriptions,
        List<TariffSpecification> competingTariffs, CostCurvesPredictor costCurvesPredictor,
        int currentTimeslot, Broker me,
        HashMap<CustomerInfo, HashMap<TariffSpecification, ShiftedEnergyData>> customer2ShiftedEnergy,
        HashMap<CustomerInfo, ArrayRealVector> customer2NonShiftedEnergy,
        HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> customer2RelevantTariffCharges) {

    TreeMap<Double, TariffSpecification> result = new TreeMap<Double, TariffSpecification>();

    // a value of null means no-op
    ArrayList<TariffSpecification> consideredTariffActions = new ArrayList<TariffSpecification>();
    consideredTariffActions.add(null);/*w  w w .j  a  va 2  s. c  om*/
    TreeMap<Double, TariffSpecification> sortedTariffs = utilityEstimator.estimateUtilities(
            consideredTariffActions, tariffSubscriptions, competingTariffs, customer2RelevantTariffCharges,
            customer2ShiftedEnergy, customer2NonShiftedEnergy, marketPredictionManager, costCurvesPredictor,
            currentTimeslot, me);
    result.putAll(sortedTariffs);

    // here do the binary search
    //
    // initialize with edges and middle
    TreeMap<Double, Integer> utilToIndex = new TreeMap<Double, Integer>();
    int numTariffs = suggestedSpecs.size();
    int[] initialIndexes = { 0, numTariffs / 2, numTariffs - 1 };
    for (int index : initialIndexes) {
        evaluateAndRecord(index, utilToIndex, result, suggestedSpecs, consideredTariffActions,
                tariffSubscriptions, competingTariffs, costCurvesPredictor, currentTimeslot, me,
                customer2ShiftedEnergy, customer2NonShiftedEnergy, customer2RelevantTariffCharges);
    }
    int bestIndex = utilToIndex.lastEntry().getValue();
    int secondBestIndex = utilToIndex.lowerEntry(utilToIndex.lastKey()).getValue();
    //
    // binary search
    while (Math.abs(secondBestIndex - bestIndex) >= 2) {
        //log.info("evaluating, bestIndex=" + bestIndex + ", secondBestIndex=" + secondBestIndex);
        int midIndex = (secondBestIndex + bestIndex) / 2;
        evaluateAndRecord(midIndex, utilToIndex, result, suggestedSpecs, consideredTariffActions,
                tariffSubscriptions, competingTariffs, costCurvesPredictor, currentTimeslot, me,
                customer2ShiftedEnergy, customer2NonShiftedEnergy, customer2RelevantTariffCharges);
        bestIndex = utilToIndex.lastEntry().getValue();
        secondBestIndex = utilToIndex.lowerEntry(utilToIndex.lastKey()).getValue();

        // TODO: handling a non-convex case (how come happens?)
        if (midIndex != bestIndex && midIndex != secondBestIndex) {
            log.warn("non-convex utility values found during binary search. breaking...");
            break;
        }
    }
    //log.info("evaluating, bestIndex=" + bestIndex + ", secondBestIndex=" + secondBestIndex);

    return result;
}

From source file:org.apache.archiva.rest.services.DefaultSearchService.java

@Override
public Response redirectToArtifactFile(String repositoryId, String groupId, String artifactId, String version,
        String packaging, String classifier) throws ArchivaRestServiceException {
    try {/*from   ww  w .j av  a2  s.c  o m*/
        // validate query

        if (StringUtils.isEmpty(groupId)) {
            return Response.status(new Response.StatusType() {
                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "groupId mandatory";
                }
            }).build();
        }

        if (StringUtils.isEmpty(version)) {
            return Response.status(new Response.StatusType() {
                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "version mandatory";
                }
            }).build();
        }

        if (StringUtils.isEmpty(artifactId)) {
            return Response.status(new Response.StatusType() {
                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "artifactId mandatory";
                }
            }).build();
        }

        SearchFields searchField = new SearchFields();
        searchField.setGroupId(groupId);
        searchField.setArtifactId(artifactId);
        searchField.setPackaging(StringUtils.isBlank(packaging) ? "jar" : packaging);
        if (!StringUtils.equals(version, LATEST_KEYWORD)) {
            searchField.setVersion(version);
        }
        searchField.setClassifier(classifier);
        List<String> userRepos = getObservablesRepoIds().getStrings();
        searchField
                .setRepositories(StringUtils.isEmpty(repositoryId) ? userRepos : Arrays.asList(repositoryId));
        searchField.setExactSearch(true);
        SearchResults searchResults = repositorySearch.search(getPrincipal(), searchField, null);
        List<Artifact> artifacts = getArtifacts(searchResults);

        if (artifacts.isEmpty()) {
            return Response.status(new Response.StatusType() {
                @Override
                public int getStatusCode() {
                    return Response.Status.NO_CONTENT.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.NO_CONTENT.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "your query doesn't return any artifact";
                }
            }).build();
        }

        // TODO improve that with querying lucene with null value for classifier
        // so simple loop and retain only artifact with null classifier
        if (classifier == null) {
            List<Artifact> filteredArtifacts = new ArrayList<>(artifacts.size());
            for (Artifact artifact : artifacts) {
                if (artifact.getClassifier() == null) {
                    filteredArtifacts.add(artifact);
                }
            }

            artifacts = filteredArtifacts;
        }

        // TODO return json result of the query ?
        if (artifacts.size() > 1 && !StringUtils.equals(version, LATEST_KEYWORD)) {
            return Response.status(new Response.StatusType() {
                @Override
                public int getStatusCode() {
                    return Response.Status.BAD_REQUEST.getStatusCode();
                }

                @Override
                public Response.Status.Family getFamily() {
                    return Response.Status.BAD_REQUEST.getFamily();
                }

                @Override
                public String getReasonPhrase() {
                    return "your query return more than one artifact";
                }
            }).build();
        }

        // version is LATEST so we have to find the latest one from the result
        if (artifacts.size() > 1 && StringUtils.equals(version, LATEST_KEYWORD)) {
            TreeMap<String, Artifact> artifactPerVersion = new TreeMap<>(VersionComparator.getInstance());

            for (Artifact artifact : artifacts) {
                artifactPerVersion.put(artifact.getVersion(), artifact);
            }

            return Response.temporaryRedirect(new URI(artifactPerVersion.lastEntry().getValue().getUrl()))
                    .build();

        }

        Artifact artifact = artifacts.get(0);

        return Response.temporaryRedirect(new URI(artifact.getUrl())).build();
    } catch (Exception e) {
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
}

From source file:com.inmobi.conduit.local.LocalStreamService.java

private void populateCheckpointPathForCollector(Table<String, String, String> checkpointPaths,
        TreeMap<String, FileStatus> collectorPaths) {
    // Last file in sorted ascending order to be check-pointed for this
    // collector//w  w w . j ava  2  s.c  o m
    if (collectorPaths != null && collectorPaths.size() > 0) {
        Entry<String, FileStatus> entry = collectorPaths.lastEntry();
        Path filePath = entry.getValue().getPath();
        String streamName = getCategoryFromSrcPath(filePath);
        String collectorName = filePath.getParent().getName();
        String checkpointPath = filePath.getName();
        checkpointPaths.put(streamName, collectorName, checkpointPath);
    }
}

From source file:GitBackend.GitAPI.java

public RevCommit getMostRecentCommit(Date execDate, String path) {
    TreeMap<DateTime, RevCommit> allCommits = this.getAllCommitsBefore(execDate, path);
    if (allCommits.size() == 0) {
        logger.severe("Error... No commit");
        return null;
    } else {/*from   w w  w.  j av  a2 s.  c o m*/
        RevCommit lastCommit = allCommits.lastEntry().getValue();
        System.out.println("Last entry: " + lastCommit.getName() + " was at "
                + new DateTime(lastCommit.getCommitterIdent().getWhen()));
        return lastCommit;

    }

}

From source file:com.terremark.impl.TerremarkClientImpl.java

/**
 * Internal method to retrieve the server supported API versions and time. If client specified a specific API
 * version, it is checked to see if the server supports it. {@link java.lang.IllegalArgumentException} is thrown if
 * the client API version is not supported by the server. If client did not specify a version, the latest version in
 * the server provided list is chosen for the client. The time difference between the server and the client is
 * computed and cached.//from w  w w  .j  a v  a 2s  .  com
 *
 * @param clientVersion Client specified API version. Can be null.
 * @throws TerremarkException If error occurs while retrieving the server time and/or API versions.
 */
private void initialize(final Version clientVersion) throws TerremarkException {
    final SupportedVersions versions = getSupportedVersions();
    final TreeMap<Date, String> versionDates = new TreeMap<Date, String>();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    for (final VersionInfo vi : versions.getVersionInfos()) {
        try {
            versionDates.put(sdf.parse(vi.getVersion()), vi.getVersion());
        } catch (final ParseException ex) {
            throw new InternalServerException(
                    "While validating the API version, got invalid version from server: " + vi.getVersion(),
                    ex);
        }
    }

    String clientVersionStr = clientVersion == null ? null : clientVersion.toString();
    if (clientVersionStr == null) {
        clientVersionStr = versionDates.lastEntry().getValue();
    } else {
        if (!versionDates.values().contains(clientVersionStr)) {
            throw new IllegalArgumentException("Invalid API version: " + clientVersionStr);
        }
    }

    final Date serverDateTime = getTime().getCurrentServerTime().toGregorianCalendar().getTime();

    versionAndDateProvider.setVersion(clientVersionStr);
    versionAndDateProvider.calculateClockSkew(serverDateTime);
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

public String executeProcessExtractionCmd(String processList, String iosDeployPath) {
    TreeMap<Date, String> pidList = new TreeMap<>();
    if (processList != null) {
        String[] lineArr = processList.split(Util.LINE_SEPARATOR);
        SimpleDateFormat formatter = new SimpleDateFormat("hh:mma");
        for (String str : lineArr) {
            String[] strArr = str.split(" +");
            try {
                if (str.contains(iosDeployPath) && strArr.length >= 8) {
                    Date timestamp = formatter.parse(strArr[8]);
                    pidList.put(timestamp, strArr[1]);
                }/*from  ww  w.jav  a2s  .  co m*/

            } catch (ParseException e) {
                LOGGER.error("Exception during pid extraction");
            }
        }
    }

    return pidList.lastEntry().getValue();
}

From source file:ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition.java

@SuppressWarnings("unchecked")
private void scanCompositeElementForChildren(Set<String> elementNames,
        TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> theOrderToElementDef,
        TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> theOrderToExtensionDef) {
    int baseElementOrder = 0;

    for (ScannedField next : myScannedFields) {
        if (next.isFirstFieldInNewClass()) {
            baseElementOrder = theOrderToElementDef.isEmpty() ? 0
                    : theOrderToElementDef.lastEntry().getKey() + 1;
        }/*from  w w w  .j  a  va  2 s .c o  m*/

        Class<?> declaringClass = next.getField().getDeclaringClass();

        Description descriptionAnnotation = ModelScanner.pullAnnotation(next.getField(), Description.class);

        TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> orderMap = theOrderToElementDef;
        Extension extensionAttr = ModelScanner.pullAnnotation(next.getField(), Extension.class);
        if (extensionAttr != null) {
            orderMap = theOrderToExtensionDef;
        }

        Child childAnnotation = next.getChildAnnotation();
        Field nextField = next.getField();
        String elementName = childAnnotation.name();
        int order = childAnnotation.order();
        boolean childIsChoiceType = false;
        boolean orderIsReplaceParent = false;

        if (order == Child.REPLACE_PARENT) {

            if (extensionAttr != null) {

                for (Entry<Integer, BaseRuntimeDeclaredChildDefinition> nextEntry : orderMap.entrySet()) {
                    BaseRuntimeDeclaredChildDefinition nextDef = nextEntry.getValue();
                    if (nextDef instanceof RuntimeChildDeclaredExtensionDefinition) {
                        if (nextDef.getExtensionUrl().equals(extensionAttr.url())) {
                            orderIsReplaceParent = true;
                            order = nextEntry.getKey();
                            orderMap.remove(nextEntry.getKey());
                            elementNames.remove(elementName);
                            break;
                        }
                    }
                }
                if (order == Child.REPLACE_PARENT) {
                    throw new ConfigurationException("Field " + nextField.getName() + "' on target type "
                            + declaringClass.getSimpleName() + " has order() of REPLACE_PARENT ("
                            + Child.REPLACE_PARENT + ") but no parent element with extension URL "
                            + extensionAttr.url() + " could be found on type "
                            + nextField.getDeclaringClass().getSimpleName());
                }

            } else {

                for (Entry<Integer, BaseRuntimeDeclaredChildDefinition> nextEntry : orderMap.entrySet()) {
                    BaseRuntimeDeclaredChildDefinition nextDef = nextEntry.getValue();
                    if (elementName.equals(nextDef.getElementName())) {
                        orderIsReplaceParent = true;
                        order = nextEntry.getKey();
                        BaseRuntimeDeclaredChildDefinition existing = orderMap.remove(nextEntry.getKey());
                        elementNames.remove(elementName);

                        /*
                         * See #350 - If the original field (in the superclass) with the given name is a choice, then we need to make sure
                         * that the field which replaces is a choice even if it's only a choice of one type - this is because the
                         * element name when serialized still needs to reflect the datatype
                         */
                        if (existing instanceof RuntimeChildChoiceDefinition) {
                            childIsChoiceType = true;
                        }
                        break;
                    }
                }
                if (order == Child.REPLACE_PARENT) {
                    throw new ConfigurationException("Field " + nextField.getName() + "' on target type "
                            + declaringClass.getSimpleName() + " has order() of REPLACE_PARENT ("
                            + Child.REPLACE_PARENT + ") but no parent element with name " + elementName
                            + " could be found on type " + nextField.getDeclaringClass().getSimpleName());
                }

            }

        }

        if (order < 0 && order != Child.ORDER_UNKNOWN) {
            throw new ConfigurationException("Invalid order '" + order + "' on @Child for field '"
                    + nextField.getName() + "' on target type: " + declaringClass);
        }

        if (order != Child.ORDER_UNKNOWN && !orderIsReplaceParent) {
            order = order + baseElementOrder;
        }
        // int min = childAnnotation.min();
        // int max = childAnnotation.max();

        /*
         * Anything that's marked as unknown is given a new ID that is <0 so that it doesn't conflict with any given IDs and can be figured out later
         */
        if (order == Child.ORDER_UNKNOWN) {
            order = Integer.valueOf(0);
            while (orderMap.containsKey(order)) {
                order++;
            }
        }

        List<Class<? extends IBase>> choiceTypes = next.getChoiceTypes();

        if (orderMap.containsKey(order)) {
            throw new ConfigurationException("Detected duplicate field order '" + childAnnotation.order()
                    + "' for element named '" + elementName + "' in type '" + declaringClass.getCanonicalName()
                    + "' - Already had: " + orderMap.get(order).getElementName());
        }

        if (elementNames.contains(elementName)) {
            throw new ConfigurationException("Detected duplicate field name '" + elementName + "' in type '"
                    + declaringClass.getCanonicalName() + "'");
        }

        Class<?> nextElementType = next.getElementType();

        BaseRuntimeDeclaredChildDefinition def;
        if (childAnnotation.name().equals("extension")
                && IBaseExtension.class.isAssignableFrom(nextElementType)) {
            def = new RuntimeChildExtension(nextField, childAnnotation.name(), childAnnotation,
                    descriptionAnnotation);
        } else if (childAnnotation.name().equals("modifierExtension")
                && IBaseExtension.class.isAssignableFrom(nextElementType)) {
            def = new RuntimeChildExtension(nextField, childAnnotation.name(), childAnnotation,
                    descriptionAnnotation);
        } else if (BaseContainedDt.class.isAssignableFrom(nextElementType)
                || (childAnnotation.name().equals("contained")
                        && IBaseResource.class.isAssignableFrom(nextElementType))) {
            /*
             * Child is contained resources
             */
            def = new RuntimeChildContainedResources(nextField, childAnnotation, descriptionAnnotation,
                    elementName);
        } else if (IAnyResource.class.isAssignableFrom(nextElementType)
                || IResource.class.equals(nextElementType)) {
            /*
             * Child is a resource as a direct child, as in Bundle.entry.resource
             */
            def = new RuntimeChildDirectResource(nextField, childAnnotation, descriptionAnnotation,
                    elementName);
        } else {
            childIsChoiceType |= choiceTypes.size() > 1;
            if (childIsChoiceType && !BaseResourceReferenceDt.class.isAssignableFrom(nextElementType)
                    && !IBaseReference.class.isAssignableFrom(nextElementType)) {
                def = new RuntimeChildChoiceDefinition(nextField, elementName, childAnnotation,
                        descriptionAnnotation, choiceTypes);
            } else if (extensionAttr != null) {
                /*
                 * Child is an extension
                 */
                Class<? extends IBase> et = (Class<? extends IBase>) nextElementType;

                Object binder = null;
                if (BoundCodeDt.class.isAssignableFrom(nextElementType)
                        || IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) {
                    binder = ModelScanner.getBoundCodeBinder(nextField);
                }

                def = new RuntimeChildDeclaredExtensionDefinition(nextField, childAnnotation,
                        descriptionAnnotation, extensionAttr, elementName, extensionAttr.url(), et, binder);

                if (IBaseEnumeration.class.isAssignableFrom(nextElementType)) {
                    ((RuntimeChildDeclaredExtensionDefinition) def).setEnumerationType(
                            ReflectionUtil.getGenericCollectionTypeOfFieldWithSecondOrderForList(nextField));
                }
            } else if (BaseResourceReferenceDt.class.isAssignableFrom(nextElementType)
                    || IBaseReference.class.isAssignableFrom(nextElementType)) {
                /*
                 * Child is a resource reference
                 */
                List<Class<? extends IBaseResource>> refTypesList = new ArrayList<Class<? extends IBaseResource>>();
                for (Class<? extends IElement> nextType : childAnnotation.type()) {
                    if (IBaseReference.class.isAssignableFrom(nextType)) {
                        refTypesList.add(myContext.getVersion().getVersion().isRi() ? IAnyResource.class
                                : IResource.class);
                        continue;
                    } else if (IBaseResource.class.isAssignableFrom(nextType) == false) {
                        throw new ConfigurationException("Field '" + nextField.getName() + "' in class '"
                                + nextField.getDeclaringClass().getCanonicalName() + "' is of type "
                                + BaseResourceReferenceDt.class + " but contains a non-resource type: "
                                + nextType.getCanonicalName());
                    }
                    refTypesList.add((Class<? extends IBaseResource>) nextType);
                }
                def = new RuntimeChildResourceDefinition(nextField, elementName, childAnnotation,
                        descriptionAnnotation, refTypesList);

            } else if (IResourceBlock.class.isAssignableFrom(nextElementType)
                    || IBaseBackboneElement.class.isAssignableFrom(nextElementType)
                    || IBaseDatatypeElement.class.isAssignableFrom(nextElementType)) {
                /*
                 * Child is a resource block (i.e. a sub-tag within a resource) TODO: do these have a better name according to HL7?
                 */

                Class<? extends IBase> blockDef = (Class<? extends IBase>) nextElementType;
                def = new RuntimeChildResourceBlockDefinition(myContext, nextField, childAnnotation,
                        descriptionAnnotation, elementName, blockDef);
            } else if (IDatatype.class.equals(nextElementType) || IElement.class.equals(nextElementType)
                    || "Type".equals(nextElementType.getSimpleName())
                    || IBaseDatatype.class.equals(nextElementType)) {

                def = new RuntimeChildAny(nextField, elementName, childAnnotation, descriptionAnnotation);
            } else if (IDatatype.class.isAssignableFrom(nextElementType)
                    || IPrimitiveType.class.isAssignableFrom(nextElementType)
                    || ICompositeType.class.isAssignableFrom(nextElementType)
                    || IBaseDatatype.class.isAssignableFrom(nextElementType)
                    || IBaseExtension.class.isAssignableFrom(nextElementType)) {
                Class<? extends IBase> nextDatatype = (Class<? extends IBase>) nextElementType;

                if (IPrimitiveType.class.isAssignableFrom(nextElementType)) {
                    if (nextElementType.equals(BoundCodeDt.class)) {
                        IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(nextField);
                        Class<? extends Enum<?>> enumType = ModelScanner
                                .determineEnumTypeForBoundField(nextField);
                        def = new RuntimeChildPrimitiveBoundCodeDatatypeDefinition(nextField, elementName,
                                childAnnotation, descriptionAnnotation, nextDatatype, binder, enumType);
                    } else if (IBaseEnumeration.class.isAssignableFrom(nextElementType)) {
                        Class<? extends Enum<?>> binderType = ModelScanner
                                .determineEnumTypeForBoundField(nextField);
                        def = new RuntimeChildPrimitiveEnumerationDatatypeDefinition(nextField, elementName,
                                childAnnotation, descriptionAnnotation, nextDatatype, binderType);
                    } else {
                        def = new RuntimeChildPrimitiveDatatypeDefinition(nextField, elementName,
                                descriptionAnnotation, childAnnotation, nextDatatype);
                    }
                } else {
                    if (IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) {
                        IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(nextField);
                        Class<? extends Enum<?>> enumType = ModelScanner
                                .determineEnumTypeForBoundField(nextField);
                        def = new RuntimeChildCompositeBoundDatatypeDefinition(nextField, elementName,
                                childAnnotation, descriptionAnnotation, nextDatatype, binder, enumType);
                    } else if (BaseNarrativeDt.class.isAssignableFrom(nextElementType)
                            || INarrative.class.isAssignableFrom(nextElementType)) {
                        def = new RuntimeChildNarrativeDefinition(nextField, elementName, childAnnotation,
                                descriptionAnnotation, nextDatatype);
                    } else {
                        def = new RuntimeChildCompositeDatatypeDefinition(nextField, elementName,
                                childAnnotation, descriptionAnnotation, nextDatatype);
                    }
                }

            } else {
                throw new ConfigurationException(
                        "Field '" + elementName + "' in type '" + declaringClass.getCanonicalName()
                                + "' is not a valid child type: " + nextElementType);
            }

            Binding bindingAnnotation = ModelScanner.pullAnnotation(nextField, Binding.class);
            if (bindingAnnotation != null) {
                if (isNotBlank(bindingAnnotation.valueSet())) {
                    def.setBindingValueSet(bindingAnnotation.valueSet());
                }
            }

        }

        orderMap.put(order, def);
        elementNames.add(elementName);
    }
}

From source file:cx.ring.service.LocalService.java

public void updateTextNotifications() {
    Log.d(TAG, "updateTextNotifications()");

    for (Conversation c : conversations.values()) {
        TreeMap<Long, TextMessage> texts = c.getUnreadTextMessages();
        if (texts.isEmpty() || texts.lastEntry().getValue().isNotified()) {
            continue;
        } else//from   w w w  . j a v a 2s.  c o m
            notificationManager.cancel(c.notificationId);

        CallContact contact = c.getContact();
        if (c.notificationBuilder == null) {
            c.notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
            c.notificationBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setDefaults(NotificationCompat.DEFAULT_ALL)
                    .setSmallIcon(R.drawable.ic_launcher).setContentTitle(contact.getDisplayName());
        }
        NotificationCompat.Builder noti = c.notificationBuilder;
        Intent c_intent = new Intent(Intent.ACTION_VIEW).setClass(this, ConversationActivity.class)
                .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0)));
        Intent d_intent = new Intent(ACTION_CONV_READ).setClass(this, LocalService.class)
                .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0)));
        noti.setContentIntent(PendingIntent.getActivity(this, new Random().nextInt(), c_intent, 0))
                .setDeleteIntent(PendingIntent.getService(this, new Random().nextInt(), d_intent, 0));

        if (contact.getPhoto() != null) {
            Resources res = getResources();
            int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height);
            int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(Bitmap.createScaledBitmap(contact.getPhoto(), width, height, false));
        }
        if (texts.size() == 1) {
            TextMessage txt = texts.firstEntry().getValue();
            txt.setNotified(true);
            noti.setContentText(txt.getMessage());
            noti.setStyle(null);
            noti.setWhen(txt.getTimestamp());
        } else {
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            for (TextMessage s : texts.values()) {
                inboxStyle.addLine(Html.fromHtml("<b>"
                        + DateUtils.formatDateTime(this, s.getTimestamp(),
                                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL)
                        + "</b> " + s.getMessage()));
                s.setNotified(true);
            }
            noti.setContentText(texts.lastEntry().getValue().getMessage());
            noti.setStyle(inboxStyle);
            noti.setWhen(texts.lastEntry().getValue().getTimestamp());
        }
        notificationManager.notify(c.notificationId, noti.build());
    }
}

From source file:com.unboundid.scim2.common.utils.JsonDiff.java

/**
 * Removes the value from an ArrayNode that matches the provided node.
 *
 * @param sourceValue The sourceValue node to match.
 * @param targetValues The ArrayNode containing the values to remove from.
 * @return The matching value that was removed or {@code null} if no matching
 *         value was found./*from   w w w . j av  a 2s. co m*/
 */
private JsonNode removeMatchingValue(final JsonNode sourceValue, final ArrayNode targetValues) {
    if (sourceValue.isObject()) {
        // Find a target value that has the most fields in common with the source
        // and have identical values. Common fields that are also one of the
        // SCIM standard multi-value sub-attributes (ie. type, value, etc...) have
        // a higher weight when determining the best matching value.
        TreeMap<Integer, Integer> matchScoreToIndex = new TreeMap<Integer, Integer>();
        for (int i = 0; i < targetValues.size(); i++) {
            JsonNode targetValue = targetValues.get(i);
            if (targetValue.isObject()) {
                int matchScore = 0;
                Iterator<String> si = sourceValue.fieldNames();
                while (si.hasNext()) {
                    String field = si.next();
                    if (sourceValue.get(field).equals(targetValue.path(field))) {
                        if (field.equals("value") || field.equals("$ref")) {
                            // These fields have the highest chance of having unique values.
                            matchScore += 3;
                        } else if (field.equals("type") || field.equals("display")) {
                            // These fields should mostly be unique.
                            matchScore += 2;
                        } else if (field.equals("primary")) {
                            // This field will definitely not be unique.
                            matchScore += 0;
                        } else {
                            // Not one of the normative fields. Use the default weight.
                            matchScore += 1;
                        }
                    }
                }
                // Only consider the match if there is not already match with the same
                // score. This will prefer matches at the same index in the array.
                if (matchScore > 0 && !matchScoreToIndex.containsKey(matchScore)) {
                    matchScoreToIndex.put(matchScore, i);
                }
            }
        }
        if (!matchScoreToIndex.isEmpty()) {
            return targetValues.remove(matchScoreToIndex.lastEntry().getValue());
        }
    } else {
        // Find an exact match
        for (int i = 0; i < targetValues.size(); i++) {
            if (JsonUtils.compareTo(sourceValue, targetValues.get(i), null) == 0) {
                return targetValues.remove(i);
            }
        }
    }

    // Can't find a match at all.
    return null;
}

From source file:ukhas.Habitat_interface.java

private boolean getPayloadDataSince(long timestampStart, long timestampStop, int limit, String payloadID,
        String callsign) {//  w  ww.  j  a  v  a 2 s  . c  om
    double prevAltitude = -99999999;
    double maxAltitude = -99999999;
    long prevtime = -1;
    try {

        //open DB connection
        if (s == null) {
            s = new Session(_habitat_url, 80);
            db = s.getDatabase(_habitat_db);// + "/_design/payload_telemetry/_update/add_listener");
        } else if (db == null)
            db = s.getDatabase(_habitat_db);

        View v = new View("payload_telemetry/payload_time");

        long starttime;
        if (timestampStart > 0)
            starttime = timestampStart;
        else
            starttime = (System.currentTimeMillis() / 1000L) - _prev_query_time;

        v.setStartKey("[%22" + payloadID + "%22," + Long.toString(starttime) + "]");
        v.setEndKey("[%22" + payloadID + "%22," + Long.toString(timestampStop) + "]");

        v.setWithDocs(true);
        v.setLimit(limit);

        System.out.println("DEBUG: DATABASE GOT QUERY");

        TreeMap<Long, Telemetry_string> out = new TreeMap<Long, Telemetry_string>();

        JsonFactory fac = new JsonFactory();
        InputStream is = db.view_dont_parse(v);
        long lasttime = 0;

        if (is != null) {

            JsonParser jp = fac.createJsonParser(is);

            String str, str1;
            boolean gotkey = false;
            boolean keypt1 = false;

            TelemetryConfig tc = null;
            if (telem_configs.containsKey(callsign)) {
                tc = telem_configs.get(callsign);
            }

            while (jp.nextToken() != null)// || (jp.getCurrentLocation().getCharOffset() < body.length()-50)) && nullcount < 20) //100000 > out.size())
            {
                //jp.nextToken();

                str = jp.getCurrentName();
                str1 = jp.getText();
                if (str == "key" && str1 == "[")
                    gotkey = true;
                else if (gotkey) {
                    keypt1 = true;
                    gotkey = false;
                } else if (keypt1) {
                    keypt1 = false;
                    try {
                        lasttime = Long.parseLong(str1);
                    } catch (NumberFormatException e) {
                        System.out.println("ERROR PARSING - NUMBER FORMAT EXCEPTION!!!");
                    }

                }
                if (str != null && str1 != null) {
                    if (str.equals("_sentence") && !str1.equals("_sentence")) {
                        Telemetry_string ts = new Telemetry_string(str1, lasttime, tc);
                        if (!ts.isZeroGPS() && ts.time != null) {
                            if (out.size() > 0) {
                                if (out.lastEntry().getValue().coords.alt_valid) {
                                    prevAltitude = out.lastEntry().getValue().coords.altitude;
                                    prevtime = out.lastEntry().getValue().time.getTime();
                                }
                            }
                            out.put(new Long(ts.time.getTime()), ts);
                            if (ts.coords.alt_valid)
                                maxAltitude = Math.max(ts.coords.altitude, maxAltitude);
                        }
                    }

                    //nullcount = 0;
                }
                //else
                //   nullcount++;
            }
            jp.close();
            is.close();

        }
        s.clearCouchResponse();

        System.out.println("DEBUG: DATABASE PROCESSING DONE");

        AscentRate as = new AscentRate();

        if (out.size() >= 2 && prevAltitude > -9999) {
            as = new AscentRate();
            as.addData(prevtime, prevAltitude);
            if (out.lastEntry().getValue().coords.alt_valid) {
                as.addData(out.lastEntry().getValue().time.getTime(),
                        out.lastEntry().getValue().coords.altitude);

            } else
                as = new AscentRate();
        }
        lasttime += 1000;
        if (lasttime >= timestampStart && lasttime <= timestampStop)
            fireDataReceived(out, true, callsign, timestampStart, lasttime, as, maxAltitude);
        else
            fireDataReceived(out, true, callsign, timestampStart, timestampStop, as, maxAltitude);

        return true;
    }

    catch (Exception e) {
        fireDataReceived(null, false, e.toString(), timestampStart, timestampStop, null, -99999999);
        return false;
    }
}