Example usage for org.springframework.util StringUtils collectionToDelimitedString

List of usage examples for org.springframework.util StringUtils collectionToDelimitedString

Introduction

In this page you can find the example usage for org.springframework.util StringUtils collectionToDelimitedString.

Prototype

public static String collectionToDelimitedString(@Nullable Collection<?> coll, String delim, String prefix,
        String suffix) 

Source Link

Document

Convert a Collection to a delimited String (e.g.

Usage

From source file:org.jasig.portlet.contacts.context.MissingContextException.java

public MissingContextException(Collection<String> missingAttributes) {
    this("Missing context attributes : needs ("
            + StringUtils.collectionToDelimitedString(missingAttributes, ",", "'", "'") + ")");
}

From source file:org.cloudfoundry.maven.common.CommonUtils.java

/**
 * Convert a List of Strings to a comma delimited String.
 *
 * @param list/*from  www  .  ja v a 2s  .c o  m*/
 * @return Returns the List as a comma delimited String. Returns an empty
 *         String for a Null or empty list.
 */
public static String collectionToCommaDelimitedString(Collection<String> list, String prefix) {
    return StringUtils.collectionToDelimitedString(list, ", ", prefix, "");
}

From source file:org.jasig.portlet.contacts.context.impl.ContactContextImpl.java

public String toString() {

    List<String> outList = new ArrayList<String>();

    for (ContextProvider prov : contextProviders) {
        for (Map.Entry entry : prov.getContext().entrySet()) {
            outList.add(entry.getKey() + "=" + entry.getValue());
        }//from   w w w  . j a  v  a  2  s .  c om

    }

    String out = StringUtils.collectionToDelimitedString(outList, ",", "[", "]");
    return out;
}

From source file:com.yoho.core.trace.instrument.web.TraceInterceptor.java

/**
 * Override to add annotations not defined in {@link TraceKeys}.
 *///w ww  .j  a  v a 2 s  .  com
protected void addRequestTags(HttpServletRequest request) {

    //add uid
    this.tracer.addTag(this.traceKeys.getYoho().getUid(), request.getParameter("uid"));

    //add http
    String uri = this.urlPathHelper.getPathWithinApplication(request);
    this.tracer.addTag(this.traceKeys.getHttp().getUrl(), getFullUrl(request));
    this.tracer.addTag(this.traceKeys.getHttp().getHost(), request.getServerName());
    this.tracer.addTag(this.traceKeys.getHttp().getPath(), uri);
    this.tracer.addTag(this.traceKeys.getHttp().getMethod(), request.getMethod());
    for (String name : this.traceKeys.getHttp().getHeaders()) {
        Enumeration<String> values = request.getHeaders(name);
        if (values.hasMoreElements()) {
            String key = this.traceKeys.getHttp().getPrefix() + name.toLowerCase();
            ArrayList<String> list = Collections.list(values);
            String value = list.size() == 1 ? list.get(0)
                    : StringUtils.collectionToDelimitedString(list, ",", "'", "'");
            this.tracer.addTag(key, value);
        }
    }
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private Map<String, Object> createTimeseries(String userPrincipalName, DataSeriesSource dss,
        List<Filter> filters, GroupingImpl group, String timeResolution, Integer prepull,
        String graphTimeSeriesUrl, final Collection<Record> records, final List<Dimension> accumulations,
        final List<Dimension> timeseriesDenominators, String detectorClass, boolean includeDetails,
        boolean displayIntervalEndDate, GraphDataInterface graphData, TimeZone clientTimezone) {

    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, ResolutionHandler> resolutionHandlers = null;
    result.put("success", false);
    try {//from  w ww . j  a va2s .  c  o  m
        GroupingDimension grpdim = dss.getGroupingDimension(group.getId());
        resolutionHandlers = grpdim.getResolutionsMap();
        String dateFieldName = group.getId();
        Date startDate = null;
        Date endDate = null;
        if (grpdim != null
                && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) {
            for (Filter f : filters) {
                if (f instanceof OneArgOpFilter) {
                    OneArgOpFilter of = (OneArgOpFilter) f;
                    if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains(">="))) {
                        startDate = (Date) of.getArguments().get(0);
                    } else if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains("<="))) {
                        endDate = (Date) of.getArguments().get(0);
                    }
                }
            }
        }
        //union accumulations to get all results
        List<Dimension> dimensions = new ArrayList<Dimension>(
                ControllerUtils.unionDimensions(accumulations, timeseriesDenominators));

        int timeOffsetMillies = 0;
        String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
        if (timezoneEnabledString.equalsIgnoreCase("true")) {
            timeOffsetMillies = (clientTimezone.getRawOffset() - clientTimezone.getDSTSavings())
                    - (TimeZone.getDefault().getRawOffset() - TimeZone.getDefault().getDSTSavings());
        }
        Calendar startDayCal = Calendar.getInstance(clientTimezone);
        startDayCal.setTime(startDate);
        startDayCal.add(Calendar.MILLISECOND, timeOffsetMillies);

        //get data grouped by group dimension
        List<AccumPoint> points = extractAccumulationPoints(userPrincipalName, dss, records,
                startDayCal.getTime(), endDate, dimensions, group, resolutionHandlers);
        if (points.size() > 0) {
            DateFormat dateFormat = getDateFormat(timeResolution); //dateFormat.setTimeZone(timezone);
            DateFormat tmpDateFormat = (DateFormat) dateFormat.clone();
            tmpDateFormat.setTimeZone(clientTimezone);

            // number format for level
            NumberFormat numFormat3 = NumberFormat.getNumberInstance();
            numFormat3.setMinimumFractionDigits(0);
            numFormat3.setMaximumFractionDigits(3);

            // number format for expected count
            NumberFormat numFormat1 = NumberFormat.getNumberInstance();
            numFormat1.setMinimumFractionDigits(0);
            numFormat1.setMaximumFractionDigits(1);

            Calendar cal = new GregorianCalendar();
            cal.setTime(startDayCal.getTime());
            //offset start date to match prepull offset
            if (timeResolution.equals("weekly")) {
                cal.add(Calendar.DATE, (7 * prepull));
            } else if (timeResolution.equals("daily")) {
                cal.add(Calendar.DATE, prepull);
            }
            Date queryStartDate = cal.getTime();

            //-- Handles Denominator Types -- //
            double[] divisors = new double[points.size()];
            double multiplier = 1.0;
            boolean percentBased = false;
            String yAxisLabel = messageSource.getDataSourceMessage("graph.count", dss);

            boolean isDetectionDetector = !NoDetectorDetector.class.getName().equalsIgnoreCase(detectorClass);

            //if there is a denominator we need to further manipulate the data
            if (timeseriesDenominators != null && !timeseriesDenominators.isEmpty()) {
                // divisor is the sum of timeseriesDenominators
                divisors = totalSeriesValues(points, timeseriesDenominators);
                multiplier = 100.0;
                percentBased = true;
                yAxisLabel = messageSource.getDataSourceMessage("graph.percent", dss);
            } else {
                //the query is for total counts
                Arrays.fill(divisors, 1.0);
            }

            double[][] allCounts = new double[accumulations.size()][];
            int[][] allColors = new int[accumulations.size()][];
            String[][] allAltTexts = new String[accumulations.size()][];
            String[] dates = new String[] { "" };
            double[][] allExpecteds = new double[accumulations.size()][];
            double[][] allLevels = new double[accumulations.size()][];
            String[][] allLineSetURLs = new String[accumulations.size()][];
            String[][] allSwitchInfo = new String[accumulations.size()][];
            String[] lineSetLabels = new String[accumulations.size()];
            boolean[] displayAlerts = new boolean[accumulations.size()];

            //get all results
            Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
            Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);
            Collection<String> accIds = ControllerUtils.getDimensionIdsFromCollection(dss.getAccumulations());
            //remove extra accumulations in the result set using string ids
            dimIds.removeAll(accIds);

            //for each accumulation we run detection and gather results
            int aIndex = 0;
            for (Dimension accumulation : accumulations) {
                String accumId = accumulation.getId();

                // use display name if it has one, otherwise translate its ID
                String accumIdTranslated = accumulation.getDisplayName();
                if (accumIdTranslated == null) {
                    accumIdTranslated = messageSource.getDataSourceMessage(accumulation.getId(), dss);
                }

                TemporalDetectorInterface TDI = (TemporalDetectorInterface) DetectorHelper
                        .createObject(detectorClass);
                TemporalDetectorSimpleDataObject TDDO = new TemporalDetectorSimpleDataObject();

                int[] colors;
                double[] counts;
                String[] altTexts;
                double[] expecteds;
                double[] levels;
                String[] switchInfo;
                String[] urls;

                //pull the counts from the accum array points
                double[] seriesDoubleArray = generateSeriesValues(points, accumId);

                //run divisor before detection
                for (int i = 0; i < seriesDoubleArray.length; i++) {
                    double div = divisors[i];
                    if (div == 0) {
                        seriesDoubleArray[i] = 0.0;
                    } else {
                        seriesDoubleArray[i] = (seriesDoubleArray[i] / div) * multiplier;
                    }
                }

                //run detection
                TDDO.setCounts(seriesDoubleArray);
                TDDO.setStartDate(startDate);
                TDDO.setTimeResolution(timeResolution);

                try {
                    TDI.runDetector(TDDO);
                } catch (Exception e) {
                    String errorMessage = "Failure to create Timeseries";
                    if (e.getMessage() != null) {
                        errorMessage = errorMessage + ":<BR>" + e.getMessage();
                    }
                    result.put("message", errorMessage);
                    result.put("success", false);
                    return result;
                }

                TDDO.cropStartup(prepull);
                counts = TDDO.getCounts();
                int tddoLength = counts.length;

                if (!DAILY.equalsIgnoreCase(timeResolution)) {
                    //toggle between start date and end date
                    //TDDO.setDates(getOurDates(startDate, endDate, tddoLength, timeResolution));
                    TDDO.setDates(getOurDates(queryStartDate, endDate, tddoLength, timeResolution,
                            displayIntervalEndDate));
                }
                double[] tcolors = TDDO.getColors();

                Date[] tdates = TDDO.getDates();
                altTexts = TDDO.getAltTexts();
                expecteds = TDDO.getExpecteds();
                levels = TDDO.getLevels();
                switchInfo = TDDO.getSwitchInfo();
                colors = new int[tddoLength];
                dates = new String[tddoLength];
                urls = new String[tddoLength];

                //add the accumId for the current series
                dimIds.add(accumId);

                StringBuilder jsCall = new StringBuilder();
                jsCall.append("javascript:OE.report.datasource.showDetails({");
                jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
                //specify results
                jsCall.append(",results:[")
                        .append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")).append(']');
                //specify accumId
                jsCall.append(",accumId:'").append(accumId).append("'");

                addJavaScriptFilters(jsCall, filters, dateFieldName);

                //this builds urls and hover texts
                int startDay = getWeekStartDay(resolutionHandlers);

                Calendar c = Calendar.getInstance(clientTimezone);

                //               Calendar curr = Calendar.getInstance();
                for (int i = 0; i < tddoLength; i++) {
                    colors[i] = (int) tcolors[i];

                    // For a time series data point, set time to be current server time
                    // This will allow us to convert this data point date object to be request timezone date
                    c.setTime(tdates[i]);
                    c.add(Calendar.MILLISECOND, timeOffsetMillies);

                    if (timeResolution.equals(WEEKLY)) {
                        dates[i] = dateFormatWeekPart.format(tdates[i]) + "-W"
                                + PgSqlDateHelper.getWeekOfYear(startDay, c) + "-"
                                + PgSqlDateHelper.getYear(startDay, c);
                    } else {
                        dates[i] = tmpDateFormat.format(c.getTime());
                    }

                    altTexts[i] = "(" + accumIdTranslated + ") " + // Accum
                            "Date: " + dates[i] + // Date
                            ", Level: " + numFormat3.format(levels[i]) + // Level
                            ", Count: " + ((int) counts[i]) + // Count
                            ", Expected: " + numFormat1.format(expecteds[i]); // Expected

                    if (switchInfo != null) {
                        altTexts[i] += ", Switch: " + switchInfo[i] + ", ";
                    }

                    // build the click through url
                    StringBuilder tmp = new StringBuilder(jsCall.toString());

                    // add the date field with start and end dates from the data point
                    if (!DAILY.equalsIgnoreCase(timeResolution)) {
                        Calendar timeSet = Calendar.getInstance(clientTimezone);
                        timeSet.setTime(tdates[i]);

                        if (WEEKLY.equalsIgnoreCase(timeResolution)) {
                            timeSet.set(Calendar.DAY_OF_WEEK, startDay + 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.add(Calendar.DAY_OF_YEAR, 6);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (MONTHLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            timeSet.add(Calendar.MONTH, 1);
                            timeSet.add(Calendar.DAY_OF_YEAR, -1);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            // set first day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (YEARLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DATE, 31);
                            timeSet.add(Calendar.MONTH, Calendar.DECEMBER);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.set(Calendar.DATE, 1);
                            timeSet.add(Calendar.MONTH, Calendar.JANUARY);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        }
                    } else {
                        // compute end date for individual data points based on the selected resolution
                        //                     detailsPointEndDate = computeEndDate(tdates[i],timeResolution);
                        // add the date field with start and end dates from the data point
                        tmp.append(",").append(dateFieldName).append("_start:'").append(tdates[i].getTime())
                                .append("'");
                        tmp.append(",").append(dateFieldName).append("_end:'").append(tdates[i].getTime())
                                .append("'");
                    }
                    tmp.append("});");
                    urls[i] = tmp.toString();
                }

                allCounts[aIndex] = counts;
                allColors[aIndex] = colors;
                allAltTexts[aIndex] = altTexts;
                allExpecteds[aIndex] = expecteds;
                allLevels[aIndex] = levels;
                allLineSetURLs[aIndex] = urls;
                allSwitchInfo[aIndex] = switchInfo;
                lineSetLabels[aIndex] = accumIdTranslated;
                displayAlerts[aIndex] = isDetectionDetector;
                aIndex++;

                //remove the accumId for the next series
                dimIds.remove(accumId);
            }

            GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
            GraphController gc = getGraphController(null, hndl, userPrincipalName);
            //TODO figure out why I (hodancj1) added this to be accumulation size ~Feb 2012
            // gc.setMaxLegendItems(accumulations.size());

            graphData.setShowSingleAlertLegends(isDetectionDetector);
            graphData.setCounts(allCounts);
            graphData.setColors(allColors);
            graphData.setAltTexts(allAltTexts);
            graphData.setXLabels(dates);
            graphData.setExpecteds(allExpecteds);
            graphData.setLevels(allLevels);
            graphData.setLineSetURLs(allLineSetURLs);
            graphData.setLineSetLabels(lineSetLabels);
            graphData.setDisplayAlerts(displayAlerts);
            // graphData.setDisplaySeverityAlerts(displayAlerts);
            graphData.setPercentBased(percentBased);

            graphData.setXAxisLabel(messageSource.getDataSourceMessage(group.getResolution(), dss));
            graphData.setYAxisLabel(yAxisLabel);

            int maxLabels = graphData.getGraphWidth() / 30;
            graphData.setMaxLabeledCategoryTicks(Math.min(maxLabels, allCounts[0].length));

            StringBuffer sb = new StringBuffer();
            GraphObject graph = gc.writeTimeSeriesGraph(sb, graphData, true, true, false, graphTimeSeriesUrl);

            result.put("html", sb.toString());

            //added to build method calls from javascript
            Map<String, Object> graphConfig = new HashMap<String, Object>();
            graphConfig.put("address", graphTimeSeriesUrl);
            graphConfig.put("graphDataId", graph.getGraphDataId());
            graphConfig.put("imageMapName", graph.getImageMapName());

            graphConfig.put("graphTitle", graphData.getGraphTitle());
            graphConfig.put("xAxisLabel", graphData.getXAxisLabel());
            graphConfig.put("yAxisLabel", graphData.getYAxisLabel());
            graphConfig.put("xLabels", graphData.getXLabels());
            graphConfig.put("graphWidth", graphData.getGraphWidth());
            graphConfig.put("graphHeight", graphData.getGraphHeight());

            graphConfig.put("yAxisMin", graph.getYAxisMin());
            graphConfig.put("yAxisMax", graph.getYAxisMax());

            // fix invalid JSON coming from GraphController
            String dataSeriesJson = graph.getDataSeriesJSON().replaceFirst("\\{", "")
                    // remove trailing "}"
                    .substring(0, graph.getDataSeriesJSON().length() - 2);

            // read malformed JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory jsonFactory = mapper.getJsonFactory()
                    .configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
                    .configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            JsonParser jsonParser = jsonFactory.createJsonParser(dataSeriesJson);

            // array of String -> Object maps
            TypeReference<Map<String, Object>[]> dataSeriesType = new TypeReference<Map<String, Object>[]>() {
            };

            // write JSON as Map so that it can be serialized properly back to JSON
            Map<String, Object>[] seriesMap = mapper.readValue(jsonParser, dataSeriesType);
            graphConfig.put("dataSeriesJSON", seriesMap);

            if (includeDetails) {
                int totalPoints = 0;
                List<HashMap<String, Object>> details = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> detail;
                for (int i = 0; i < allCounts.length; i++) {
                    for (int j = 0; j < allCounts[i].length; j++) {
                        totalPoints++;
                        detail = new HashMap<String, Object>();
                        detail.put("Date", dates[j]);
                        detail.put("Series", lineSetLabels[i]);
                        detail.put("Level", allLevels[i][j]);
                        detail.put("Count", allCounts[i][j]);
                        if (!ArrayUtils.isEmpty(allExpecteds[i])) {
                            detail.put("Expected", allExpecteds[i][j]);
                        }
                        if (!ArrayUtils.isEmpty(allSwitchInfo[i])) {
                            detail.put("Switch", allSwitchInfo[i][j]);
                        }
                        detail.put("Color", allColors[i][j]);
                        details.add(detail);
                    }
                }
                result.put("detailsTotalRows", totalPoints);
                result.put("details", details);
            }
            result.put("graphConfiguration", graphConfig);
            result.put("success", true);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("<h2>" + messageSource.getDataSourceMessage("graph.nodataline1", dss) + "</h2>");
            sb.append("<p>" + messageSource.getDataSourceMessage("graph.nodataline2", dss) + "</p>");
            result.put("html", sb.toString());
            result.put("success", true);
        }
    } catch (Exception e) {
        log.error("Failure to create Timeseries", e);
    }
    return result;
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private GraphObject createGraph(OeDataSource dataSource, final String userPrincipalName,
        final Collection<Record> records, final Dimension dimension, final Dimension filter,
        final Dimension accumulation, DefaultGraphData data, ChartModel chart, List<Filter> filters) {

    String filterId = (filter == null) ? dimension.getId() : filter.getId();
    Map<String, String> possibleKeyValueMap = null;
    if (dimension.getPossibleValuesConfiguration() != null
            && dimension.getPossibleValuesConfiguration().getData() != null) {
        List<List<Object>> dataMap = dimension.getPossibleValuesConfiguration().getData();
        possibleKeyValueMap = new HashMap<String, String>();
        for (int i = 0; i < dataMap.size(); i++) {
            String dispVal = dataMap.get(i).size() == 2 ? dataMap.get(i).get(1).toString()
                    : dataMap.get(i).get(0).toString();
            possibleKeyValueMap.put(dataMap.get(i).get(0).toString(), dispVal);
        }//w w  w .j  av  a  2  s.  co m
    }

    GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
    GraphObject graph = null;

    Color[] colorsFromHex = null;
    //only set an array if they provided one
    if (!ArrayUtils.isEmpty(chart.getGraphBaseColors())) {
        colorsFromHex = ControllerUtils.getColorsFromHex(Color.BLUE, chart.getGraphBaseColors());
        //TODO when we limit the series these colors need augmented.  Create a map of id = graphbasecolor[index] first, then use that map to create a
        //new graph base color array that combines the parameter list with the default list...
        data.setGraphBaseColors(colorsFromHex);
    }

    GraphController gc = getGraphController(null, hndl, userPrincipalName);

    List<Record> recs = new ArrayList<Record>(records);

    String otherLabel = messageSource.getDataSourceMessage("graph.category.other", dataSource);

    LinkedHashMap<String, ChartData> recordMap = getRecordMap(recs, accumulation.getId(), dimension.getId(),
            filterId);
    //perform series limit
    recordMap = ControllerUtils.getSortedAndLimitedChartDataMap(recordMap, chart.getCategoryLimit(),
            otherLabel);

    //if there is no data (all zeros for a pie chart) the chart will not display anything
    if (!ControllerUtils.isCollectionValued(getCountsForChart(recordMap)) && !chart.isShowNoDataGraph()) {
        //this will hide the title and message if there is no data
        data.setGraphTitle("");
        data.setNoDataMessage("");
    }

    // Create urls for each slice/bar
    DataSeriesSource dss = null;
    StringBuilder jsCall = new StringBuilder();
    jsCall.append("javascript:OE.report.datasource.showDetails({");

    if (dataSource instanceof DataSeriesSource) {
        dss = (DataSeriesSource) dataSource;

        Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
        Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);

        Collection<Dimension> accums = new ArrayList<Dimension>(dss.getAccumulations());

        for (Dimension d : accums) {
            if (dimIds.contains(d.getId()) && d.getId().equals(accumulation.getId())) {

            } else {
                dimIds.remove(d.getId());
            }
        }

        jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
        //specify results
        jsCall.append(",results:[").append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'"))
                .append(']');
        //specify accumId
        jsCall.append(",accumId:'").append(accumulation.getId()).append("'");

        addJavaScriptFilters(jsCall, filters, dimension.getId());
    }

    int rSize = recordMap.size();
    int aSize = 1;
    String[] lbl = new String[rSize];
    String[][] txtb = new String[1][rSize];
    double[][] bardat = new double[aSize][rSize];
    String[][] txtp = new String[rSize][1];
    double[][] piedat = new double[rSize][aSize];
    String[][] urlsP = new String[rSize][1];
    String[][] urlsB = new String[1][rSize];
    int i = 0;
    double totalCount = 0;
    DecimalFormat df = new DecimalFormat("#.##");

    for (String key : recordMap.keySet()) {
        if (recordMap.get(key) != null && recordMap.get(key).getCount() != null
                && !recordMap.get(key).getCount().isNaN()) {
            totalCount += recordMap.get(key).getCount();
        }
    }

    for (String key : recordMap.keySet()) {
        Double dubVal = recordMap.get(key).getCount();
        String strPercentVal = df.format(100 * dubVal / totalCount);
        lbl[i] = recordMap.get(key).getName();
        //create bar data set
        bardat[0][i] = dubVal;
        txtb[0][i] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)";
        if (lbl[i].length() > DEFAULT_LABEL_LENGTH) {
            lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "...";
        }
        //create pie data set
        piedat[i][0] = dubVal;
        txtp[i][0] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)";
        if (lbl[i].length() > DEFAULT_LABEL_LENGTH) {
            lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "...";
        }
        //TODO all "Others" to return details of all results except for those in recordMap.keyset
        //We need a "Not" filter
        if (!otherLabel.equals(key)) {
            if (dataSource instanceof DataSeriesSource) {
                if (dimension.getId().equals(filterId) && possibleKeyValueMap != null) {
                    if (possibleKeyValueMap.containsKey(key)) {
                        urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                        urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                    } else {
                        urlsP[i][0] = jsCall.toString() + "});";
                        urlsB[0][i] = jsCall.toString() + "});";
                    }
                } else {
                    if (key == null || key.equals("")
                            || key.equals(messageSource.getMessage("graph.dimension.null", "Empty Value"))) {
                        // TODO: This is when we have an ID field also marked as isResult:true and the value is null
                        // We can not provide url param filterId:null as field can be numeric and we get a java.lang.NumberFormatException...
                        urlsP[i][0] = jsCall.toString() + "});";
                        urlsB[0][i] = jsCall.toString() + "});";
                    } else {
                        urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                        urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                    }
                }
            }
        }

        i++;
    }

    if (BAR.equalsIgnoreCase(chart.getType())) {
        data.setCounts(bardat);
        data.setXLabels(lbl);
        data.setMaxLabeledCategoryTicks(rSize);
        data.setAltTexts(txtb);
        if (jsCall.length() > 0) {
            data.setLineSetURLs(urlsB);
        }
        //TODO add encoding?
        graph = gc.createBarGraph(data, false, true);
    } else if (PIE.equalsIgnoreCase(chart.getType())) {
        data.setCounts(piedat);
        data.setLineSetLabels(lbl);
        data.setAltTexts(txtp);
        if (jsCall.length() > 0) {
            data.setLineSetURLs(urlsP);
        }
        graph = gc.createPieGraph(data, Encoding.PNG_WITH_TRANSPARENCY);
    }
    return graph;
}

From source file:org.springframework.cloud.deployer.resource.maven.MavenArtifactResolver.java

/**
 * Resolve an artifact and return its location in the local repository. Aether performs the normal
 * Maven resolution process ensuring that the latest update is cached to the local repository.
 * In addition, if the {@link MavenProperties#resolvePom} flag is <code>true</code>,
 * the POM is also resolved and cached.//from w ww  . ja  v a2s  .  com
 * @param resource the {@link MavenResource} representing the artifact
 * @return a {@link FileSystemResource} representing the resolved artifact in the local repository
 * @throws IllegalStateException if the artifact does not exist or the resolution fails
 */
Resource resolve(MavenResource resource) {
    Assert.notNull(resource, "MavenResource must not be null");
    validateCoordinates(resource);
    RepositorySystemSession session = newRepositorySystemSession(this.repositorySystem,
            this.properties.getLocalRepository());
    ArtifactResult resolvedArtifact;
    try {
        List<ArtifactRequest> artifactRequests = new ArrayList<>(2);
        if (properties.isResolvePom()) {
            artifactRequests.add(
                    new ArtifactRequest(toPomArtifact(resource), this.remoteRepositories, JavaScopes.RUNTIME));
        }
        artifactRequests
                .add(new ArtifactRequest(toJarArtifact(resource), this.remoteRepositories, JavaScopes.RUNTIME));

        List<ArtifactResult> results = this.repositorySystem.resolveArtifacts(session, artifactRequests);
        resolvedArtifact = results.get(results.size() - 1);
    } catch (ArtifactResolutionException e) {

        ChoiceFormat pluralizer = new ChoiceFormat(new double[] { 0d, 1d, ChoiceFormat.nextDouble(1d) },
                new String[] { "repositories: ", "repository: ", "repositories: " });
        MessageFormat messageFormat = new MessageFormat(
                "Failed to resolve MavenResource: {0}. Configured remote {1}: {2}");
        messageFormat.setFormat(1, pluralizer);
        String repos = properties.getRemoteRepositories().isEmpty() ? "none"
                : StringUtils.collectionToDelimitedString(properties.getRemoteRepositories().keySet(), ",", "[",
                        "]");
        throw new IllegalStateException(messageFormat
                .format(new Object[] { resource, properties.getRemoteRepositories().size(), repos }), e);
    }
    return toResource(resolvedArtifact);
}

From source file:org.springframework.cloud.sleuth.instrument.web.TraceFilter.java

/** Override to add annotations not defined in {@link TraceKeys}. */
protected void addRequestTags(Span span, HttpServletRequest request) {
    String uri = this.urlPathHelper.getPathWithinApplication(request);
    this.httpTraceKeysInjector.addRequestTags(span, getFullUrl(request), request.getServerName(), uri,
            request.getMethod());//from w  ww.  ja  v a2s  .  c  o  m
    for (String name : this.traceKeys.getHttp().getHeaders()) {
        Enumeration<String> values = request.getHeaders(name);
        if (values.hasMoreElements()) {
            String key = this.traceKeys.getHttp().getPrefix() + name.toLowerCase();
            ArrayList<String> list = Collections.list(values);
            String value = list.size() == 1 ? list.get(0)
                    : StringUtils.collectionToDelimitedString(list, ",", "'", "'");
            this.httpTraceKeysInjector.tagSpan(span, key, value);
        }
    }
}