Example usage for java.lang Comparable toString

List of usage examples for java.lang Comparable toString

Introduction

In this page you can find the example usage for java.lang Comparable toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java

private AbstractDataset getPieDataset(Report report) {
    List<Stat> reportData = report.getReportData();

    // fill dataset
    DefaultPieDataset dataSet = new DefaultPieDataset();
    String dataSource = report.getReportDefinition().getReportParams().getHowChartSource();
    //int total = 0;
    double total = 0;
    for (Stat s : reportData) {
        Comparable key = getStatValue(s, dataSource);
        if (key != null) {
            try {
                Number existingValue = dataSet.getValue(key);
                dataSet.setValue(key, getTotalValue(existingValue, s, report));
                total += getTotalValue(s, report).doubleValue();
            } catch (UnknownKeyException e) {
                dataSet.setValue(key, getTotalValue(s, report));
                total += getTotalValue(s, report).doubleValue();
            }//www . j ava2  s. c om
        }
    }

    // sort
    dataSet.sortByValues(SortOrder.DESCENDING);

    // fill in final key values in dataset
    // show only top values (aggregate remaining in 'others')
    int maxDisplayedItems = 10;
    int currItem = 1;
    Number othersValues = Integer.valueOf(0);
    List<Comparable> keys = dataSet.getKeys();
    for (Comparable key : keys) {
        Number existingValue = dataSet.getValue(key);
        if (currItem < maxDisplayedItems) {
            // re-compute values
            double percentage = (double) existingValue.doubleValue() * 100 / total;
            double valuePercentage = Util.round(percentage, (percentage > 0.1) ? 1 : 2);
            // replace key with updated label
            StringBuilder keyStr = new StringBuilder(key.toString());
            keyStr.append(' ');
            keyStr.append(valuePercentage);
            keyStr.append("% (");
            if ((double) existingValue.intValue() == existingValue.doubleValue())
                keyStr.append(existingValue.intValue());
            else
                keyStr.append(existingValue.doubleValue());
            keyStr.append(")");
            dataSet.remove(key);
            dataSet.setValue(keyStr.toString(), existingValue);
        } else {
            othersValues = Integer.valueOf(othersValues.intValue() + existingValue.intValue());
            dataSet.remove(key);
        }
        currItem++;
    }
    // compute "Others" value
    if (othersValues.intValue() > 0) {
        double percentage = (double) othersValues.doubleValue() * 100 / total;
        double valuePercentage = Util.round(percentage, (percentage > 0.1) ? 1 : 2);
        // replace key with updated label
        StringBuilder keyStr = new StringBuilder(msgs.getString("pie_chart_others"));
        keyStr.append(' ');
        keyStr.append(valuePercentage);
        keyStr.append("% (");
        if ((double) othersValues.intValue() == othersValues.doubleValue())
            keyStr.append(othersValues.intValue());
        else
            keyStr.append(othersValues.doubleValue());
        keyStr.append(")");
        dataSet.setValue(keyStr.toString(), othersValues);
    }

    return dataSet;
}

From source file:com.meidusa.amoeba.route.AbstractQueryRouter.java

License:asdf

protected List<String> evaluate(StringBuffer loggerBuffer, T connection, V queryObject) {
    boolean isRead = true;
    boolean isPrepared = false;
    if (queryObject instanceof Request) {
        isRead = ((Request) queryObject).isRead();
        isPrepared = ((Request) queryObject).isPrepared();
    }//from   www .  ja v a  2s .c o m
    List<String> poolNames = new ArrayList<String>();
    Map<Table, Map<Column, Comparative>> tables = evaluateTable(connection, queryObject);

    if (tables != null && tables.size() > 0) {
        Set<Map.Entry<Table, Map<Column, Comparative>>> entrySet = tables.entrySet();
        for (Map.Entry<Table, Map<Column, Comparative>> entry : entrySet) {
            boolean regexMatched = false;
            Map<Column, Comparative> columnMap = entry.getValue();

            TableRule tableRule = this.tableRuleMap.get(entry.getKey());

            Table table = entry.getKey();

            if (tableRule == null && table.getName() != null) {

                /**
                 * foreach regex table rule
                 */
                for (Map.Entry<Table, TableRule> ruleEntry : this.regexTableRuleMap.entrySet()) {
                    Table ruleTable = ruleEntry.getKey();
                    boolean tableMatched = false;
                    boolean schemaMatched = false;

                    /**
                     * check table name matched or not.
                     */
                    Pattern pattern = this.getPattern(ruleTable.getName());
                    java.util.regex.Matcher matcher = pattern.matcher(table.getName());
                    if (matcher.find()) {
                        tableMatched = true;
                    }

                    /**
                      * check table schema matched or not.
                      */
                    pattern = this.getPattern(ruleTable.getSchema().getName());
                    matcher = pattern.matcher(table.getSchema().getName());
                    if (matcher.find()) {
                        schemaMatched = true;
                    }

                    if (tableMatched && schemaMatched) {
                        tableRule = ruleEntry.getValue();
                        regexMatched = true;
                        break;
                    }
                }
            }

            // table Rule Rule
            if (tableRule != null) {
                // sqltableRule
                if (columnMap == null || isPrepared) {
                    String[] pools = (isRead ? tableRule.readPools : tableRule.writePools);
                    if (pools == null || pools.length == 0) {
                        pools = tableRule.defaultPools;
                    }

                    for (String poolName : pools) {
                        if (!poolNames.contains(poolName)) {
                            poolNames.add(poolName);
                        }
                    }

                    if (!isPrepared) {
                        if (logger.isDebugEnabled()) {
                            loggerBuffer.append(", no Column rule, using table:" + tableRule.table
                                    + " default rules:" + Arrays.toString(tableRule.defaultPools));
                        }
                    }
                    continue;
                }

                List<String> groupMatched = new ArrayList<String>();
                for (Rule rule : tableRule.ruleList) {
                    if (rule.group != null) {
                        if (groupMatched.contains(rule.group)) {
                            continue;
                        }
                    }

                    // 
                    if (columnMap.size() < rule.parameterMap.size()) {
                        continue;
                    } else {
                        boolean matched = true;
                        // 
                        for (Column exclude : rule.excludes) {
                            Comparable<?> condition = columnMap.get(exclude);
                            if (condition != null) {
                                matched = false;
                                break;
                            }
                        }

                        // 
                        if (!matched) {
                            continue;
                        }

                        Comparable<?>[] comparables = new Comparable[rule.parameterMap.size()];
                        // dmlstatement
                        for (Map.Entry<Column, Integer> parameter : rule.cloumnMap.entrySet()) {
                            Comparative condition = null;
                            if (regexMatched) {
                                Column column = new Column();
                                column.setName(parameter.getKey().getName());
                                column.setTable(table);
                                condition = columnMap.get(column);
                            } else {
                                condition = columnMap.get(parameter.getKey());
                            }

                            if (condition != null) {
                                //   array 
                                if (rule.ignoreArray && condition instanceof ComparativeBaseList) {
                                    matched = false;
                                    break;
                                }

                                comparables[parameter.getValue()] = (Comparative) condition.clone();
                            } else {
                                matched = false;
                                break;
                            }
                        }

                        // 
                        if (!matched) {
                            continue;
                        }

                        try {
                            Comparable<?> result = rule.rowJep.getValue(comparables);
                            Integer i = 0;
                            if (result instanceof Comparative) {
                                if (rule.result == RuleResult.INDEX) {
                                    i = (Integer) ((Comparative) result).getValue();
                                    if (i < 0) {
                                        continue;
                                    }
                                    matched = true;
                                } else if (rule.result == RuleResult.POOLNAME) {
                                    String matchedPoolsString = ((Comparative) result).getValue().toString();
                                    String[] poolNamesMatched = matchedPoolsString.split(",");

                                    if (poolNamesMatched != null && poolNamesMatched.length > 0) {
                                        for (String poolName : poolNamesMatched) {
                                            if (!poolNames.contains(poolName)) {
                                                poolNames.add(poolName);
                                            }
                                        }

                                        if (logger.isDebugEnabled()) {
                                            loggerBuffer.append(", matched table:" + tableRule.table + ", rule:"
                                                    + rule.name);
                                        }
                                    }
                                    continue;
                                } else {
                                    matched = (Boolean) ((Comparative) result).getValue();
                                }
                            } else {

                                if (rule.result == RuleResult.INDEX) {
                                    i = (Integer) Integer.valueOf(result.toString());
                                    if (i < 0) {
                                        continue;
                                    }
                                    matched = true;
                                } else if (rule.result == RuleResult.POOLNAME) {
                                    String matchedPoolsString = result.toString();
                                    String[] poolNamesMatched = StringUtil.split(matchedPoolsString, ";,");
                                    if (poolNamesMatched != null && poolNamesMatched.length > 0) {
                                        for (String poolName : poolNamesMatched) {
                                            if (!poolNames.contains(poolName)) {
                                                poolNames.add(poolName);
                                            }
                                        }

                                        if (logger.isDebugEnabled()) {
                                            loggerBuffer.append(", matched table:" + tableRule.table + ", rule:"
                                                    + rule.name);
                                        }
                                    }
                                    continue;
                                } else {
                                    matched = (Boolean) result;
                                }
                            }

                            if (matched) {
                                if (rule.group != null) {
                                    groupMatched.add(rule.group);
                                }
                                String[] pools = (isRead ? rule.readPools : rule.writePools);
                                if (pools == null || pools.length == 0) {
                                    pools = rule.defaultPools;
                                }
                                if (pools != null && pools.length > 0) {
                                    if (rule.isSwitch) {
                                        if (!poolNames.contains(pools[i])) {
                                            poolNames.add(pools[i]);
                                        }
                                    } else {
                                        for (String poolName : pools) {
                                            if (!poolNames.contains(poolName)) {
                                                poolNames.add(poolName);
                                            }
                                        }
                                    }
                                } else {
                                    logger.error("rule:" + rule.name + " matched, but pools is null");
                                }

                                if (logger.isDebugEnabled()) {
                                    loggerBuffer.append(
                                            ", matched table:" + tableRule.table + ", rule:" + rule.name);
                                }
                            }
                        } catch (com.meidusa.amoeba.sqljep.ParseException e) {
                            // logger.error("parse rule error:"+rule.expression,e);
                        }
                    }
                }

                // TableRulepool
                if (poolNames.size() == 0) {
                    String[] pools = (isRead ? tableRule.readPools : tableRule.writePools);
                    if (pools == null || pools.length == 0) {
                        pools = tableRule.defaultPools;
                    }

                    if (!isPrepared) {
                        if (tableRule.ruleList != null && tableRule.ruleList.size() > 0) {
                            if (logger.isDebugEnabled()) {
                                loggerBuffer.append(", no rule matched, using tableRule:[" + tableRule.table
                                        + "] defaultPools");
                            }
                        } else {
                            if (logger.isDebugEnabled()) {
                                if (pools != null) {
                                    StringBuffer buffer = new StringBuffer();
                                    for (String pool : pools) {
                                        buffer.append(pool).append(",");
                                    }
                                    loggerBuffer.append(", using tableRule:[" + tableRule.table
                                            + "] defaultPools=" + buffer.toString());
                                }
                            }
                        }
                    }
                    for (String poolName : pools) {
                        if (!poolNames.contains(poolName)) {
                            poolNames.add(poolName);
                        }
                    }
                }
            }
        }
    }
    return poolNames;
}

From source file:org.elasticsearch.hadoop.cascading.EsHadoopScheme.java

@SuppressWarnings("unchecked")
@Override// w w w.ja  v  a 2  s .  c  o m
public boolean source(FlowProcess<JobConf> flowProcess, SourceCall<Object[], RecordReader> sourceCall)
        throws IOException {
    Object[] context = sourceCall.getContext();

    if (!sourceCall.getInput().next(context[0], context[1])) {
        return false;
    }

    TupleEntry entry = sourceCall.getIncomingEntry();
    Map data = (Map) context[1];
    FieldAlias alias = (FieldAlias) context[2];

    if (entry.getFields().isDefined()) {
        // lookup using writables
        Text lookupKey = new Text();
        for (Comparable<?> field : entry.getFields()) {
            // check for multi-level alias (since ES 1.0)
            Object result = data;
            for (String level : StringUtils.tokenize(alias.toES(field.toString()), ".")) {
                lookupKey.set(level);
                result = ((Map) result).get(lookupKey);
                if (result == null) {
                    break;
                }
            }
            CascadingUtils.setObject(entry, field, result);
        }
    } else {
        // no definition means no coercion
        List<Object> elements = Tuple.elements(entry.getTuple());
        elements.clear();
        elements.addAll(data.values());
    }

    return true;
}

From source file:org.elasticsearch.hadoop.cascading.EsLocalScheme.java

@SuppressWarnings("unchecked")
@Override/*from   w w w  .j av a 2  s.c  om*/
public boolean source(FlowProcess<Properties> flowProcess, SourceCall<Object[], ScrollQuery> sourceCall)
        throws IOException {
    ScrollQuery query = sourceCall.getInput();

    if (!query.hasNext()) {
        return false;
    }

    TupleEntry entry = sourceCall.getIncomingEntry();
    Map<String, ?> data = (Map<String, ?>) query.next()[1];
    FieldAlias alias = (FieldAlias) sourceCall.getContext()[0];

    if (entry.getFields().isDefined()) {
        // lookup using writables
        for (Comparable<?> field : entry.getFields()) {
            Object result = data;
            // check for multi-level alias
            for (String level : StringUtils.tokenize(alias.toES(field.toString()), ".")) {
                result = ((Map) result).get(level);
                if (result == null) {
                    break;
                }
            }
            entry.setObject(field, result);
        }
    } else {
        // no definition means no coercion
        List<Object> elements = Tuple.elements(entry.getTuple());
        elements.clear();
        elements.addAll(data.values());
    }
    return true;
}

From source file:org.kuali.coeus.common.budget.framework.query.QueryList.java

/** calculates the sum of the field in this QueryList.
 * @param fieldName field of bean whose sum has to be calculated.
 * @param arg argument for the getter method of field if it takes any argumnt,
 * else can be null./*w w  w  .j  a v  a  2 s . co m*/
 * @param value value for the argument, else can be null.
 * @return returns sum.
 */
public double sum(String fieldName, Class arg, Object value) {
    if (size() == 0) {
        return 0;
    }

    Object current;
    Field field = null;
    Method method = null;
    Class dataClass = get(0).getClass();
    double sum = 0;

    try {
        field = dataClass.getDeclaredField(fieldName);

        Class fieldClass = field.getType();
        if (!(fieldClass.equals(Integer.class) || fieldClass.equals(Long.class)
                || fieldClass.equals(Double.class) || fieldClass.equals(Float.class)
                || fieldClass.equals(BigDecimal.class) || fieldClass.equals(BigInteger.class)
                || fieldClass.equals(ScaleTwoDecimal.class) || fieldClass.equals(ScaleTwoDecimal.class)
                || fieldClass.equals(int.class) || fieldClass.equals(long.class)
                || fieldClass.equals(float.class) || fieldClass.equals(double.class))) {
            throw new UnsupportedOperationException("Data Type not numeric");
        }

        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        try {
            String methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            if (arg != null) {
                Class args[] = { arg };
                method = dataClass.getMethod(methodName, args);
            } else {
                method = dataClass.getMethod(methodName, null);
            }
        } catch (NoSuchMethodException noSuchMethodException) {
            LOG.error(noSuchMethodException.getMessage(), noSuchMethodException);
        }
    }

    for (int index = 0; index < size(); index++) {
        current = get(index);

        try {
            if (field != null && field.isAccessible()) {
                sum = sum + Double.parseDouble(((Comparable) field.get(current)).toString());
            } else {
                Comparable dataValue;
                if (value != null) {
                    Object values[] = { value };
                    dataValue = (Comparable) method.invoke(current, values);
                } else {
                    dataValue = (Comparable) method.invoke(current, null);
                }
                if (dataValue != null) {
                    sum += Double.parseDouble(dataValue.toString());
                }

            }
        } catch (IllegalAccessException illegalAccessException) {
            LOG.error(illegalAccessException.getMessage(), illegalAccessException);
        } catch (InvocationTargetException invocationTargetException) {
            LOG.error(invocationTargetException.getMessage(), invocationTargetException);
        }
    }
    return sum;
}

From source file:org.kuali.kra.budget.calculator.QueryList.java

/** calculates the sum of the field in this QueryList.
 * @param fieldName field of bean whose sum has to be calculated.
 * @param arg argument for the getter method of field if it takes any argumnt,
 * else can be null./*  w w  w  .j a  v a2 s .  c  o m*/
 * @param value value for the argument, else can be null.
 * @return returns sum.
 */
public double sum(String fieldName, Class arg, Object value) {
    if (size() == 0) {
        return 0;
    }

    Object current;
    Field field = null;
    Method method = null;
    Class dataClass = get(0).getClass();
    double sum = 0;

    try {
        field = dataClass.getDeclaredField(fieldName);

        Class fieldClass = field.getType();
        if (!(fieldClass.equals(Integer.class) || fieldClass.equals(Long.class)
                || fieldClass.equals(Double.class) || fieldClass.equals(Float.class)
                || fieldClass.equals(BigDecimal.class) || fieldClass.equals(BigInteger.class)
                || fieldClass.equals(BudgetDecimal.class) || fieldClass.equals(KualiDecimal.class)
                || fieldClass.equals(int.class) || fieldClass.equals(long.class)
                || fieldClass.equals(float.class) || fieldClass.equals(double.class))) {
            throw new UnsupportedOperationException("Data Type not numeric");
        }

        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        try {
            String methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            if (arg != null) {
                Class args[] = { arg };
                method = dataClass.getMethod(methodName, args);
            } else {
                method = dataClass.getMethod(methodName, null);
            }
        } catch (NoSuchMethodException noSuchMethodException) {
            noSuchMethodException.printStackTrace();
        }
    }

    for (int index = 0; index < size(); index++) {
        current = get(index);

        try {
            if (field != null && field.isAccessible()) {
                sum = sum + Double.parseDouble(((Comparable) field.get(current)).toString());
            } else {
                Comparable dataValue;
                if (value != null) {
                    Object values[] = { value };
                    dataValue = (Comparable) method.invoke(current, values);
                } else {
                    dataValue = (Comparable) method.invoke(current, null);
                }
                if (dataValue != null) {
                    sum += Double.parseDouble(dataValue.toString());
                }

            }
        } catch (IllegalAccessException illegalAccessException) {
            illegalAccessException.printStackTrace();
        } catch (InvocationTargetException invocationTargetException) {
            invocationTargetException.printStackTrace();
        }
    }
    return sum;
}

From source file:org.pentaho.big.data.impl.vfs.hdfs.nc.NamedClusterProvider.java

protected synchronized FileSystem findFileSystem(final Comparable<?> key,
        final FileSystemOptions fileSystemProps) {
    String editedKey = getFileSystemKey(key.toString(), fileSystemProps);
    return super.findFileSystem(editedKey, fileSystemProps);
}

From source file:org.silverpeas.components.jdbcconnector.service.comparators.Equality.java

@Override
public boolean compare(final Comparable value, final Comparable referenceValue) {
    if (value == null && NULL_VALUE.equals(referenceValue)) {
        return true;
    } else if (value != null && !NULL_VALUE.equals(referenceValue)) {
        final String finalReferenceValue = EMPTY_VALUE.equals(referenceValue) ? EMPTY
                : referenceValue.toString();
        return value.toString().compareTo(finalReferenceValue) == 0;
    }//w ww .jav  a 2s.c om
    return false;
}

From source file:org.silverpeas.components.jdbcconnector.service.comparators.Inequality.java

@Override
public boolean compare(final Comparable value, final Comparable referenceValue) {
    if (value == null && NULL_VALUE.equals(referenceValue)) {
        return false;
    } else if (value != null && !NULL_VALUE.equals(referenceValue)) {
        final String finalReferenceValue = EMPTY_VALUE.equals(referenceValue) ? EMPTY
                : referenceValue.toString();
        return value.toString().compareTo(finalReferenceValue) != 0;
    }//from  w w  w. j a va  2s  . c o  m
    return true;
}