Example usage for java.lang Float isInfinite

List of usage examples for java.lang Float isInfinite

Introduction

In this page you can find the example usage for java.lang Float isInfinite.

Prototype

public boolean isInfinite() 

Source Link

Document

Returns true if this Float value is infinitely large in magnitude, false otherwise.

Usage

From source file:Main.java

public static void main(String[] args) {

    Float f1 = new Float(1.0 / 0.0);
    Float f2 = new Float(0.0 / 0.0);

    System.out.println(f1 + " = " + f1.isInfinite());
    System.out.println(f2 + " = " + f2.isInfinite());
}

From source file:Main.java

/**
 * <p>Turns a string value into a java.lang.Number.</p>
 *
 * <p>First, the value is examined for a type qualifier on the end
 * (<code>'f','F','d','D','l','L'</code>).  If it is found, it starts 
 * trying to create successively larger types from the type specified
 * until one is found that can hold the value.</p>
 *
 * <p>If a type specifier is not found, it will check for a decimal point
 * and then try successively larger types from <code>Integer</code> to
 * <code>BigInteger</code> and from <code>Float</code> to
 * <code>BigDecimal</code>.</p>
 *
 * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it
 * will be interpreted as a hexadecimal integer.  Values with leading
 * <code>0</code>'s will not be interpreted as octal.</p>
 *
 * @param val String containing a number
 * @return Number created from the string
 * @throws NumberFormatException if the value cannot be converted
 *///from ww w . ja  va 2s. c o m
public static Number createNumber(String val) throws NumberFormatException {
    if (val == null) {
        return null;
    }
    if (val.length() == 0) {
        throw new NumberFormatException("\"\" is not a valid number.");
    }
    if (val.startsWith("--")) {
        // this is protection for poorness in java.lang.BigDecimal.
        // it accepts this as a legal value, but it does not appear 
        // to be in specification of class. OS X Java parses it to 
        // a wrong value.
        return null;
    }
    if (val.startsWith("0x") || val.startsWith("-0x")) {
        return createInteger(val);
    }
    char lastChar = val.charAt(val.length() - 1);
    String mant;
    String dec;
    String exp;
    int decPos = val.indexOf('.');
    int expPos = val.indexOf('e') + val.indexOf('E') + 1;

    if (decPos > -1) {

        if (expPos > -1) {
            if (expPos < decPos) {
                throw new NumberFormatException(val + " is not a valid number.");
            }
            dec = val.substring(decPos + 1, expPos);
        } else {
            dec = val.substring(decPos + 1);
        }
        mant = val.substring(0, decPos);
    } else {
        if (expPos > -1) {
            mant = val.substring(0, expPos);
        } else {
            mant = val;
        }
        dec = null;
    }
    if (!Character.isDigit(lastChar)) {
        if (expPos > -1 && expPos < val.length() - 1) {
            exp = val.substring(expPos + 1, val.length() - 1);
        } else {
            exp = null;
        }
        //Requesting a specific type..
        String numeric = val.substring(0, val.length() - 1);
        boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
        switch (lastChar) {
        case 'l':
        case 'L':
            if (dec == null && exp == null
                    && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
                try {
                    return createLong(numeric);
                } catch (NumberFormatException nfe) {
                    //Too big for a long
                }
                return createBigInteger(numeric);

            }
            throw new NumberFormatException(val + " is not a valid number.");
        case 'f':
        case 'F':
            try {
                Float f = createFloat(numeric);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    //If it's too big for a float or the float value = 0 and the string
                    //has non-zeros in it, then float does not have the precision we want
                    return f;
                }

            } catch (NumberFormatException e) {
                // ignore the bad number
            }
            //Fall through
        case 'd':
        case 'D':
            try {
                Double d = createDouble(numeric);
                if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                return createBigDecimal(numeric);
            } catch (NumberFormatException e) {
                // empty catch
            }
            //Fall through
        default:
            throw new NumberFormatException(val + " is not a valid number.");

        }
    } else {
        //User doesn't have a preference on the return type, so let's start
        //small and go from there...
        if (expPos > -1 && expPos < val.length() - 1) {
            exp = val.substring(expPos + 1, val.length());
        } else {
            exp = null;
        }
        if (dec == null && exp == null) {
            //Must be an int,long,bigint
            try {
                return createInteger(val);
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                return createLong(val);
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            return createBigInteger(val);

        } else {
            //Must be a float,double,BigDec
            boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
            try {
                Float f = createFloat(val);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    return f;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                Double d = createDouble(val);
                if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }

            return createBigDecimal(val);

        }

    }
}

From source file:org.kordamp.ezmorph.object.BigDecimalMorpher.java

public Object morph(Object value) {
    if (value instanceof BigDecimal) {
        return value;
    }/* www.  ja v a2  s  .co m*/

    if (value == null) {
        if (isUseDefault()) {
            return defaultValue;
        } else {
            return (BigDecimal) null;
        }
    }

    if (value instanceof Number) {
        if (value instanceof Float) {
            Float f = ((Float) value);
            if (f.isInfinite() || f.isNaN()) {
                throw new MorphException("BigDecimal can not be infinite or NaN");
            }
        } else if (value instanceof Double) {
            Double d = ((Double) value);
            if (d.isInfinite() || d.isNaN()) {
                throw new MorphException("BigDecimal can not be infinite or NaN");
            }
        } else if (value instanceof BigInteger) {
            return new BigDecimal((BigInteger) value);
        }

        return new BigDecimal(((Number) value).doubleValue());
    } else {
        try {
            String str = String.valueOf(value).trim();
            if (str.length() == 0 || str.equalsIgnoreCase("null")) {
                return (BigDecimal) null;
            } else {
                return new BigDecimal(str);
            }
        } catch (NumberFormatException nfe) {
            if (isUseDefault()) {
                return defaultValue;
            } else {
                throw new MorphException(nfe);
            }
        }
    }
}

From source file:org.kordamp.ezmorph.object.BigIntegerMorpher.java

public Object morph(Object value) {
    if (value instanceof BigInteger) {
        return value;
    }/*from   w ww.  j a  v a2 s .  c om*/

    if (value == null) {
        if (isUseDefault()) {
            return defaultValue;
        } else {
            return (BigInteger) null;
        }
    }

    if (value instanceof Number) {
        if (value instanceof Float) {
            Float f = ((Float) value);
            if (f.isInfinite() || f.isNaN()) {
                throw new MorphException("BigInteger can not be infinite or NaN");
            }
        } else if (value instanceof Double) {
            Double d = ((Double) value);
            if (d.isInfinite() || d.isNaN()) {
                throw new MorphException("BigInteger can not be infinite or NaN");
            }
        } else if (value instanceof BigDecimal) {
            return ((BigDecimal) value).toBigInteger();
        }
        return BigInteger.valueOf(((Number) value).longValue());
    } else {
        try {
            String str = getIntegerValue(value);
            if (str.length() == 0 || str.equalsIgnoreCase("null")) {
                return (BigInteger) null;
            } else {
                return new BigInteger(str);
            }
        } catch (NumberFormatException nfe) {
            if (isUseDefault()) {
                return defaultValue;
            } else {
                throw new MorphException(nfe);
            }
        }
    }
}

From source file:org.caleydo.view.tourguide.impl.PAGEAlgorithm.java

@Override
public void init(IProgressMonitor monitor) {
    if (!foldChanges.isEmpty())
        return;//from   www.j a  v  a2s.  c  om

    final Set<Integer> inA = new HashSet<>(perspective.getVirtualArray().getIDsOfGroup(group.getGroupIndex()));
    ATableBasedDataDomain dataDomain = (ATableBasedDataDomain) perspective.getDataDomain();
    Table table = dataDomain.getTable();

    List<Integer> rows = perspective.getVirtualArray().getIDs();
    List<Integer> cols = table.getDefaultDimensionPerspective(false).getVirtualArray().getIDs();

    Stopwatch w = new Stopwatch().start();

    float sum = 0;
    float squaredSum = 0;

    for (Integer col : cols) {
        // mean of the expressions level of the samples for the given gen.
        float asum = 0;
        int acount = 0;
        float bsum = 0;
        int bcount = 0;
        for (Integer row : rows) {
            Float v = table.getRaw(col, row);
            if (v == null || v.isNaN() || v.isInfinite())
                continue;
            if (inA.contains(row)) {
                asum += v;
                acount++;
            } else {
                bsum += v;
                bcount++;
            }

        }
        if (monitor.isCanceled()) {
            foldChanges.clear(); // undo init
            return;
        }

        // now some kind of correlation between the two
        float foldChange = Statistics.foldChange((asum / acount), (bsum / bcount));
        Set<Integer> davids = dim2primary.apply(col);
        if (davids == null)
            continue;
        sum += foldChange * davids.size();
        squaredSum += (foldChange * foldChange) * davids.size();
        for (Integer david : davids)
            foldChanges.put(david, foldChange);
    }
    foldChangesMean = sum / foldChanges.size();
    foldChangesSD = (float) Math.sqrt(squaredSum / foldChanges.size() - foldChangesMean * foldChangesMean);
    System.out.println(w);
}

From source file:org.apache.stratos.autoscaler.monitor.cluster.VMClusterMonitor.java

@Override
public void handleAverageRequestsInFlightEvent(AverageRequestsInFlightEvent averageRequestsInFlightEvent) {

    String networkPartitionId = averageRequestsInFlightEvent.getNetworkPartitionId();
    String clusterId = averageRequestsInFlightEvent.getClusterId();
    Float servedCount = averageRequestsInFlightEvent.getServedCount();
    Float activeInstances = averageRequestsInFlightEvent.getActiveInstances();
    Float requestsServedPerInstance = servedCount / activeInstances;
    if (requestsServedPerInstance.isInfinite()) {
        requestsServedPerInstance = 0f;//  www .  ja  v  a 2  s .co  m
    }
    float value = averageRequestsInFlightEvent.getValue();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Average Rif event: [cluster] %s [network-partition] %s [value] %s", clusterId,
                networkPartitionId, value));
    }
    NetworkPartitionContext networkPartitionContext = getNetworkPartitionCtxt(networkPartitionId);
    if (null != networkPartitionContext) {
        networkPartitionContext.setAverageRequestsInFlight(value);
    } else {
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "Network partition context is not available for :" + " [network partition] %s",
                    networkPartitionId));
        }
    }
}

From source file:org.displaytag.util.NumberUtils.java

/**
 * <p>Turns a string value into a java.lang.Number.</p>
 *
 * <p>First, the value is examined for a type qualifier on the end
 * (<code>'f','F','d','D','l','L'</code>).  If it is found, it starts 
 * trying to create successively larger types from the type specified
 * until one is found that can represent the value.</p>
 *
 * <p>If a type specifier is not found, it will check for a decimal point
 * and then try successively larger types from <code>Integer</code> to
 * <code>BigInteger</code> and from <code>Float</code> to
 * <code>BigDecimal</code>.</p>
 *
 * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it
 * will be interpreted as a hexadecimal integer.  Values with leading
 * <code>0</code>'s will not be interpreted as octal.</p>
 *
 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
 *
 * <p>This method does not trim the input string, i.e., strings with leading
 * or trailing spaces will generate NumberFormatExceptions.</p>
 *
 * @param str  String containing a number, may be null
 * @return Number created from the string
 * @throws NumberFormatException if the value cannot be converted
 *///  w  w  w  .j  a  v  a2s.co  m
public static Number createNumber(String str) throws NumberFormatException {
    if (str == null) {
        return null;
    }
    if (StringUtils.isBlank(str)) {
        throw new NumberFormatException("A blank string is not a valid number");
    }
    if (str.startsWith("--")) {
        // this is protection for poorness in java.lang.BigDecimal.
        // it accepts this as a legal value, but it does not appear 
        // to be in specification of class. OS X Java parses it to 
        // a wrong value.
        return null;
    }
    if (str.startsWith("0x") || str.startsWith("-0x")) {
        return createInteger(str);
    }
    char lastChar = str.charAt(str.length() - 1);
    String mant;
    String dec;
    String exp;
    int decPos = str.indexOf('.');
    int expPos = str.indexOf('e') + str.indexOf('E') + 1;

    if (decPos > -1) {

        if (expPos > -1) {
            if (expPos < decPos || expPos > str.length()) {
                throw new NumberFormatException(str + " is not a valid number.");
            }
            dec = str.substring(decPos + 1, expPos);
        } else {
            dec = str.substring(decPos + 1);
        }
        mant = str.substring(0, decPos);
    } else {
        if (expPos > -1) {
            if (expPos > str.length()) {
                throw new NumberFormatException(str + " is not a valid number.");
            }
            mant = str.substring(0, expPos);
        } else {
            mant = str;
        }
        dec = null;
    }
    if (!Character.isDigit(lastChar) && lastChar != '.') {
        if (expPos > -1 && expPos < str.length() - 1) {
            exp = str.substring(expPos + 1, str.length() - 1);
        } else {
            exp = null;
        }
        //Requesting a specific type..
        String numeric = str.substring(0, str.length() - 1);
        boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
        switch (lastChar) {
        case 'l':
        case 'L':
            if (dec == null && exp == null
                    && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
                try {
                    return createLong(numeric);
                } catch (NumberFormatException nfe) {
                    //Too big for a long
                }
                return createBigInteger(numeric);

            }
            throw new NumberFormatException(str + " is not a valid number.");
        case 'f':
        case 'F':
            try {
                Float f = NumberUtils.createFloat(numeric);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    //If it's too big for a float or the float value = 0 and the string
                    //has non-zeros in it, then float does not have the precision we want
                    return f;
                }

            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            //$FALL-THROUGH$
        case 'd':
        case 'D':
            try {
                Double d = NumberUtils.createDouble(numeric);
                if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            try {
                return createBigDecimal(numeric);
            } catch (NumberFormatException e) {
                // ignore the bad number
            }
            //$FALL-THROUGH$
        default:
            throw new NumberFormatException(str + " is not a valid number.");

        }
    } else {
        //User doesn't have a preference on the return type, so let's start
        //small and go from there...
        if (expPos > -1 && expPos < str.length() - 1) {
            exp = str.substring(expPos + 1, str.length());
        } else {
            exp = null;
        }
        if (dec == null && exp == null) {
            //Must be an int,long,bigint
            try {
                return createInteger(str);
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            try {
                return createLong(str);
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            return createBigInteger(str);

        } else {
            //Must be a float,double,BigDec
            boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
            try {
                Float f = createFloat(str);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    return f;
                }
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            try {
                Double d = createDouble(str);
                if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }

            return createBigDecimal(str);

        }
    }
}

From source file:org.alfresco.serializers.types.DefaultTypeConverter.java

@SuppressWarnings("rawtypes")
private DefaultTypeConverter() {
    ///*from   w  w  w. j av  a  2s  .co m*/
    // From string
    //
    addConverter(String.class, Class.class, new TypeConverter.Converter<String, Class>() {
        public Class convert(String source) {
            try {
                return Class.forName(source);
            } catch (ClassNotFoundException e) {
                throw new TypeConversionException("Failed to convert string to class: " + source, e);
            }
        }
    });
    addConverter(String.class, Boolean.class, new TypeConverter.Converter<String, Boolean>() {
        public Boolean convert(String source) {
            return Boolean.valueOf(source);
        }
    });
    addConverter(String.class, Character.class, new TypeConverter.Converter<String, Character>() {
        public Character convert(String source) {
            if ((source == null) || (source.length() == 0)) {
                return null;
            }
            return Character.valueOf(source.charAt(0));
        }
    });
    addConverter(String.class, Number.class, new TypeConverter.Converter<String, Number>() {
        public Number convert(String source) {
            try {
                return DecimalFormat.getNumberInstance().parse(source);
            } catch (ParseException e) {
                throw new TypeConversionException("Failed to parse number " + source, e);
            }
        }
    });
    addConverter(String.class, Byte.class, new TypeConverter.Converter<String, Byte>() {
        public Byte convert(String source) {
            return Byte.valueOf(source);
        }
    });
    addConverter(String.class, Short.class, new TypeConverter.Converter<String, Short>() {
        public Short convert(String source) {
            return Short.valueOf(source);
        }
    });
    addConverter(String.class, Integer.class, new TypeConverter.Converter<String, Integer>() {
        public Integer convert(String source) {
            return Integer.valueOf(source);
        }
    });
    addConverter(String.class, Long.class, new TypeConverter.Converter<String, Long>() {
        public Long convert(String source) {
            return Long.valueOf(source);
        }
    });
    addConverter(String.class, Float.class, new TypeConverter.Converter<String, Float>() {
        public Float convert(String source) {
            return Float.valueOf(source);
        }
    });
    addConverter(String.class, Double.class, new TypeConverter.Converter<String, Double>() {
        public Double convert(String source) {
            return Double.valueOf(source);
        }
    });
    addConverter(String.class, BigInteger.class, new TypeConverter.Converter<String, BigInteger>() {
        public BigInteger convert(String source) {
            return new BigInteger(source);
        }
    });
    addConverter(String.class, BigDecimal.class, new TypeConverter.Converter<String, BigDecimal>() {
        public BigDecimal convert(String source) {
            return new BigDecimal(source);
        }
    });
    addConverter(BasicDBObject.class, BigDecimal.class,
            new TypeConverter.Converter<BasicDBObject, BigDecimal>() {
                public BigDecimal convert(BasicDBObject source) {
                    String type = (String) source.get("t");
                    if (type.equals("FIXED_POINT")) {
                        String number = (String) source.get("n");
                        Integer precision = (Integer) source.get("p");
                        MathContext ctx = new MathContext(precision);
                        return new BigDecimal(number, ctx);
                    } else {
                        throw new IllegalArgumentException("Invalid source object for conversion " + source
                                + ", expected a Fixed Decimal object");
                    }
                }
            });
    addConverter(String.class, Date.class, new TypeConverter.Converter<String, Date>() {
        public Date convert(String source) {
            try {
                Date date = ISO8601DateFormat.parse(source);
                return date;
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            } catch (AlfrescoRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });
    addConverter(String.class, Duration.class, new TypeConverter.Converter<String, Duration>() {
        public Duration convert(String source) {
            return new Duration(source);
        }
    });
    addConverter(String.class, QName.class, new TypeConverter.Converter<String, QName>() {
        public QName convert(String source) {
            return QName.createQName(source);
        }
    });
    addConverter(BasicDBObject.class, QName.class, new TypeConverter.Converter<BasicDBObject, QName>() {
        public QName convert(BasicDBObject source) {
            String type = (String) source.get("t");
            if (type.equals("QNAME")) {
                String qname = (String) source.get("v");
                return QName.createQName(qname);
            } else {
                throw new IllegalArgumentException();
            }
        }
    });
    addConverter(String.class, ContentData.class, new TypeConverter.Converter<String, ContentData>() {
        public ContentData convert(String source) {
            return ContentData.createContentProperty(source);
        }
    });
    addConverter(String.class, NodeRef.class, new TypeConverter.Converter<String, NodeRef>() {
        public NodeRef convert(String source) {
            return new NodeRef(source);
        }
    });
    addConverter(BasicDBObject.class, NodeRef.class, new TypeConverter.Converter<BasicDBObject, NodeRef>() {
        public NodeRef convert(BasicDBObject source) {
            String type = (String) source.get("t");
            if (!type.equals("NODEREF")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a NodeRef object");
            }
            String protocol = (String) source.get("p");
            String storeId = (String) source.get("s");
            String id = (String) source.get("id");
            NodeRef nodeRef = new NodeRef(new StoreRef(protocol, storeId), id);
            return nodeRef;
        }
    });
    addConverter(String.class, StoreRef.class, new TypeConverter.Converter<String, StoreRef>() {
        public StoreRef convert(String source) {
            return new StoreRef(source);
        }
    });
    addConverter(BasicDBObject.class, StoreRef.class, new TypeConverter.Converter<BasicDBObject, StoreRef>() {
        public StoreRef convert(BasicDBObject source) {
            String type = (String) source.get("t");
            if (!type.equals("STOREREF")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a StoreRef object");
            }
            String protocol = (String) source.get("p");
            String storeId = (String) source.get("s");
            return new StoreRef(protocol, storeId);
        }
    });
    addConverter(String.class, ChildAssociationRef.class,
            new TypeConverter.Converter<String, ChildAssociationRef>() {
                public ChildAssociationRef convert(String source) {
                    return new ChildAssociationRef(source);
                }
            });
    addConverter(String.class, AssociationRef.class, new TypeConverter.Converter<String, AssociationRef>() {
        public AssociationRef convert(String source) {
            return new AssociationRef(source);
        }
    });
    addConverter(String.class, InputStream.class, new TypeConverter.Converter<String, InputStream>() {
        public InputStream convert(String source) {
            try {
                return new ByteArrayInputStream(source.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new TypeConversionException("Encoding not supported", e);
            }
        }
    });
    addConverter(String.class, MLText.class, new TypeConverter.Converter<String, MLText>() {
        public MLText convert(String source) {
            return new MLText(source);
        }
    });
    addConverter(BasicDBObject.class, MLText.class, new TypeConverter.Converter<BasicDBObject, MLText>() {
        public MLText convert(BasicDBObject source) {
            String type = (String) source.get("t");
            if (!type.equals("MLTEXT")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a NodeRef object");
            }

            MLText mlText = new MLText();
            for (String languageTag : source.keySet()) {
                String text = (String) source.get(languageTag);
                Locale locale = Locale.forLanguageTag(languageTag);
                mlText.put(locale, text);
            }

            return mlText;
        }
    });
    //        addConverter(BasicDBObject.class, ContentDataWithId.class, new TypeConverter.Converter<BasicDBObject, ContentDataWithId>()
    //        {
    //            public ContentDataWithId convert(BasicDBObject source)
    //            {
    //                String type = (String)source.get("t");
    //                if(!type.equals("CONTENT_DATA_ID"))
    //                {
    //                    throw new IllegalArgumentException("Invalid source object for conversion "
    //                            + source 
    //                            + ", expected a ContentDataWithId object");
    //                }
    //                String contentUrl = (String)source.get("u");
    //                String mimeType = (String)source.get("m");
    //                Long size = (Long)source.get("s");
    //                String encoding = (String)source.get("e");
    //                String languageTag = (String)source.get("l");
    //                Long id = (Long)source.get("id");
    //                Locale locale = Locale.forLanguageTag(languageTag);
    //
    //                ContentData contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
    //                ContentDataWithId contentDataWithId = new ContentDataWithId(contentData, id);
    //                return contentDataWithId;
    //            }
    //        });
    addConverter(BasicDBObject.class, ContentData.class,
            new TypeConverter.Converter<BasicDBObject, ContentData>() {
                public ContentData convert(BasicDBObject source) {
                    ContentData contentData = null;

                    String type = (String) source.get("t");
                    if (type.equals("CONTENT")) {
                        String contentUrl = (String) source.get("u");
                        String mimeType = (String) source.get("m");
                        Long size = (Long) source.get("s");
                        String encoding = (String) source.get("e");
                        String languageTag = (String) source.get("l");
                        Locale locale = Locale.forLanguageTag(languageTag);
                        contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
                    } else if (type.equals("CONTENT_DATA_ID")) {
                        String contentUrl = (String) source.get("u");
                        String mimeType = (String) source.get("m");
                        Long size = (Long) source.get("s");
                        String encoding = (String) source.get("e");
                        String languageTag = (String) source.get("l");
                        Locale locale = Locale.forLanguageTag(languageTag);
                        contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
                    } else {
                        throw new IllegalArgumentException("Invalid source object for conversion " + source
                                + ", expected a ContentData object");
                    }

                    return contentData;
                }
            });
    addConverter(BasicDBObject.class, String.class, new TypeConverter.Converter<BasicDBObject, String>() {
        public String convert(BasicDBObject source) {
            // TODO distinguish between different BasicDBObject representations e.g. for MLText, ...

            Set<String> languageTags = source.keySet();
            if (languageTags.size() == 0) {
                throw new IllegalArgumentException("Persisted MLText is invalid " + source);
            } else if (languageTags.size() > 1) {
                // TODO
                logger.warn("Persisted MLText has more than 1 locale " + source);
            }

            String languageTag = languageTags.iterator().next();
            String text = source.getString(languageTag);
            return text;
        }
    });
    addConverter(String.class, Locale.class, new TypeConverter.Converter<String, Locale>() {
        public Locale convert(String source) {
            return I18NUtil.parseLocale(source);
        }
    });
    addConverter(String.class, Period.class, new TypeConverter.Converter<String, Period>() {
        public Period convert(String source) {
            return new Period(source);
        }
    });
    addConverter(String.class, VersionNumber.class, new TypeConverter.Converter<String, VersionNumber>() {
        public VersionNumber convert(String source) {
            return new VersionNumber(source);
        }
    });

    //
    // From Locale
    //
    addConverter(Locale.class, String.class, new TypeConverter.Converter<Locale, String>() {
        public String convert(Locale source) {
            String localeStr = source.toString();
            if (localeStr.length() < 6) {
                localeStr += "_";
            }
            return localeStr;
        }
    });

    //
    // From VersionNumber
    //
    addConverter(VersionNumber.class, String.class, new TypeConverter.Converter<VersionNumber, String>() {
        public String convert(VersionNumber source) {
            return source.toString();
        }
    });

    //
    // From MLText
    //
    addConverter(MLText.class, String.class, new TypeConverter.Converter<MLText, String>() {
        public String convert(MLText source) {
            return source.getDefaultValue();
        }
    });

    addConverter(MLText.class, BasicDBObject.class, new TypeConverter.Converter<MLText, BasicDBObject>() {
        public BasicDBObject convert(MLText source) {
            BasicDBObject dbObject = new BasicDBObject("t", "MLTEXT");
            for (Map.Entry<Locale, String> entry : source.entrySet()) {
                dbObject.put(entry.getKey().toLanguageTag(), entry.getValue());
            }
            return dbObject;
        }
    });

    //        addConverter(ContentDataWithId.class, BasicDBObject.class, new TypeConverter.Converter<ContentDataWithId, BasicDBObject>()
    //        {
    //            public BasicDBObject convert(ContentDataWithId source)
    //            {
    //                BasicDBObject dbObject = new BasicDBObject("t", "CONTENT_DATA_ID");
    //
    //                String contentUrl = source.getContentUrl();
    //                Long id = source.getId();
    //                String languageTag = source.getLocale().toLanguageTag();
    //                String encoding = source.getEncoding();
    //                long size = source.getSize();
    //                String mimeType = source.getMimetype();
    //
    //                dbObject.put("u", contentUrl);
    //                dbObject.put("m", mimeType);
    //                dbObject.put("s", size);
    //                dbObject.put("e", encoding);
    //                dbObject.put("l", languageTag);
    //                dbObject.put("id", id);
    //                return dbObject;
    //            }
    //        });

    addConverter(ContentData.class, BasicDBObject.class,
            new TypeConverter.Converter<ContentData, BasicDBObject>() {
                public BasicDBObject convert(ContentData source) {
                    BasicDBObject dbObject = new BasicDBObject("t", "CONTENT");

                    String contentUrl = source.getContentUrl();
                    String languageTag = source.getLocale().toLanguageTag();
                    String encoding = source.getEncoding();
                    long size = source.getSize();
                    String mimeType = source.getMimetype();

                    dbObject.put("u", contentUrl);
                    dbObject.put("m", mimeType);
                    dbObject.put("s", size);
                    dbObject.put("e", encoding);
                    dbObject.put("l", languageTag);
                    return dbObject;
                }
            });

    //
    // From enum
    //
    addConverter(Enum.class, String.class, new TypeConverter.Converter<Enum, String>() {
        public String convert(Enum source) {
            return source.toString();
        }
    });

    // From Period
    addConverter(Period.class, String.class, new TypeConverter.Converter<Period, String>() {
        public String convert(Period source) {
            return source.toString();
        }
    });

    // From Class
    addConverter(Class.class, String.class, new TypeConverter.Converter<Class, String>() {
        public String convert(Class source) {
            return source.getName();
        }
    });

    //
    // Number to Subtypes and Date
    //
    addConverter(Number.class, Boolean.class, new TypeConverter.Converter<Number, Boolean>() {
        public Boolean convert(Number source) {
            return new Boolean(source.longValue() > 0);
        }
    });
    addConverter(Number.class, Byte.class, new TypeConverter.Converter<Number, Byte>() {
        public Byte convert(Number source) {
            return Byte.valueOf(source.byteValue());
        }
    });
    addConverter(Number.class, Short.class, new TypeConverter.Converter<Number, Short>() {
        public Short convert(Number source) {
            return Short.valueOf(source.shortValue());
        }
    });
    addConverter(Number.class, Integer.class, new TypeConverter.Converter<Number, Integer>() {
        public Integer convert(Number source) {
            return Integer.valueOf(source.intValue());
        }
    });
    addConverter(Number.class, Long.class, new TypeConverter.Converter<Number, Long>() {
        public Long convert(Number source) {
            return Long.valueOf(source.longValue());
        }
    });
    addConverter(Number.class, Float.class, new TypeConverter.Converter<Number, Float>() {
        public Float convert(Number source) {
            return Float.valueOf(source.floatValue());
        }
    });
    addConverter(Number.class, Double.class, new TypeConverter.Converter<Number, Double>() {
        public Double convert(Number source) {
            return Double.valueOf(source.doubleValue());
        }
    });
    addConverter(Number.class, Date.class, new TypeConverter.Converter<Number, Date>() {
        public Date convert(Number source) {
            return new Date(source.longValue());
        }
    });
    addConverter(Number.class, String.class, new TypeConverter.Converter<Number, String>() {
        public String convert(Number source) {
            return source.toString();
        }
    });
    addConverter(Number.class, BigInteger.class, new TypeConverter.Converter<Number, BigInteger>() {
        public BigInteger convert(Number source) {
            if (source instanceof BigDecimal) {
                return ((BigDecimal) source).toBigInteger();
            } else {
                return BigInteger.valueOf(source.longValue());
            }
        }
    });
    addConverter(Number.class, BigDecimal.class, new TypeConverter.Converter<Number, BigDecimal>() {
        public BigDecimal convert(Number source) {
            if (source instanceof BigInteger) {
                return new BigDecimal((BigInteger) source);
            } else if (source instanceof Double) {
                return BigDecimal.valueOf((Double) source);
            } else if (source instanceof Float) {
                Float val = (Float) source;
                if (val.isInfinite()) {
                    // What else can we do here?  this is 3.4 E 38 so is fairly big
                    return new BigDecimal(Float.MAX_VALUE);
                }
                return BigDecimal.valueOf((Float) source);
            } else {
                return BigDecimal.valueOf(source.longValue());
            }
        }
    });
    addDynamicTwoStageConverter(Number.class, String.class, InputStream.class);

    //
    // Date, Timestamp ->
    //
    addConverter(Timestamp.class, Date.class, new TypeConverter.Converter<Timestamp, Date>() {
        public Date convert(Timestamp source) {
            return new Date(source.getTime());
        }
    });
    addConverter(Date.class, Number.class, new TypeConverter.Converter<Date, Number>() {
        public Number convert(Date source) {
            return Long.valueOf(source.getTime());
        }
    });
    addConverter(Date.class, String.class, new TypeConverter.Converter<Date, String>() {
        public String convert(Date source) {
            try {
                return ISO8601DateFormat.format(source);
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });
    addConverter(Date.class, Calendar.class, new TypeConverter.Converter<Date, Calendar>() {
        public Calendar convert(Date source) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(source);
            return calendar;
        }
    });

    addConverter(Date.class, GregorianCalendar.class, new TypeConverter.Converter<Date, GregorianCalendar>() {
        public GregorianCalendar convert(Date source) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(source);
            return calendar;
        }
    });
    addDynamicTwoStageConverter(Date.class, String.class, InputStream.class);

    //
    // Boolean ->
    //
    final Long LONG_FALSE = new Long(0L);
    final Long LONG_TRUE = new Long(1L);
    addConverter(Boolean.class, Long.class, new TypeConverter.Converter<Boolean, Long>() {
        public Long convert(Boolean source) {
            return source.booleanValue() ? LONG_TRUE : LONG_FALSE;
        }
    });
    addConverter(Boolean.class, String.class, new TypeConverter.Converter<Boolean, String>() {
        public String convert(Boolean source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Boolean.class, String.class, InputStream.class);

    //
    // Character ->
    //
    addConverter(Character.class, String.class, new TypeConverter.Converter<Character, String>() {
        public String convert(Character source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Character.class, String.class, InputStream.class);

    //
    // Duration ->
    //
    addConverter(Duration.class, String.class, new TypeConverter.Converter<Duration, String>() {
        public String convert(Duration source) {
            return source.toString();
        }

    });
    addDynamicTwoStageConverter(Duration.class, String.class, InputStream.class);

    //
    // Byte
    //
    addConverter(Byte.class, String.class, new TypeConverter.Converter<Byte, String>() {
        public String convert(Byte source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Byte.class, String.class, InputStream.class);

    //
    // Short
    //
    addConverter(Short.class, String.class, new TypeConverter.Converter<Short, String>() {
        public String convert(Short source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Short.class, String.class, InputStream.class);

    //
    // Integer
    //
    addConverter(Integer.class, String.class, new TypeConverter.Converter<Integer, String>() {
        public String convert(Integer source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Integer.class, String.class, InputStream.class);

    //
    // Long
    //
    addConverter(Long.class, String.class, new TypeConverter.Converter<Long, String>() {
        public String convert(Long source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Long.class, String.class, InputStream.class);

    //
    // Float
    //
    addConverter(Float.class, String.class, new TypeConverter.Converter<Float, String>() {
        public String convert(Float source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Float.class, String.class, InputStream.class);

    //
    // Double
    //
    addConverter(Double.class, String.class, new TypeConverter.Converter<Double, String>() {
        public String convert(Double source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Double.class, String.class, InputStream.class);

    //
    // BigInteger
    //
    addConverter(BigInteger.class, String.class, new TypeConverter.Converter<BigInteger, String>() {
        public String convert(BigInteger source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(BigInteger.class, String.class, InputStream.class);

    //
    // Calendar
    //
    addConverter(Calendar.class, Date.class, new TypeConverter.Converter<Calendar, Date>() {
        public Date convert(Calendar source) {
            return source.getTime();
        }
    });
    addConverter(Calendar.class, String.class, new TypeConverter.Converter<Calendar, String>() {
        public String convert(Calendar source) {
            try {
                return ISO8601DateFormat.format(source.getTime());
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });

    //
    // BigDecimal
    //
    addConverter(BigDecimal.class, BasicDBObject.class,
            new TypeConverter.Converter<BigDecimal, BasicDBObject>() {
                public BasicDBObject convert(BigDecimal source) {
                    String number = source.toPlainString();
                    int precision = source.precision();
                    BasicDBObject dbObject = new BasicDBObject();
                    dbObject.put("t", "FIXED_POINT");
                    dbObject.put("n", number);
                    dbObject.put("p", precision);
                    return dbObject;
                }
            });
    addConverter(BigDecimal.class, String.class, new TypeConverter.Converter<BigDecimal, String>() {
        public String convert(BigDecimal source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(BigDecimal.class, String.class, InputStream.class);

    //
    // QName
    //
    addConverter(QName.class, String.class, new TypeConverter.Converter<QName, String>() {
        public String convert(QName source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(QName.class, String.class, InputStream.class);

    //
    // EntityRef (NodeRef, ChildAssociationRef, NodeAssociationRef)
    //
    addConverter(EntityRef.class, String.class, new TypeConverter.Converter<EntityRef, String>() {
        public String convert(EntityRef source) {
            return source.toString();
        }
    });
    addConverter(EntityRef.class, BasicDBObject.class, new TypeConverter.Converter<EntityRef, BasicDBObject>() {
        public BasicDBObject convert(EntityRef source) {
            BasicDBObject ret = null;

            if (source instanceof NodeRef) {
                NodeRef nodeRef = (NodeRef) source;

                BasicDBObjectBuilder builder = BasicDBObjectBuilder.start("t", "NODEREF");
                builder.add("p", nodeRef.getStoreRef().getProtocol());
                builder.add("s", nodeRef.getStoreRef().getIdentifier());
                builder.add("id", nodeRef.getId());
                ret = (BasicDBObject) builder.get();
            } else if (source instanceof StoreRef) {
                StoreRef storeRef = (StoreRef) source;

                BasicDBObjectBuilder builder = BasicDBObjectBuilder.start("t", "STOREREF");
                builder.add("p", storeRef.getProtocol());
                builder.add("s", storeRef.getIdentifier());
                ret = (BasicDBObject) builder.get();
            } else {
                throw new IllegalArgumentException();
            }

            return ret;
        }
    });
    addDynamicTwoStageConverter(EntityRef.class, String.class, InputStream.class);

    //
    // ContentData
    //
    addConverter(ContentData.class, String.class, new TypeConverter.Converter<ContentData, String>() {
        public String convert(ContentData source) {
            return source.getInfoUrl();
        }
    });
    addDynamicTwoStageConverter(ContentData.class, String.class, InputStream.class);

    //
    // Path
    //
    addConverter(Path.class, String.class, new TypeConverter.Converter<Path, String>() {
        public String convert(Path source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Path.class, String.class, InputStream.class);

    //
    // Content Reader
    //
    addConverter(ContentReader.class, InputStream.class,
            new TypeConverter.Converter<ContentReader, InputStream>() {
                public InputStream convert(ContentReader source) {
                    return source.getContentInputStream();
                }
            });
    addConverter(ContentReader.class, String.class, new TypeConverter.Converter<ContentReader, String>() {
        public String convert(ContentReader source) {
            // Getting the string from the ContentReader binary is meaningless
            return source.toString();
        }
    });

    //
    // Content Writer
    //
    addConverter(ContentWriter.class, String.class, new TypeConverter.Converter<ContentWriter, String>() {
        public String convert(ContentWriter source) {
            return source.toString();
        }
    });

    addConverter(Collection.class, BasicDBList.class, new TypeConverter.Converter<Collection, BasicDBList>() {
        public BasicDBList convert(Collection source) {
            BasicDBList ret = new BasicDBList();
            for (Object o : source) {
                ret.add(o);
            }
            return ret;
        }
    });

    addConverter(BasicDBList.class, Collection.class, new TypeConverter.Converter<BasicDBList, Collection>() {
        @SuppressWarnings("unchecked")
        public Collection convert(BasicDBList source) {
            Collection ret = new LinkedList();
            for (Object o : source) {
                ret.add(o);
            }
            return ret;
        }
    });

    //
    // Input Stream
    //
    addConverter(InputStream.class, String.class, new TypeConverter.Converter<InputStream, String>() {
        public String convert(InputStream source) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int read;
                while ((read = source.read(buffer)) > 0) {
                    out.write(buffer, 0, read);
                }
                byte[] data = out.toByteArray();
                return new String(data, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new TypeConversionException("Cannot convert input stream to String.", e);
            } catch (IOException e) {
                throw new TypeConversionException("Conversion from stream to string failed", e);
            } finally {
                if (source != null) {
                    try {
                        source.close();
                    } catch (IOException e) {
                        //NOOP
                    }
                }
            }
        }
    });
    addDynamicTwoStageConverter(InputStream.class, String.class, Date.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Double.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Long.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Boolean.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, QName.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Path.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, NodeRef.class);

}

From source file:org.alfresco.serializers.PropertiesTypeConverter.java

@SuppressWarnings("rawtypes")
private PropertiesTypeConverter() {
    ///*from   w w  w.  j a v  a 2  s. c om*/
    // From string
    //
    addConverter(String.class, Class.class, new TypeConverter.Converter<String, Class>() {
        public Class convert(String source) {
            try {
                return Class.forName(source);
            } catch (ClassNotFoundException e) {
                throw new TypeConversionException("Failed to convert string to class: " + source, e);
            }
        }
    });
    addConverter(String.class, Boolean.class, new TypeConverter.Converter<String, Boolean>() {
        public Boolean convert(String source) {
            return Boolean.valueOf(source);
        }
    });
    addConverter(String.class, Character.class, new TypeConverter.Converter<String, Character>() {
        public Character convert(String source) {
            if ((source == null) || (source.length() == 0)) {
                return null;
            }
            return Character.valueOf(source.charAt(0));
        }
    });
    addConverter(String.class, Number.class, new TypeConverter.Converter<String, Number>() {
        public Number convert(String source) {
            try {
                return DecimalFormat.getNumberInstance().parse(source);
            } catch (ParseException e) {
                throw new TypeConversionException("Failed to parse number " + source, e);
            }
        }
    });
    addConverter(String.class, Byte.class, new TypeConverter.Converter<String, Byte>() {
        public Byte convert(String source) {
            return Byte.valueOf(source);
        }
    });
    addConverter(String.class, Short.class, new TypeConverter.Converter<String, Short>() {
        public Short convert(String source) {
            return Short.valueOf(source);
        }
    });
    addConverter(String.class, Integer.class, new TypeConverter.Converter<String, Integer>() {
        public Integer convert(String source) {
            return Integer.valueOf(source);
        }
    });
    addConverter(String.class, Long.class, new TypeConverter.Converter<String, Long>() {
        public Long convert(String source) {
            return Long.valueOf(source);
        }
    });
    addConverter(String.class, Float.class, new TypeConverter.Converter<String, Float>() {
        public Float convert(String source) {
            return Float.valueOf(source);
        }
    });
    addConverter(String.class, Double.class, new TypeConverter.Converter<String, Double>() {
        public Double convert(String source) {
            return Double.valueOf(source);
        }
    });
    addConverter(String.class, BigInteger.class, new TypeConverter.Converter<String, BigInteger>() {
        public BigInteger convert(String source) {
            return new BigInteger(source);
        }
    });
    addConverter(String.class, BigDecimal.class, new TypeConverter.Converter<String, BigDecimal>() {
        public BigDecimal convert(String source) {
            return new BigDecimal(source);
        }
    });
    addConverter(JSON.class, BigDecimal.class, new TypeConverter.Converter<JSON, BigDecimal>() {
        public BigDecimal convert(JSON source) {
            String type = (String) source.get("t");
            if (type.equals("FIXED_POINT")) {
                String number = (String) source.get("n");
                Integer precision = (Integer) source.get("p");
                MathContext ctx = new MathContext(precision);
                return new BigDecimal(number, ctx);
            } else {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a Fixed Decimal object");
            }
        }
    });
    addConverter(String.class, Date.class, new TypeConverter.Converter<String, Date>() {
        public Date convert(String source) {
            try {
                Date date = ISO8601DateFormat.parse(source);
                return date;
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            } catch (AlfrescoRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });
    addConverter(String.class, Duration.class, new TypeConverter.Converter<String, Duration>() {
        public Duration convert(String source) {
            return new Duration(source);
        }
    });
    addConverter(String.class, QName.class, new TypeConverter.Converter<String, QName>() {
        public QName convert(String source) {
            return QName.createQName(source);
        }
    });
    addConverter(JSON.class, QName.class, new TypeConverter.Converter<JSON, QName>() {
        public QName convert(JSON source) {
            String type = (String) source.get("t");
            if (type.equals("QNAME")) {
                String qname = (String) source.get("v");
                return QName.createQName(qname);
            } else {
                throw new IllegalArgumentException();
            }
        }
    });
    addConverter(String.class, ContentData.class, new TypeConverter.Converter<String, ContentData>() {
        public ContentData convert(String source) {
            return ContentData.createContentProperty(source);
        }
    });
    addConverter(String.class, NodeRef.class, new TypeConverter.Converter<String, NodeRef>() {
        public NodeRef convert(String source) {
            return new NodeRef(source);
        }
    });
    addConverter(JSON.class, NodeRef.class, new TypeConverter.Converter<JSON, NodeRef>() {
        public NodeRef convert(JSON source) {
            String type = (String) source.get("t");
            if (!type.equals("NODEREF")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a NodeRef object");
            }
            String protocol = (String) source.get("p");
            String storeId = (String) source.get("s");
            String id = (String) source.get("id");
            NodeRef nodeRef = new NodeRef(new StoreRef(protocol, storeId), id);
            return nodeRef;
        }
    });
    addConverter(String.class, StoreRef.class, new TypeConverter.Converter<String, StoreRef>() {
        public StoreRef convert(String source) {
            return new StoreRef(source);
        }
    });
    addConverter(JSON.class, StoreRef.class, new TypeConverter.Converter<JSON, StoreRef>() {
        public StoreRef convert(JSON source) {
            String type = (String) source.get("t");
            if (!type.equals("STOREREF")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a StoreRef object");
            }
            String protocol = (String) source.get("p");
            String storeId = (String) source.get("s");
            return new StoreRef(protocol, storeId);
        }
    });
    addConverter(String.class, ChildAssociationRef.class,
            new TypeConverter.Converter<String, ChildAssociationRef>() {
                public ChildAssociationRef convert(String source) {
                    return new ChildAssociationRef(source);
                }
            });
    addConverter(String.class, AssociationRef.class, new TypeConverter.Converter<String, AssociationRef>() {
        public AssociationRef convert(String source) {
            return new AssociationRef(source);
        }
    });
    addConverter(String.class, InputStream.class, new TypeConverter.Converter<String, InputStream>() {
        public InputStream convert(String source) {
            try {
                return new ByteArrayInputStream(source.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new TypeConversionException("Encoding not supported", e);
            }
        }
    });
    addConverter(String.class, MLText.class, new TypeConverter.Converter<String, MLText>() {
        public MLText convert(String source) {
            return new MLText(source);
        }
    });
    addConverter(JSON.class, MLText.class, new TypeConverter.Converter<JSON, MLText>() {
        public MLText convert(JSON source) {
            String type = (String) source.get("t");
            if (!type.equals("MLTEXT")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a NodeRef object");
            }

            MLText mlText = new MLText();
            for (String languageTag : source.keySet()) {
                String text = (String) source.get(languageTag);
                Locale locale = Locale.forLanguageTag(languageTag);
                mlText.put(locale, text);
            }

            return mlText;
        }
    });
    //        addConverter(JSON.class, ContentDataWithId.class, new TypeConverter.Converter<JSON, ContentDataWithId>()
    //        {
    //            public ContentDataWithId convert(JSON source)
    //            {
    //                String type = (String)source.get("t");
    //                if(!type.equals("CONTENT_DATA_ID"))
    //                {
    //                    throw new IllegalArgumentException("Invalid source object for conversion "
    //                            + source 
    //                            + ", expected a ContentDataWithId object");
    //                }
    //                String contentUrl = (String)source.get("u");
    //                String mimeType = (String)source.get("m");
    //                Long size = (Long)source.get("s");
    //                String encoding = (String)source.get("e");
    //                String languageTag = (String)source.get("l");
    //                Long id = (Long)source.get("id");
    //                Locale locale = Locale.forLanguageTag(languageTag);
    //
    //                ContentData contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
    //                ContentDataWithId contentDataWithId = new ContentDataWithId(contentData, id);
    //                return contentDataWithId;
    //            }
    //        });
    addConverter(JSON.class, ContentData.class, new TypeConverter.Converter<JSON, ContentData>() {
        public ContentData convert(JSON source) {
            ContentData contentData = null;

            String type = (String) source.get("t");
            if (type.equals("CONTENT")) {
                String contentUrl = (String) source.get("u");
                String mimeType = (String) source.get("m");
                Long size = (Long) source.get("s");
                String encoding = (String) source.get("e");
                String languageTag = (String) source.get("l");
                Locale locale = Locale.forLanguageTag(languageTag);
                contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
            } else if (type.equals("CONTENT_DATA_ID")) {
                String contentUrl = (String) source.get("u");
                String mimeType = (String) source.get("m");
                Long size = (Long) source.get("s");
                String encoding = (String) source.get("e");
                String languageTag = (String) source.get("l");
                Locale locale = Locale.forLanguageTag(languageTag);
                contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
            } else {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a ContentData object");
            }

            return contentData;
        }
    });
    addConverter(JSON.class, String.class, new TypeConverter.Converter<JSON, String>() {
        public String convert(JSON source) {
            // TODO distinguish between different BasicDBObject representations e.g. for MLText, ...

            Set<String> languageTags = source.keySet();
            if (languageTags.size() == 0) {
                throw new IllegalArgumentException("Persisted MLText is invalid " + source);
            } else if (languageTags.size() > 1) {
                // TODO
                logger.warn("Persisted MLText has more than 1 locale " + source);
            }

            String languageTag = languageTags.iterator().next();
            String text = (String) source.get(languageTag);
            return text;
        }
    });
    addConverter(String.class, Locale.class, new TypeConverter.Converter<String, Locale>() {
        public Locale convert(String source) {
            return I18NUtil.parseLocale(source);
        }
    });
    addConverter(String.class, Period.class, new TypeConverter.Converter<String, Period>() {
        public Period convert(String source) {
            return new Period(source);
        }
    });
    addConverter(String.class, VersionNumber.class, new TypeConverter.Converter<String, VersionNumber>() {
        public VersionNumber convert(String source) {
            return new VersionNumber(source);
        }
    });

    //
    // From Locale
    //
    addConverter(Locale.class, String.class, new TypeConverter.Converter<Locale, String>() {
        public String convert(Locale source) {
            String localeStr = source.toString();
            if (localeStr.length() < 6) {
                localeStr += "_";
            }
            return localeStr;
        }
    });

    //
    // From VersionNumber
    //
    addConverter(VersionNumber.class, String.class, new TypeConverter.Converter<VersionNumber, String>() {
        public String convert(VersionNumber source) {
            return source.toString();
        }
    });

    //
    // From MLText
    //
    addConverter(MLText.class, String.class, new TypeConverter.Converter<MLText, String>() {
        public String convert(MLText source) {
            return source.getDefaultValue();
        }
    });

    addConverter(MLText.class, JSON.class, new TypeConverter.Converter<MLText, JSON>() {
        public JSON convert(MLText source) {
            JSON map = new JSON();
            map.put("t", "MLTEXT");
            for (Map.Entry<Locale, String> entry : source.entrySet()) {
                map.put(entry.getKey().toLanguageTag(), entry.getValue());
            }
            return map;
        }
    });

    //        addConverter(ContentDataWithId.class, JSON.class, new TypeConverter.Converter<ContentDataWithId, JSON>()
    //        {
    //            public JSON convert(ContentDataWithId source)
    //            {
    //                JSON map = new JSON();
    //
    //                String contentUrl = source.getContentUrl();
    //                Long id = source.getId();
    //                String languageTag = source.getLocale().toLanguageTag();
    //                String encoding = source.getEncoding();
    //                long size = source.getSize();
    //                String mimeType = source.getMimetype();
    //
    //                map.put("t", "CONTENT_DATA_ID");
    //                map.put("u", contentUrl);
    //                map.put("m", mimeType);
    //                map.put("s", size);
    //                map.put("e", encoding);
    //                map.put("l", languageTag);
    //                map.put("id", id);
    //                return map;
    //            }
    //        });

    addConverter(ContentData.class, JSON.class, new TypeConverter.Converter<ContentData, JSON>() {
        public JSON convert(ContentData source) {
            JSON map = new JSON();

            String contentUrl = source.getContentUrl();
            String languageTag = source.getLocale().toLanguageTag();
            String encoding = source.getEncoding();
            long size = source.getSize();
            String mimeType = source.getMimetype();

            map.put("t", "CONTENT_DATA");
            map.put("u", contentUrl);
            map.put("m", mimeType);
            map.put("s", size);
            map.put("e", encoding);
            map.put("l", languageTag);
            return map;
        }
    });

    //
    // From enum
    //
    addConverter(Enum.class, String.class, new TypeConverter.Converter<Enum, String>() {
        public String convert(Enum source) {
            return source.toString();
        }
    });

    // From Period
    addConverter(Period.class, String.class, new TypeConverter.Converter<Period, String>() {
        public String convert(Period source) {
            return source.toString();
        }
    });

    // From Class
    addConverter(Class.class, String.class, new TypeConverter.Converter<Class, String>() {
        public String convert(Class source) {
            return source.getName();
        }
    });

    //
    // Number to Subtypes and Date
    //
    addConverter(Number.class, Boolean.class, new TypeConverter.Converter<Number, Boolean>() {
        public Boolean convert(Number source) {
            return new Boolean(source.longValue() > 0);
        }
    });
    addConverter(Number.class, Byte.class, new TypeConverter.Converter<Number, Byte>() {
        public Byte convert(Number source) {
            return Byte.valueOf(source.byteValue());
        }
    });
    addConverter(Number.class, Short.class, new TypeConverter.Converter<Number, Short>() {
        public Short convert(Number source) {
            return Short.valueOf(source.shortValue());
        }
    });
    addConverter(Number.class, Integer.class, new TypeConverter.Converter<Number, Integer>() {
        public Integer convert(Number source) {
            return Integer.valueOf(source.intValue());
        }
    });
    addConverter(Number.class, Long.class, new TypeConverter.Converter<Number, Long>() {
        public Long convert(Number source) {
            return Long.valueOf(source.longValue());
        }
    });
    addConverter(Number.class, Float.class, new TypeConverter.Converter<Number, Float>() {
        public Float convert(Number source) {
            return Float.valueOf(source.floatValue());
        }
    });
    addConverter(Number.class, Double.class, new TypeConverter.Converter<Number, Double>() {
        public Double convert(Number source) {
            return Double.valueOf(source.doubleValue());
        }
    });
    addConverter(Number.class, Date.class, new TypeConverter.Converter<Number, Date>() {
        public Date convert(Number source) {
            return new Date(source.longValue());
        }
    });
    addConverter(Number.class, String.class, new TypeConverter.Converter<Number, String>() {
        public String convert(Number source) {
            return source.toString();
        }
    });
    addConverter(Number.class, BigInteger.class, new TypeConverter.Converter<Number, BigInteger>() {
        public BigInteger convert(Number source) {
            if (source instanceof BigDecimal) {
                return ((BigDecimal) source).toBigInteger();
            } else {
                return BigInteger.valueOf(source.longValue());
            }
        }
    });
    addConverter(Number.class, BigDecimal.class, new TypeConverter.Converter<Number, BigDecimal>() {
        public BigDecimal convert(Number source) {
            if (source instanceof BigInteger) {
                return new BigDecimal((BigInteger) source);
            } else if (source instanceof Double) {
                return BigDecimal.valueOf((Double) source);
            } else if (source instanceof Float) {
                Float val = (Float) source;
                if (val.isInfinite()) {
                    // What else can we do here?  this is 3.4 E 38 so is fairly big
                    return new BigDecimal(Float.MAX_VALUE);
                }
                return BigDecimal.valueOf((Float) source);
            } else {
                return BigDecimal.valueOf(source.longValue());
            }
        }
    });
    addDynamicTwoStageConverter(Number.class, String.class, InputStream.class);

    //
    // Date, Timestamp ->
    //
    addConverter(Timestamp.class, Date.class, new TypeConverter.Converter<Timestamp, Date>() {
        public Date convert(Timestamp source) {
            return new Date(source.getTime());
        }
    });
    addConverter(Date.class, Number.class, new TypeConverter.Converter<Date, Number>() {
        public Number convert(Date source) {
            return Long.valueOf(source.getTime());
        }
    });
    addConverter(Date.class, String.class, new TypeConverter.Converter<Date, String>() {
        public String convert(Date source) {
            try {
                return ISO8601DateFormat.format(source);
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });
    addConverter(Date.class, Calendar.class, new TypeConverter.Converter<Date, Calendar>() {
        public Calendar convert(Date source) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(source);
            return calendar;
        }
    });

    addConverter(Date.class, GregorianCalendar.class, new TypeConverter.Converter<Date, GregorianCalendar>() {
        public GregorianCalendar convert(Date source) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(source);
            return calendar;
        }
    });
    addDynamicTwoStageConverter(Date.class, String.class, InputStream.class);

    //
    // Boolean ->
    //
    final Long LONG_FALSE = new Long(0L);
    final Long LONG_TRUE = new Long(1L);
    addConverter(Boolean.class, Long.class, new TypeConverter.Converter<Boolean, Long>() {
        public Long convert(Boolean source) {
            return source.booleanValue() ? LONG_TRUE : LONG_FALSE;
        }
    });
    addConverter(Boolean.class, String.class, new TypeConverter.Converter<Boolean, String>() {
        public String convert(Boolean source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Boolean.class, String.class, InputStream.class);

    //
    // Character ->
    //
    addConverter(Character.class, String.class, new TypeConverter.Converter<Character, String>() {
        public String convert(Character source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Character.class, String.class, InputStream.class);

    //
    // Duration ->
    //
    addConverter(Duration.class, String.class, new TypeConverter.Converter<Duration, String>() {
        public String convert(Duration source) {
            return source.toString();
        }

    });
    addDynamicTwoStageConverter(Duration.class, String.class, InputStream.class);

    //
    // Byte
    //
    addConverter(Byte.class, String.class, new TypeConverter.Converter<Byte, String>() {
        public String convert(Byte source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Byte.class, String.class, InputStream.class);

    //
    // Short
    //
    addConverter(Short.class, String.class, new TypeConverter.Converter<Short, String>() {
        public String convert(Short source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Short.class, String.class, InputStream.class);

    //
    // Integer
    //
    addConverter(Integer.class, String.class, new TypeConverter.Converter<Integer, String>() {
        public String convert(Integer source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Integer.class, String.class, InputStream.class);

    //
    // Long
    //
    addConverter(Long.class, String.class, new TypeConverter.Converter<Long, String>() {
        public String convert(Long source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Long.class, String.class, InputStream.class);

    //
    // Float
    //
    addConverter(Float.class, String.class, new TypeConverter.Converter<Float, String>() {
        public String convert(Float source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Float.class, String.class, InputStream.class);

    //
    // Double
    //
    addConverter(Double.class, String.class, new TypeConverter.Converter<Double, String>() {
        public String convert(Double source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Double.class, String.class, InputStream.class);

    //
    // BigInteger
    //
    addConverter(BigInteger.class, String.class, new TypeConverter.Converter<BigInteger, String>() {
        public String convert(BigInteger source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(BigInteger.class, String.class, InputStream.class);

    //
    // Calendar
    //
    addConverter(Calendar.class, Date.class, new TypeConverter.Converter<Calendar, Date>() {
        public Date convert(Calendar source) {
            return source.getTime();
        }
    });
    addConverter(Calendar.class, String.class, new TypeConverter.Converter<Calendar, String>() {
        public String convert(Calendar source) {
            try {
                return ISO8601DateFormat.format(source.getTime());
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });

    //
    // BigDecimal
    //
    addConverter(BigDecimal.class, JSON.class, new TypeConverter.Converter<BigDecimal, JSON>() {
        public JSON convert(BigDecimal source) {
            String number = source.toPlainString();
            int precision = source.precision();
            JSON map = new JSON();
            map.put("t", "FIXED_POINT");
            map.put("n", number);
            map.put("p", precision);
            return map;
        }
    });
    addConverter(BigDecimal.class, String.class, new TypeConverter.Converter<BigDecimal, String>() {
        public String convert(BigDecimal source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(BigDecimal.class, String.class, InputStream.class);

    //
    // QName
    //
    addConverter(QName.class, String.class, new TypeConverter.Converter<QName, String>() {
        public String convert(QName source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(QName.class, String.class, InputStream.class);

    //
    // EntityRef (NodeRef, ChildAssociationRef, NodeAssociationRef)
    //
    addConverter(EntityRef.class, String.class, new TypeConverter.Converter<EntityRef, String>() {
        public String convert(EntityRef source) {
            return source.toString();
        }
    });
    addConverter(EntityRef.class, JSON.class, new TypeConverter.Converter<EntityRef, JSON>() {
        public JSON convert(EntityRef source) {
            JSON ret = null;

            if (source instanceof NodeRef) {
                NodeRef nodeRef = (NodeRef) source;

                JSON map = new JSON();
                map.put("t", "NODEREF");
                map.put("p", nodeRef.getStoreRef().getProtocol());
                map.put("s", nodeRef.getStoreRef().getIdentifier());
                map.put("id", nodeRef.getId());
                ret = map;
            } else if (source instanceof StoreRef) {
                StoreRef storeRef = (StoreRef) source;

                JSON map = new JSON();
                map.put("t", "STOREREF");
                map.put("p", storeRef.getProtocol());
                map.put("s", storeRef.getIdentifier());
                ret = map;
            } else {
                throw new IllegalArgumentException();
            }

            return ret;
        }
    });
    addDynamicTwoStageConverter(EntityRef.class, String.class, InputStream.class);

    //
    // ContentData
    //
    addConverter(ContentData.class, String.class, new TypeConverter.Converter<ContentData, String>() {
        public String convert(ContentData source) {
            return source.getInfoUrl();
        }
    });
    addDynamicTwoStageConverter(ContentData.class, String.class, InputStream.class);

    //
    // Path
    //
    addConverter(Path.class, String.class, new TypeConverter.Converter<Path, String>() {
        public String convert(Path source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Path.class, String.class, InputStream.class);

    //
    // Content Reader
    //
    addConverter(ContentReader.class, InputStream.class,
            new TypeConverter.Converter<ContentReader, InputStream>() {
                public InputStream convert(ContentReader source) {
                    return source.getContentInputStream();
                }
            });
    addConverter(ContentReader.class, String.class, new TypeConverter.Converter<ContentReader, String>() {
        public String convert(ContentReader source) {
            // Getting the string from the ContentReader binary is meaningless
            return source.toString();
        }
    });

    //
    // Content Writer
    //
    addConverter(ContentWriter.class, String.class, new TypeConverter.Converter<ContentWriter, String>() {
        public String convert(ContentWriter source) {
            return source.toString();
        }
    });

    //        addConverter(Collection.class, BasicDBList.class, new TypeConverter.Converter<Collection, BasicDBList>()
    //        {
    //            public BasicDBList convert(Collection source)
    //            {
    //                BasicDBList ret = new BasicDBList();
    //                for(Object o : source)
    //                {
    //                    ret.add(o);
    //                }
    //                return ret;
    //            }
    //        });

    //        addConverter(BasicDBList.class, Collection.class, new TypeConverter.Converter<BasicDBList, Collection>()
    //        {
    //            @SuppressWarnings("unchecked")
    //            public Collection convert(BasicDBList source)
    //            {
    //                Collection ret = new LinkedList();
    //                for(Object o : source)
    //                {
    //                    ret.add(o);
    //                }
    //                return ret;
    //            }
    //        });

    //
    // Input Stream
    //
    addConverter(InputStream.class, String.class, new TypeConverter.Converter<InputStream, String>() {
        public String convert(InputStream source) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int read;
                while ((read = source.read(buffer)) > 0) {
                    out.write(buffer, 0, read);
                }
                byte[] data = out.toByteArray();
                return new String(data, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new TypeConversionException("Cannot convert input stream to String.", e);
            } catch (IOException e) {
                throw new TypeConversionException("Conversion from stream to string failed", e);
            } finally {
                if (source != null) {
                    try {
                        source.close();
                    } catch (IOException e) {
                        //NOOP
                    }
                }
            }
        }
    });
    addDynamicTwoStageConverter(InputStream.class, String.class, Date.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Double.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Long.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Boolean.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, QName.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Path.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, NodeRef.class);

}

From source file:eu.uqasar.util.UQasarUtil.java

/**
 * //w w  w . j a  va2  s  .  c o  m
 * @param node Node whose value is studied
 * @return
 */
private static Multimap<SuggestionType, Object> getSuggestionForNode(TreeNode node) {

    // For storing the suggestion type and the payload
    Multimap<SuggestionType, Object> suggestionsMultimap = ArrayListMultimap.create();

    final String EMPTY = "";

    try {
        InitialContext ic = new InitialContext();
        ProjectSimilarityService projectSimilarityService = (ProjectSimilarityService) ic
                .lookup("java:module/ProjectSimilarityService");
        QualityObjectiveSimilarityService qoSimilarityService = (QualityObjectiveSimilarityService) ic
                .lookup("java:module/QualityObjectiveSimilarityService");
        //TODO: Finding similar metrics

        if (node instanceof QualityObjective) {
            QualityObjective qo = (QualityObjective) node;
            Float value = qo.getValue();

            // If the value of a quality objective cannot be computed, 
            // attempt to obtain a suggestion             
            if (value == null || value.isNaN()) {
                // Attempt to find a suitable project 
                Project proj = qo.getProject();
                Project similarProject = null;
                if (proj != null) {
                    // Get a list of similar projects
                    List<Project> similarProjects = projectSimilarityService.getSimilarProjects(proj);
                    if (similarProjects != null && similarProjects.size() > 0) {
                        // For now obtain the first suitable project
                        similarProject = similarProjects.get(0);
                    }
                }

                // If a suitable similar project was found, search for similar Quality Objective(s) to be suggested
                if (similarProject != null) {
                    // Get similar QOs from a similar project
                    List<QualityObjective> qos = qoSimilarityService.getSimilarQOs(qo, similarProject);
                    // If results were found, construct a suggestion (for now obtain the first one). 
                    if (qos != null && qos.size() > 0) {
                        suggestionsMultimap.put(SuggestionType.QO_REPLACE, qos.get(0));
                        return suggestionsMultimap;
                    }
                }

                // Otherwise suggest the QO to be removed
                suggestionsMultimap.put(SuggestionType.QO_REMOVE, null);
                return suggestionsMultimap;
            }
        }
        // if a metric has no value / the value is 0, return a suggestion to 
        // remove the metric 
        if (node instanceof Metric) {

            Metric metric = (Metric) node;
            Float value = metric.getValue();

            if (value == null || value.isNaN() || value.isInfinite()) {
                suggestionsMultimap.put(SuggestionType.METRIC_REMOVE, null);
                return suggestionsMultimap;
            }
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }

    // If no suggestion is to be provided, return an empty string 
    // (overwrite the possible existing suggestion). 
    suggestionsMultimap.put(SuggestionType.NO_SUGGESTION, "");
    return suggestionsMultimap;
}