Example usage for java.util TreeMap values

List of usage examples for java.util TreeMap values

Introduction

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

Prototype

public Collection<V> values() 

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:org.xframium.spi.RunDetails.java

private void writePageHeader(StringBuilder stringBuilder, int activeIndex) {
    TreeMap<String, int[]> caseMap = new TreeMap<String, int[]>();
    TreeMap<String, int[]> deviceMap = new TreeMap<String, int[]>();
    TreeMap<String, int[]> osMap = new TreeMap<String, int[]>();

    int osSuccess = 0;
    int osFail = 0;
    int[] stepBreakdown = new int[3];
    int successCount = 0;
    int skipCount = 0;
    int failCount = 0;
    int scriptFailure = 0;
    int configFailure = 0;
    int appFailure = 0;
    int cloudFailure = 0;
    for (int i = 0; i < detailsList.size(); i++) {
        String runKey = (String) detailsList.get(i)[0];
        Device device = (Device) detailsList.get(i)[1];
        int success = (int) detailsList.get(i)[2];
        stepBreakdown[0] += (int) detailsList.get(i)[3];
        stepBreakdown[1] += (int) detailsList.get(i)[4];
        stepBreakdown[2] += (int) detailsList.get(i)[5];

        scriptFailure += (int) detailsList.get(i)[8];
        configFailure += (int) detailsList.get(i)[9];
        appFailure += (int) detailsList.get(i)[10];
        cloudFailure += (int) detailsList.get(i)[11];

        String deviceKey = device.getManufacturer() + " " + device.getModel();

        int[] caseValue = caseMap.get(runKey);
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0 };
            caseMap.put(runKey, caseValue);
        }//from ww  w  .j  a v  a2 s .com

        if (success == 1)
            caseValue[0]++;
        else if (success == 0)
            caseValue[1]++;
        else
            caseValue[2]++;

        caseValue = deviceMap.get(deviceKey);
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0 };
            deviceMap.put(deviceKey, caseValue);
        }

        if (success == 1)
            caseValue[0]++;
        else if (success == 0)
            caseValue[1]++;
        else
            caseValue[2]++;

        String osName = device.getEnvironment();
        if (osName == null)
            osName = "Unknown";

        caseValue = osMap.get(osName);
        if (caseValue == null) {
            caseValue = new int[] { 0, 0, 0 };
            osMap.put(osName, caseValue);
        }

        if (success == 1)
            caseValue[0]++;
        else if (success == 0)
            caseValue[1]++;
        else
            caseValue[2]++;

        if (success == 1)
            successCount++;
        else if (success == 0)
            failCount++;
        else
            skipCount++;
    }

    for (int[] caseValue : osMap.values()) {
        if (caseValue[1] > 0)
            osFail++;
        else
            osSuccess++;
    }

    stringBuilder.append("<html>");
    stringBuilder.append(
            "<head><link href=\"http://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic\" rel=\"stylesheet\"><link href=\"http://www.xframium.org/output/assets/css/toolkit-inverse.css\" rel=\"stylesheet\"><link href=\"http://www.xframium.org/output/assets/css/application.css\" rel=\"stylesheet\"><style>.abscenter { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } h2 { margin-bottom: 0px;}  h4 { margin-bottom: 0px;} .pass {color: #1bc98e;}.fail {color: #e64759;}</style></head>");
    stringBuilder.append("<body><div class=\"container\"><div class=\"row\">");

    stringBuilder.append(
            "<div class=\"col-sm-12 content\"><div class=\"dashhead\"><span class=\"pull-right text-muted\">")
            .append(simpleDateFormat.format(new Date(System.currentTimeMillis()))).append(" at ")
            .append(simpleTimeFormat.format(new Date(System.currentTimeMillis())))
            .append("</span><h6 class=\"dashhead-subtitle\">xFramium " + Initializable.VERSION
                    + "</h6><h3 class=\"dashhead-title\">Test Suite Execution Summary</h3><h6>"
                    + ApplicationRegistry.instance().getAUT().getName() + "</h6></div>");

    stringBuilder.append(
            "<div class=\"row text-center m-t-lg\"><div class=\"col-sm-2 m-b-md\"></div><div class=\"col-sm-3 m-b-md\"><div class=\"w-lg m-x-auto\">");
    stringBuilder.append(
            "<div class=\"abscenter\"  style=\"width: 100%; height: 100px; vertical-align: center;  line-height:19px; text-align: center; z-index: 999999999999999\"><h2 class=\"text-muted\"><b>"
                    + detailsList.size() + "</b></h2><h4><span class=\"text-success\">" + successCount
                    + "</span> / <span class=\"text-warning\">" + skipCount
                    + "</span> / <span class=\"text-danger\">" + failCount + "</span></h4></div>");
    stringBuilder.append(
            "<canvas class=\"ex-graph\" width=\"200\" height=\"200\" data-animation=\"true\" data-animation-easing=\"easeOutQuart\" data-chart=\"doughnut\" data-value=\"[");
    stringBuilder.append("{ value: ").append(successCount).append(", color: '#1bc98e', label: 'Passed' },");

    int failureCount = failCount;
    if (scriptFailure > 0) {
        stringBuilder.append("{ value: ").append(scriptFailure)
                .append(", color: '#ea6272', label: 'Script Issues' },");
        failureCount -= scriptFailure;
    }

    if (configFailure > 0) {
        stringBuilder.append("{ value: ").append(configFailure)
                .append(", color: '#e74b5e', label: 'Configuration Issues' },");
        failureCount -= configFailure;
    }

    if (appFailure > 0) {
        stringBuilder.append("{ value: ").append(appFailure)
                .append(", color: '#e33549', label: 'Application Issues' },");
        failureCount -= appFailure;
    }

    if (cloudFailure > 0) {
        stringBuilder.append("{ value: ").append(cloudFailure)
                .append(", color: '#e01f35', label: 'Device Issues' },");
        failureCount -= cloudFailure;
    }

    if (skipCount > 0) {
        stringBuilder.append("{ value: ").append(skipCount)
                .append(", color: '#e4d836', label: 'Skipped Tests' },");
        failureCount -= configFailure;
    }

    if (failureCount > 0) {
        stringBuilder.append("{ value: ").append(failureCount)
                .append(", color: '#e64759', label: 'General Failures' },");
    }

    stringBuilder.append(
            "]\" data-segment-stroke-color=\"white\" data-percentage-inner-cutout=\"70\" /></div><center><strong class=\"text-muted\">Test Executions</strong></center></div>");

    stringBuilder.append("<div class=\"col-sm-3 m-b-md\"><div class=\"w-lg m-x-auto\">");
    stringBuilder.append(
            "<div class=\"abscenter\"  style=\"width: 100%; height: 100px; vertical-align: center;  line-height:19px; text-align: center; z-index: 999999999999999\"><h2 class=\"text-muted\"><b>"
                    + (stepBreakdown[0] + stepBreakdown[1] + stepBreakdown[2])
                    + "</b></h2><h4><span class=\"text-success\">" + stepBreakdown[0]
                    + "</span> / <span class=\"text-danger\">" + stepBreakdown[1] + "</span></h4></div>");
    stringBuilder.append(
            "<canvas class=\"ex-graph\" width=\"200\" height=\"200\" data-animation=\"true\" data-animation-easing=\"easeOutQuart\" data-chart=\"doughnut\" data-value=\"[");
    stringBuilder.append("{ value: ").append(stepBreakdown[0]).append(", color: '#1bc98e', label: 'Passed' },");
    stringBuilder.append("{ value: ").append(stepBreakdown[1]).append(", color: '#e64759', label: 'Failed' },");
    stringBuilder.append("{ value: ").append(stepBreakdown[2]).append(", color: '#e4d836', label: 'Ignored' }");
    stringBuilder.append(
            "]\" data-segment-stroke-color=\"white\" data-percentage-inner-cutout=\"70\" /></div><center><strong class=\"text-muted\">Tests Steps</strong></center></div>");

    stringBuilder.append("<div class=\"col-sm-3 m-b-md\"><div class=\"w-lg m-x-auto\">");
    stringBuilder.append(
            "<div class=\"abscenter\"  style=\"width: 100%; height: 100px; vertical-align: center;  line-height:19px; text-align: center; z-index: 999999999999999\"><h2 class=\"text-muted\"><b>"
                    + (osSuccess + osFail) + "</b></h2><h4><span class=\"text-success\">" + osSuccess
                    + "</span> / <span class=\"text-danger\">" + osFail + "</span></h4></div>");
    stringBuilder.append(
            "<canvas class=\"ex-graph\" width=\"200\" height=\"200\" data-animation=\"true\" data-animation-easing=\"easeOutQuart\" data-chart=\"doughnut\" data-value=\"[");
    stringBuilder.append("{ value: ").append(osSuccess).append(", color: '#1bc98e', label: 'Passed' },");
    stringBuilder.append("{ value: ").append(osFail).append(", color: '#e64759', label: 'Failed' },");
    stringBuilder.append(
            "]\" data-segment-stroke-color=\"white\" data-percentage-inner-cutout=\"70\" /></div><center><strong class=\"text-muted\">Environments</strong></center></div>");

    stringBuilder.append("</div>");

}

From source file:org.jamocha.dn.compiler.pathblocks.PathBlocks.java

protected static List<PathRule> createOutput(final List<Either<Rule, ExistentialProxy>> rules,
        final PathBlockSet resultBlockSet) {
    final Function<? super Block, ? extends Integer> characteristicNumber = block -> block
            .getFlatFilterInstances().size() / block.getRulesOrProxies().size();
    final TreeMap<Integer, CursorableLinkedList<Block>> blockMap = resultBlockSet.getBlocks().stream()
            .collect(groupingBy(characteristicNumber, TreeMap::new, toCollection(CursorableLinkedList::new)));
    // iterate over all the filter proxies ever used
    for (final FilterProxy filterProxy : FilterProxy.getFilterProxies()) {
        final Set<ExistentialProxy> existentialProxies = filterProxy.getProxies();
        // determine the largest characteristic number of the blocks containing filter instances
        // of one of the existential proxies (choice is arbitrary, since the filters and the
        // conflicts are identical if they belong to the same filter).
        final OptionalInt optMax = resultBlockSet.getRuleInstanceToBlocks()
                .computeIfAbsent(Either.right(existentialProxies.iterator().next()), newHashSet()).stream()
                .mapToInt(composeToInt(characteristicNumber, Integer::intValue)).max();
        if (!optMax.isPresent())
            continue;
        final int eCN = optMax.getAsInt();
        // get the list to append the blocks using the existential closure filter INSTANCE to
        final CursorableLinkedList<Block> targetList = blockMap.get(eCN);
        // for every existential part
        for (final ExistentialProxy existentialProxy : existentialProxies) {
            final FilterInstance exClosure = existentialProxy.getExistentialClosure();
            // create a list storing the blocks to move
            final List<Block> toMove = new ArrayList<>();
            for (final CursorableLinkedList<Block> blockList : blockMap.headMap(eCN, true).values()) {
                // iterate over the blocks in the current list
                for (final ListIterator<Block> iterator = blockList.listIterator(); iterator.hasNext();) {
                    final Block current = iterator.next();
                    // if the current block uses the current existential closure filter
                    // INSTANCE, it has to be moved
                    if (current.getFlatFilterInstances().contains(exClosure)) {
                        iterator.remove();
                        toMove.add(current);
                    }//from  w ww. j  av  a2 s. c o  m
                }
            }
            // append the blocks to be moved (they were only removed so far)
            targetList.addAll(toMove);
        }
    }
    final Set<FilterInstance> constructedFIs = new HashSet<>();
    final Map<Either<Rule, ExistentialProxy>, Map<FilterInstance, Set<FilterInstance>>> ruleToJoinedWith = new HashMap<>();
    final Map<Set<FilterInstance>, PathFilterList> joinedWithToComponent = new HashMap<>();
    // at this point, the network can be constructed
    for (final CursorableLinkedList<Block> blockList : blockMap.values()) {
        for (final Block block : blockList) {
            final List<Either<Rule, ExistentialProxy>> blockRules = Lists
                    .newArrayList(block.getRulesOrProxies());
            final Set<List<FilterInstance>> filterInstanceColumns = Block
                    .getFilterInstanceColumns(block.getFilters(), block.getRuleToFilterToRow(), blockRules);
            // since we are considering blocks, it is either the case that all filter
            // instances of the column have been constructed or none of them have
            final PathSharedListWrapper sharedListWrapper = new PathSharedListWrapper(blockRules.size());
            final Map<Either<Rule, ExistentialProxy>, PathSharedList> ruleToSharedList = IntStream
                    .range(0, blockRules.size()).boxed()
                    .collect(toMap(blockRules::get, sharedListWrapper.getSharedSiblings()::get));
            final List<List<FilterInstance>> columnsToConstruct, columnsAlreadyConstructed;
            {
                final Map<Boolean, List<List<FilterInstance>>> partition = filterInstanceColumns.stream()
                        .collect(partitioningBy(column -> Collections.disjoint(column, constructedFIs)));
                columnsAlreadyConstructed = partition.get(Boolean.FALSE);
                columnsToConstruct = partition.get(Boolean.TRUE);
            }

            if (!columnsAlreadyConstructed.isEmpty()) {
                final Map<PathSharedList, LinkedHashSet<PathFilterList>> sharedPart = new HashMap<>();
                for (final List<FilterInstance> column : columnsAlreadyConstructed) {
                    for (final FilterInstance fi : column) {
                        sharedPart
                                .computeIfAbsent(ruleToSharedList.get(fi.getRuleOrProxy()), newLinkedHashSet())
                                .add(joinedWithToComponent
                                        .get(ruleToJoinedWith.get(fi.getRuleOrProxy()).get(fi)));
                    }
                }
                sharedListWrapper.addSharedColumns(sharedPart);
            }

            for (final List<FilterInstance> column : columnsToConstruct) {
                sharedListWrapper.addSharedColumn(column.stream().collect(
                        toMap(fi -> ruleToSharedList.get(fi.getRuleOrProxy()), FilterInstance::convert)));
            }
            constructedFIs.addAll(block.getFlatFilterInstances());
            for (final Entry<Either<Rule, ExistentialProxy>, Map<Filter, FilterInstancesSideBySide>> entry : block
                    .getRuleToFilterToRow().entrySet()) {
                final Either<Rule, ExistentialProxy> rule = entry.getKey();
                final Set<FilterInstance> joined = entry.getValue().values().stream()
                        .flatMap(sbs -> sbs.getInstances().stream()).collect(toSet());
                final Map<FilterInstance, Set<FilterInstance>> joinedWithMapForThisRule = ruleToJoinedWith
                        .computeIfAbsent(rule, newHashMap());
                joined.forEach(fi -> joinedWithMapForThisRule.put(fi, joined));
                joinedWithToComponent.put(joined, ruleToSharedList.get(rule));
            }
        }
    }
    final List<PathRule> pathRules = new ArrayList<>();
    for (final Either<Rule, ExistentialProxy> either : rules) {
        if (either.isRight()) {
            continue;
        }
        final List<PathFilterList> pathFilterLists = Stream
                .concat(either.left().get().existentialProxies.values().stream().map(p -> Either.right(p)),
                        Stream.of(either))
                .flatMap(e -> ruleToJoinedWith.getOrDefault(e, Collections.emptyMap()).values().stream()
                        .distinct())
                .map(joinedWithToComponent::get).collect(toList());
        pathRules.add(either.left().get().getOriginal().toPathRule(PathFilterList.toSimpleList(pathFilterLists),
                pathFilterLists.size() > 1 ? InitialFactPathsFinder.gather(pathFilterLists)
                        : Collections.emptySet()));
    }
    return pathRules;
}

From source file:org.onebusaway.nyc.sms.actions.IndexAction.java

private String singleStopResponse(String message) throws Exception {

    if (message == null) {
        message = "";
    }//from   w  w w  .  j ava2  s.  co m
    message = message.trim();
    if (!message.isEmpty()) {
        message = "\n" + message + "\n";
    }

    StopResult stopResult = (StopResult) _searchResults.getMatches().get(0);

    String header = "Stop " + stopResult.getIdWithoutAgency() + "\n\n";

    String footer = "\nSend:\n";
    footer += "R for refresh\n";
    if (_searchResults.getRouteFilter().isEmpty() && stopResult.getStop().getRoutes().size() > 1) {
        footer += stopResult.getIdWithoutAgency() + "+ROUTE for bus info\n";
    }

    // worst case for footer length
    String alertsFooter = footer + "C+ROUTE for *svc alert\n";

    // body content for stops
    String body = "";
    if (stopResult.getRoutesAvailable().size() == 0) {
        // if we found a stop with no routes because of a stop+route filter, 
        // indicate that specifically
        if (_searchResults.getRouteFilter().size() > 0) {
            body += "No filter matches\n";
        } else {
            body += "No routes\n";
        }
    } else {
        // bulid map of sorted vehicle observation strings for this stop, sorted by closest->farthest
        TreeMap<Double, String> observationsByDistanceFromStopAcrossAllRoutes = new TreeMap<Double, String>();
        // Keep track of not scheduled and not en route so we can display that later
        Set<String> notScheduledRoutes = new HashSet<String>();
        Set<String> notEnRouteRoutes = new HashSet<String>();

        for (RouteAtStop routeHere : stopResult.getRoutesAvailable()) {

            if (_searchResults.getRouteFilter() != null && !_searchResults.getRouteFilter().isEmpty()
                    && !_searchResults.getRouteFilter().contains(routeHere.getRoute())) {
                continue;
            }

            for (RouteDirection direction : routeHere.getDirections()) {
                String prefix = "";
                if (!direction.getSerivceAlerts().isEmpty()) {
                    footer = alertsFooter;
                    prefix += "*";
                }
                prefix += routeHere.getShortName();

                if (!direction.hasUpcomingScheduledService() && direction.getDistanceAways().isEmpty()) {
                    notScheduledRoutes.add(prefix);
                } else {
                    if (!direction.getDistanceAways().isEmpty()) {
                        HashMap<Double, String> sortableDistanceAways = direction.getDistanceAwaysWithSortKey();
                        for (Double distanceAway : sortableDistanceAways.keySet()) {
                            String distanceAwayString = sortableDistanceAways.get(distanceAway);

                            observationsByDistanceFromStopAcrossAllRoutes.put(distanceAway,
                                    prefix + ": " + distanceAwayString);
                        }
                    } else {
                        notEnRouteRoutes.add(prefix);
                    }
                }
            }
        }

        // if there are no upcoming buses, provide info about the routes that are not en route or not scheduled
        if (observationsByDistanceFromStopAcrossAllRoutes.isEmpty()) {
            if (notEnRouteRoutes.size() > 0) {
                body += StringUtils.join(notEnRouteRoutes, ",") + ": no buses en-route\n";
            }
            if (notScheduledRoutes.size() > 0) {
                body += StringUtils.join(notScheduledRoutes, ",") + ": not scheduled\n";
            }
            // as many observations as will fit, sorted by soonest to arrive out
        } else {
            for (String observationString : observationsByDistanceFromStopAcrossAllRoutes.values()) {
                String textToAdd = observationString + "\n";

                if (message.length() + body.length() + header.length() + alertsFooter.length()
                        + textToAdd.length() < MAX_SMS_CHARACTER_COUNT) {
                    body += textToAdd;
                } else {
                    break;
                }
            }
        }
    }

    if (_googleAnalytics != null) {
        try {
            _googleAnalytics.trackEvent("SMS", "Stop Realtime Response for Single Stop", _query);
        } catch (Exception e) {
            //discard
        }
    }

    return header + body + message + footer;
}

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/* w w w  .  jav a 2  s .  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:org.jactr.eclipse.ui.editor.assist.ACTRContentAssistProposer.java

public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    try {//from w ww  . ja v a  2s.c  om
        IRegion region = getPrefixRegion(viewer, offset);
        String prefix = getPrefix(viewer, region).toLowerCase();

        ASTPosition position = getContextualPosition(viewer, offset);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug(String.format("computing proposals for %d in (%d-%d), prefixed:%s, ASTPosition:%d",
                    offset, region.getOffset(), region.getOffset() + region.getLength(), prefix,
                    position != null ? position.getNode().getType() : -1));

        Map<String, CommonTree> recommendations = getRecommendationsUsingPositions(position, viewer, offset,
                prefix);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug(String.format("Yielded %d recommendations", recommendations.size()));

        if (recommendations.size() == 0)
            return null;

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Proposing " + recommendations);

        Point selection = viewer.getSelectedRange();

        TreeMap<CommonTree, ICompletionProposal> proposals = new TreeMap<CommonTree, ICompletionProposal>(
                new Comparator<CommonTree>() {

                    public int compare(CommonTree o1, CommonTree o2) {
                        if (o1 == o2)
                            return 0;
                        try {
                            int compare = ASTSupport.getName(o1).compareToIgnoreCase(ASTSupport.getName(o2));
                            if (compare != 0)
                                return compare;
                        } catch (Exception e) {
                            // its a variable (no name node)
                        }
                        // compare types..
                        int o1Type = o1.getType();
                        int o2Type = o2.getType();
                        if (o1Type < o2Type)
                            return -1;
                        if (o1Type > o2Type)
                            return 1;
                        return o1.hashCode() < o2.hashCode() ? -1 : 1;
                    }

                });
        // TreeMap<String, ICompletionProposal> proposals = new TreeMap<String,
        // ICompletionProposal>();

        for (Map.Entry<String, CommonTree> entry : recommendations.entrySet()) {
            int start = Math.min(region.getOffset(), selection.x);
            int length = region.getLength() + selection.y;
            CommonTree node = entry.getValue();
            String textToInsert = entry.getKey();
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Initial proposal (" + prefix + ") : " + textToInsert + " at " + start
                        + " replacing " + length);

            if (node != null)
                try {
                    textToInsert = ASTSupport.getName(entry.getValue());
                    if (prefix.length() > 0 && textToInsert.startsWith(prefix)) {
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("shifting start and length " + region.getLength());
                        textToInsert = textToInsert.substring(region.getLength());
                        start += region.getLength();
                        length -= region.getLength();
                    }
                } catch (Exception e) {
                }

            if (textToInsert.length() == 0)
                continue;

            if (textToInsert.equals(prefix))
                continue;

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Proposing : " + textToInsert + " at " + start + " replacing " + length);

            /*
             * note: the displayString is not being used, but rather the
             * textToInsert. this is because for some reason, the display string is
             * being used for the intermediary completion (say, when there are
             * multiple completions that might work). don't know why..
             */
            ACTRCompletionProposal proposal = new ACTRCompletionProposal(textToInsert, start, length,
                    textToInsert.length(), ACTRLabelProvider.getImageOfAST(node), textToInsert, null, null,
                    true);
            proposals.put(node, proposal);
        }

        return proposals.values().toArray(new ICompletionProposal[proposals.size()]);
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("something went wrong ", e);
    }

    return null;
}

From source file:org.mule.devkit.doclet.ClassInfo.java

public AttributeInfo[] selfAttributes() {
    if (mSelfAttributes == null) {
        TreeMap<FieldInfo, AttributeInfo> attrs = new TreeMap<FieldInfo, AttributeInfo>();

        // the ones in the class comment won't have any methods
        for (AttrTagInfo tag : comment().attrTags()) {
            FieldInfo field = tag.reference();
            if (field != null) {
                AttributeInfo attr = attrs.get(field);
                if (attr == null) {
                    attr = new AttributeInfo(this, field);
                    attrs.put(field, attr);
                }/*  w w  w .ja v  a  2 s.c om*/
                tag.setAttribute(attr);
            }
        }

        // in the methods
        for (MethodInfo m : selfMethods()) {
            for (AttrTagInfo tag : m.comment().attrTags()) {
                FieldInfo field = tag.reference();
                if (field != null) {
                    AttributeInfo attr = attrs.get(field);
                    if (attr == null) {
                        attr = new AttributeInfo(this, field);
                        attrs.put(field, attr);
                    }
                    tag.setAttribute(attr);
                    attr.methods.add(m);
                }
            }
        }

        // constructors too
        for (MethodInfo m : constructors()) {
            for (AttrTagInfo tag : m.comment().attrTags()) {
                FieldInfo field = tag.reference();
                if (field != null) {
                    AttributeInfo attr = attrs.get(field);
                    if (attr == null) {
                        attr = new AttributeInfo(this, field);
                        attrs.put(field, attr);
                    }
                    tag.setAttribute(attr);
                    attr.methods.add(m);
                }
            }
        }

        mSelfAttributes = attrs.values().toArray(new AttributeInfo[attrs.size()]);
        Arrays.sort(mSelfAttributes, AttributeInfo.comparator);
    }
    return mSelfAttributes;
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

private void handlerPreviewSiteList(HttpServletRequest request, HttpServletResponse response,
        AdminService admin, ExtendedMap formItems, User user)
        throws VerticalAdminException, VerticalEngineException {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("page", formItems.get("page"));
    int unitKey = formItems.getInt("selectedunitkey", -1);
    int siteKey = formItems.getInt("menukey", -1);

    int contentKey = formItems.getInt("contentkey", -1);
    int contentTypeKey;
    if (contentKey >= 0) {
        parameters.put("contentkey", contentKey);
        contentTypeKey = admin.getContentTypeKey(contentKey);
        parameters.put("sessiondata", formItems.getBoolean("sessiondata", false));
    } else {/*w  w  w  . j a  va 2 s  . c om*/
        contentTypeKey = formItems.getInt("contenttypekey", -1);
    }
    parameters.put("contenttypekey", contentTypeKey);

    int versionKey = formItems.getInt("versionkey", -1);
    if (versionKey != -1) {
        parameters.put("versionkey", versionKey);
    }

    Document doc = XMLTool.domparse(admin.getAdminMenu(user, -1));
    Element rootSitesElement = doc.getDocumentElement();
    Element[] allSiteElements = XMLTool.getElements(rootSitesElement);
    int defaultPageTemplateKey = -1;
    if (allSiteElements.length > 0) {
        TreeMap<String, Element> allSitesMap = new TreeMap<String, Element>();
        for (Element siteElement : allSiteElements) {
            int mKey = Integer.valueOf(siteElement.getAttribute("key"));
            if (admin.hasContentPageTemplates(mKey, contentTypeKey)) {
                String name = siteElement.getAttribute("name");
                allSitesMap.put(name, siteElement);
            }
            rootSitesElement.removeChild(siteElement);
        }

        if (allSitesMap.size() > 0) {
            Element firstMenuElem = allSitesMap.get(allSitesMap.firstKey());
            if (siteKey < 0) {
                siteKey = Integer.valueOf(firstMenuElem.getAttribute("key"));
            }

            for (Element siteElement : allSitesMap.values()) {
                rootSitesElement.appendChild(siteElement);
                int key = Integer.parseInt(siteElement.getAttribute("key"));
                if (key == siteKey) {
                    String defaultPageTemplateAttr = siteElement.getAttribute("defaultpagetemplate");
                    if (defaultPageTemplateAttr != null && !defaultPageTemplateAttr.equals("")) {
                        defaultPageTemplateKey = Integer.parseInt(defaultPageTemplateAttr);
                    }

                }
            }
        }
    }

    addCommonParameters(admin, user, request, parameters, unitKey, siteKey);

    if (siteKey >= 0) {
        int[] excludeTypeKeys = { 1, 2, 3, 4, 6 };
        String pageTemplateXML = admin.getPageTemplatesByMenu(siteKey, excludeTypeKeys);
        Document ptDoc = XMLTool.domparse(pageTemplateXML);
        XMLTool.mergeDocuments(doc, ptDoc, true);

        if (contentKey >= 0) {
            Document chDoc = XMLTool.domparse(admin.getContentHomes(contentKey));
            XMLTool.mergeDocuments(doc, chDoc, true);
        }

        if (formItems.containsKey("pagetemplatekey")) {
            int pageTemplateKey = formItems.getInt("pagetemplatekey");
            parameters.put("pagetemplatekey", String.valueOf(pageTemplateKey));
        } else {
            if (contentTypeKey >= 0) {
                org.jdom.Document pageTemplateDocument = XMLTool.jdomparse(pageTemplateXML);
                org.jdom.Element root = pageTemplateDocument.getRootElement();
                List<org.jdom.Element> pageTemplates = root.getChildren("pagetemplate");
                Set<KeyValue> pageTemplateKeys = new HashSet<KeyValue>();
                for (org.jdom.Element pageTemplate : pageTemplates) {

                    int pageTemplateKey = Integer.parseInt(pageTemplate.getAttribute("key").getValue());
                    org.jdom.Element contentTypesNode = pageTemplate.getChild("contenttypes");
                    List<org.jdom.Element> contentTypeElements = contentTypesNode.getChildren("contenttype");

                    if (checkMatchingContentType(contentTypeKey, contentTypeElements)) {
                        KeyValue keyValue = new KeyValue(pageTemplateKey, pageTemplate.getChildText("name"));
                        pageTemplateKeys.add(keyValue);
                    }
                }
                if (pageTemplateKeys.size() > 0) {
                    KeyValue[] keys = new KeyValue[pageTemplateKeys.size()];
                    keys = pageTemplateKeys.toArray(keys);
                    Arrays.sort(keys);
                    parameters.put("pagetemplatekey", keys[0].key);
                } else {
                    if (defaultPageTemplateKey < 0) {
                        throw new VerticalAdminException("Unable to resolve page template. "
                                + "No matching page template found and default page template is not set.");
                    }
                    parameters.put("pagetemplatekey", String.valueOf(defaultPageTemplateKey));
                }

            }
        }

        if (formItems.containsKey("menuitemkey")) {
            parameters.put("menuitemkey", formItems.get("menuitemkey"));
        }
    }

    transformXML(request, response, doc, "contenttype_preview_list.xsl", parameters);
}

From source file:com.projity.server.data.Serializer.java

public ProjectData serializeProject(Project project, Collection flatAssignments, Collection flatLinks,
        boolean incremental, SerializeOptions options) throws Exception {
    if (TMP_FILES)
        initTmpDir();/*ww w. jav a 2 s. c o  m*/
    if (project.isForceNonIncremental())
        incremental = false;
    boolean incrementalDistributions = incremental && !project.isForceNonIncrementalDistributions();

    //      calendars.clear();
    Count projectCount = new Count("Project");
    //if (globalIdsOnly) makeGLobal(project);
    ProjectData projectData = (ProjectData) serialize(project, ProjectData.FACTORY, projectCount);
    if (project.isForceNonIncremental())
        projectData.setVersion(0);
    projectData.setMaster(project.isMaster());
    //        projectData.setExternalId(project.getExternalId());

    //exposed attributes
    //        projectData.setAttributes(SpreadSheetFieldArray.convertFields(project, "projectExposed", new Transformer(){
    //           public Object transform(Object value) {
    //              if (value instanceof Money) return ((Money)value).doubleValue();
    //              return null;
    //           }
    //        }));

    projectCount.dump();

    //resources
    Map resourceMap = saveResources(project, projectData);

    //tasks
    saveTasks(project, projectData, resourceMap, flatAssignments, flatLinks, incremental, options);

    //distribution
    long t = System.currentTimeMillis();
    Collection<DistributionData> dist = (Collection<DistributionData>) (new DistributionConverter())
            .createDistributionData(project, incrementalDistributions);
    if (dist == null) {
        dist = new ArrayList<DistributionData>();
    }
    projectData.setDistributions(dist);
    projectData.setIncrementalDistributions(incrementalDistributions);

    TreeMap<DistributionData, DistributionData> distMap = project.getDistributionMap();
    if (distMap == null) {
        distMap = new TreeMap<DistributionData, DistributionData>(new DistributionComparator());
        project.setDistributionMap(distMap);
    }
    TreeMap<DistributionData, DistributionData> newDistMap = new TreeMap<DistributionData, DistributionData>(
            new DistributionComparator());
    //ArrayList<DistributionData> toInsertInOld=new ArrayList<DistributionData>();

    //insert, update dist
    for (Iterator<DistributionData> i = dist.iterator(); i.hasNext();) {
        DistributionData d = i.next();
        if (incrementalDistributions) {
            DistributionData oldD = distMap.get(d);
            if (oldD == null) {
                d.setStatus(DistributionData.INSERT);
            } else {
                if (oldD.getWork() == d.getWork() && oldD.getCost() == d.getCost()) {
                    //System.out.println(d+" did not change");
                    d.setStatus(0);
                    i.remove();
                } else
                    d.setStatus(DistributionData.UPDATE);
            }
        } else {
            d.setStatus(DistributionData.INSERT);
        }
        newDistMap.put(d, d);
    }
    //remove dist
    if (incrementalDistributions && distMap.size() > 0) {
        Set<Long> noChangeTaskIds = new HashSet<Long>();

        Task task;
        for (Iterator i = project.getTaskOutlineIterator(); i.hasNext();) {
            task = (Task) i.next();
            if (incremental && !task.isDirty())
                noChangeTaskIds.add(task.getUniqueId());
        }
        //           for (Iterator i=projectData.getTasks().iterator();i.hasNext();){
        //              TaskData task=(TaskData)i.next();
        //              if (!task.isDirty()) noChangeTaskIds.add(task.getUniqueId());
        //           }
        for (Iterator<DistributionData> i = distMap.values().iterator(); i.hasNext();) {
            DistributionData d = i.next();
            if (newDistMap.containsKey(d))
                continue;
            if (noChangeTaskIds.contains(d.getTaskId())) {
                d.setStatus(0);
                newDistMap.put(d, d);
            } else {
                d.setStatus(DistributionData.REMOVE);
                dist.add(d);
            }
        }
    }
    project.setNewDistributionMap(newDistMap);
    System.out.println("Distributions generated in " + (System.currentTimeMillis() - t) + " ms");

    // send project field values to server too
    HashMap fieldValues = FieldValues.getValues(FieldDictionary.getInstance().getProjectFields(), project);
    if (project.getContainingSubprojectTask() != null) { // special case in which we want to use the duration from subproject task
        Object durationFieldValue = Configuration.getFieldFromId("Field.duration")
                .getValue(project.getContainingSubprojectTask(), null);
        fieldValues.put("Field.duration", durationFieldValue);
    }
    projectData.setFieldValues(fieldValues);
    projectData.setGroup(project.getGroup());
    projectData.setDivision(project.getDivision());
    projectData.setExpenseType(project.getExpenseType());
    projectData.setProjectType(project.getProjectType());
    projectData.setProjectStatus(project.getProjectStatus());
    projectData.setExtraFields(project.getExtraFields());
    projectData.setAccessControlPolicy(project.getAccessControlPolicy());
    projectData.setCreationDate(project.getCreationDate());
    projectData.setLastModificationDate(project.getLastModificationDate());
    //     System.out.println("done serialize project " + project);

    //        Collection<DistributionData> dis=(Collection<DistributionData>)projectData.getDistributions();
    //        for (DistributionData d: dis) System.out.println("Dist: "+d.getTimeId()+", "+d.getType()+", "+d.getStatus());

    //        project.setNewTaskIds(null);
    //        if (projectData.getTasks()!=null){
    //           Set<Long> ids=new HashSet<Long>();
    //           project.setNewTaskIds(ids);
    //           for (TaskData task:(Collection<TaskData>)projectData.getTasks()){
    //              ids.add(task.getUniqueId());
    //           }
    //        }
    //        long[] unchangedTasks=projectData.getUnchangedTasks();
    //        if (unchangedTasks!=null){
    //           Set<Long> ids=project.getNewTaskIds();
    //           if (ids==null){
    //              ids=new HashSet<Long>();
    //              project.setNewTaskIds(ids);
    //           }
    //           for (int i=0;i<unchangedTasks.length;i++) ids.add(unchangedTasks[i]);
    //        }
    //
    //        project.setNewLinkIds(null);
    //        if (flatLinks!=null){
    //           Set<DependencyKey> ids=new HashSet<DependencyKey>();
    //           project.setNewLinkIds(ids);
    //           for (LinkData link:(Collection<LinkData>)flatLinks){
    //              ids.add(new DependencyKey(link.getPredecessorId(),link.getSuccessorId()/*,link.getExternalId()*/));
    //           }
    //        }
    //        long[] unchangedLinks=projectData.getUnchangedLinks();
    //        if (unchangedLinks!=null){
    //           Set<DependencyKey> ids=project.getNewLinkIds();
    //           if (ids==null){
    //              ids=new HashSet<DependencyKey>();
    //              project.setNewLinkIds(ids);
    //           }
    //           for (int i=0;i<unchangedLinks.length;i+=2) ids.add(new DependencyKey(unchangedLinks[i],unchangedLinks[i+1]));
    //        }

    //project.setNewIds(); //claur - useful ?

    return projectData;

}