Example usage for java.lang Double TYPE

List of usage examples for java.lang Double TYPE

Introduction

In this page you can find the example usage for java.lang Double TYPE.

Prototype

Class TYPE

To view the source code for java.lang Double TYPE.

Click Source Link

Document

The Class instance representing the primitive type double .

Usage

From source file:io.nuun.plugin.configuration.common.ConfigurationMembersInjector.java

@Override
public void injectMembers(T instance) {
    NuunProperty injectConfigAnnotation = null;
    // The annotation is actual NuunProperty.class
    if (clonedAnno.annotationType() == NuunProperty.class) {
        injectConfigAnnotation = field.getAnnotation(NuunProperty.class);
    } else { // The annotation has the NuunProperty annotation on it we proxy it
        injectConfigAnnotation = AssertUtils.annotationProxyOf(NuunProperty.class, clonedAnno);
    }/*from   www. j  ava  2s .  c o  m*/

    String configurationParameterName = injectConfigAnnotation.value();

    // Pre verification //
    if (StringUtils.isEmpty(configurationParameterName)) {
        log.error("Value for annotation {} on field {} can not be null or empty.", clonedAnno.annotationType(),
                field.toGenericString());
        throw new PluginException("Value for annotation %s on field %s can not be null or empty.",
                clonedAnno.annotationType(), field.toGenericString());
    }

    if (!configuration.containsKey(configurationParameterName) && injectConfigAnnotation.mandatory()) {
        throw new PluginException("\"%s\" must be in one properties file for field %s.",
                configurationParameterName, field.toGenericString());
    }

    try {
        this.field.setAccessible(true);
        Class<?> type = field.getType();
        if (type == Integer.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setInt(instance, configuration.getInt(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setInt(instance, injectConfigAnnotation.defaultIntValue());
            }
        } else if (type == Integer.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Integer(configuration.getInt(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Integer(injectConfigAnnotation.defaultIntValue()));
            }
        } else if (type == Boolean.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setBoolean(instance, configuration.getBoolean(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setBoolean(instance, injectConfigAnnotation.defaultBooleanValue());
            }

        } else if (type == Boolean.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Boolean(configuration.getBoolean(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Boolean(injectConfigAnnotation.defaultBooleanValue()));
            }

        } else if (type == Short.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setShort(instance, configuration.getShort(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setShort(instance, injectConfigAnnotation.defaultShortValue());
            }
        } else if (type == Short.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Short(configuration.getShort(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Short(injectConfigAnnotation.defaultShortValue()));
            }
        } else if (type == Byte.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setByte(instance, configuration.getByte(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setByte(instance, injectConfigAnnotation.defaultByteValue());
            }
        } else if (type == Byte.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Byte(configuration.getByte(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Byte(injectConfigAnnotation.defaultByteValue()));
            }
        } else if (type == Long.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setLong(instance, configuration.getLong(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setLong(instance, injectConfigAnnotation.defaultLongValue());
            }
        } else if (type == Long.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Long(configuration.getLong(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Long(injectConfigAnnotation.defaultLongValue()));
            }
        } else if (type == Float.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setFloat(instance, configuration.getFloat(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setFloat(instance, injectConfigAnnotation.defaultFloatValue());
            }
        } else if (type == Float.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Float(configuration.getFloat(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Float(injectConfigAnnotation.defaultFloatValue()));
            }
        } else if (type == Double.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setDouble(instance, configuration.getDouble(configurationParameterName));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.setDouble(instance, injectConfigAnnotation.defaultDoubleValue());
            }
        } else if (type == Double.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance, new Double(configuration.getDouble(configurationParameterName)));
            } else {
                log.debug(NO_PROPERTY_FOUND_LOG_MESSAGE, configurationParameterName);
                field.set(instance, new Double(injectConfigAnnotation.defaultDoubleValue()));
            }
        } else if (type == Character.TYPE) {
            if (configuration.containsKey(configurationParameterName)) {
                field.setChar(instance, configuration.getString(configurationParameterName).charAt(0));
            }
        } else if (type == Character.class) {
            if (configuration.containsKey(configurationParameterName)) {
                field.set(instance,
                        new Character(configuration.getString(configurationParameterName).charAt(0)));
            }
        } else {
            Object property = getProperty(configurationParameterName, injectConfigAnnotation);
            field.set(instance, property);
        }
    } catch (IllegalArgumentException ex) {
        log.error("Wrong argument or argument type during configuration injection", ex);
    } catch (IllegalAccessException ex) {
        log.error("Illegal access during configuration injection", ex);
    } catch (InstantiationException ex) {
        log.error("Impossible to instantiate value converter", ex);
    } finally {
        this.field.setAccessible(false);
    }
}

From source file:org.robobinding.util.ClassUtils.java

/**
 * <p>//from www  . j  a  va 2  s.c  o m
 * Checks if one {@code Class} can be assigned to a variable of another
 * {@code Class}.
 * </p>
 * 
 * <p>
 * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
 * method takes into account widenings of primitive classes and {@code null}
 * s.
 * </p>
 * 
 * <p>
 * Primitive widenings allow an int to be assigned to a long, float or
 * double. This method returns the correct result for these cases.
 * </p>
 * 
 * <p>
 * {@code Null} may be assigned to any reference type. This method will
 * return {@code true} if {@code null} is passed in and the toClass is
 * non-primitive.
 * </p>
 * 
 * <p>
 * Specifically, this method tests whether the type represented by the
 * specified {@code Class} parameter can be converted to the type
 * represented by this {@code Class} object via an identity conversion
 * widening primitive or widening reference conversion. See
 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>
 * , sections 5.1.1, 5.1.2 and 5.1.4 for details.
 * </p>
 * 
 * @param cls
 *            the Class to check, may be null
 * @param toClass
 *            the Class to try to assign into, returns false if null
 * @param autoboxing
 *            whether to use implicit autoboxing/unboxing between primitives
 *            and wrappers
 * @return {@code true} if assignment possible
 */
public static boolean isAssignable(Class<?> cls, final Class<?> toClass, final boolean autoboxing) {
    if (toClass == null) {
        return false;
    }
    // have to check for null, as isAssignableFrom doesn't
    if (cls == null) {
        return !toClass.isPrimitive();
    }
    // autoboxing:
    if (autoboxing) {
        if (cls.isPrimitive() && !toClass.isPrimitive()) {
            cls = primitiveToWrapper(cls);
            if (cls == null) {
                return false;
            }
        }
        if (toClass.isPrimitive() && !cls.isPrimitive()) {
            cls = wrapperToPrimitive(cls);
            if (cls == null) {
                return false;
            }
        }
    }
    if (cls.equals(toClass)) {
        return true;
    }
    if (cls.isPrimitive()) {
        if (toClass.isPrimitive() == false) {
            return false;
        }
        if (Integer.TYPE.equals(cls)) {
            return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
        }
        if (Long.TYPE.equals(cls)) {
            return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
        }
        if (Boolean.TYPE.equals(cls)) {
            return false;
        }
        if (Double.TYPE.equals(cls)) {
            return false;
        }
        if (Float.TYPE.equals(cls)) {
            return Double.TYPE.equals(toClass);
        }
        if (Character.TYPE.equals(cls)) {
            return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass)
                    || Double.TYPE.equals(toClass);
        }
        if (Short.TYPE.equals(cls)) {
            return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass)
                    || Double.TYPE.equals(toClass);
        }
        if (Byte.TYPE.equals(cls)) {
            return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass)
                    || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
        }
        // should never get here
        return false;
    }
    return toClass.isAssignableFrom(cls);
}

From source file:org.jdto.util.ClassUtils.java

/**
 * <p>Checks if one/*from   www.ja  va2s . c  om*/
 * <code>Class</code> can be assigned to a variable of another
 * <code>Class</code>.</p>
 *
 * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
 * this method takes into account widenings of primitive classes and
 * <code>null</code>s.</p>
 *
 * <p>Primitive widenings allow an int to be assigned to a long, float or
 * double. This method returns the correct result for these cases.</p>
 *
 * <p><code>Null</code> may be assigned to any reference type. This method
 * will return
 * <code>true</code> if
 * <code>null</code> is passed in and the toClass is non-primitive.</p>
 *
 * <p>Specifically, this method tests whether the type represented by the
 * specified
 * <code>Class</code> parameter can be converted to the type represented by
 * this
 * <code>Class</code> object via an identity conversion widening primitive
 * or widening reference conversion. See <em><a
 * href="http://java.sun.com/docs/books/jls/">The Java Language
 * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
 *
 * @param cls the Class to check, may be null
 * @param toClass the Class to try to assign into, returns false if null
 * @param autoboxing whether to use implicit autoboxing/unboxing between
 * primitives and wrappers
 * @return
 * <code>true</code> if assignment possible
 * @since 2.5
 */
public static boolean isAssignable(Class cls, Class toClass, boolean autoboxing) {
    if (toClass == null) {
        return false;
    }
    // have to check for null, as isAssignableFrom doesn't
    if (cls == null) {
        return !(toClass.isPrimitive());
    }
    //autoboxing:
    if (autoboxing) {
        if (cls.isPrimitive() && !toClass.isPrimitive()) {
            cls = primitiveToWrapper(cls);
            if (cls == null) {
                return false;
            }
        }
        if (toClass.isPrimitive() && !cls.isPrimitive()) {
            cls = wrapperToPrimitive(cls);
            if (cls == null) {
                return false;
            }
        }
    }
    if (cls.equals(toClass)) {
        return true;
    }
    if (cls.isPrimitive()) {
        if (toClass.isPrimitive() == false) {
            return false;
        }
        if (Integer.TYPE.equals(cls)) {
            return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
        }
        if (Long.TYPE.equals(cls)) {
            return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
        }
        if (Boolean.TYPE.equals(cls)) {
            return false;
        }
        if (Double.TYPE.equals(cls)) {
            return false;
        }
        if (Float.TYPE.equals(cls)) {
            return Double.TYPE.equals(toClass);
        }
        if (Character.TYPE.equals(cls)) {
            return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass)
                    || Double.TYPE.equals(toClass);
        }
        if (Short.TYPE.equals(cls)) {
            return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass)
                    || Double.TYPE.equals(toClass);
        }
        if (Byte.TYPE.equals(cls)) {
            return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass)
                    || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
        }
        // should never get here
        return false;
    }
    return toClass.isAssignableFrom(cls);
}

From source file:org.openspaces.rest.utils.ControllerUtils.java

public static Object convertPropertyToPrimitiveType(String object, Class type, String propKey) {
    if (type.equals(Long.class) || type.equals(Long.TYPE))
        return Long.valueOf(object);

    if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
        return Boolean.valueOf(object);

    if (type.equals(Integer.class) || type.equals(Integer.TYPE))
        return Integer.valueOf(object);

    if (type.equals(Byte.class) || type.equals(Byte.TYPE))
        return Byte.valueOf(object);

    if (type.equals(Short.class) || type.equals(Short.TYPE))
        return Short.valueOf(object);

    if (type.equals(Float.class) || type.equals(Float.TYPE))
        return Float.valueOf(object);

    if (type.equals(Double.class) || type.equals(Double.TYPE))
        return Double.valueOf(object);

    if (type.isEnum())
        return Enum.valueOf(type, object);

    if (type.equals(String.class) || type.equals(Object.class))
        return String.valueOf(object);

    if (type.equals(java.util.Date.class)) {
        try {/*from   ww  w .ja va2 s. c  om*/
            return simpleDateFormat.parse(object);
        } catch (ParseException e) {
            throw new RestException(
                    "Unable to parse date [" + object + "]. Make sure it matches the format: " + date_format);
        }
    }

    //unknown type
    throw new UnsupportedTypeException("Non primitive type when converting property [" + propKey + "]:" + type);
}

From source file:org.apache.struts.action.TestDynaActionForm.java

/**
 * Positive getDynaProperty on property <code>doubleProperty</code>.
 *///from  www . j  a v  a2s.  c o  m
public void testGetDescriptorDouble() {
    testGetDescriptorBase("doubleProperty", Double.TYPE);
}

From source file:ca.sqlpower.architect.swingui.TestPlayPenComponent.java

/**
 * Returns true if an instance of the given property type is of a mutable class.
 * Throws an exception if it lacks a case for the given type.
 * //from   w  w w  .ja  va  2s  . c o  m
 * @param property The property that should be checked for mutability.
 */
private boolean isPropertyInstanceMutable(PropertyDescriptor property) {
    if (property.getPropertyType() == String.class) {
        return false;
    } else if (property.getPropertyType().isAssignableFrom(Enum.class)) {
        return false;
    } else if (property.getPropertyType() == Boolean.class || property.getPropertyType() == Boolean.TYPE) {
        return false;
    } else if (property.getPropertyType() == Integer.class || property.getPropertyType() == Integer.TYPE) {
        return false;
    } else if (property.getPropertyType() == Double.class || property.getPropertyType() == Double.TYPE) {
        return false;
    } else if (property.getPropertyType() == Color.class) {
        return false;
    } else if (property.getPropertyType() == Font.class) {
        return false;
    } else if (property.getPropertyType() == Point.class) {
        return true;
    } else if (property.getPropertyType() == Dimension.class) {
        return true;
    } else if (property.getPropertyType() == Insets.class) {
        return true;
    } else if (property.getPropertyType() == Set.class) {
        return true;
    } else if (property.getPropertyType() == List.class) {
        return true;
    } else if (property.getPropertyType() == TablePane.class) {
        return true;
    } else if (property.getPropertyType() == SQLTable.class) {
        return true;
    } else if (property.getPropertyType() == JPopupMenu.class) {
        return true;
    }
    if (property.getName().equals("model")) {
        return true;
    }
    throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
            + property.getPropertyType().getName() + ") in isPropertyInstanceMutable()");
}

From source file:com.projity.field.FieldConverter.java

private FieldConverter() {
    instance = this;
    stringConverter = new StringConverter(false);
    compactStringConverter = new StringConverter(true);
    ConvertUtils.register(stringConverter, String.class); // Wrapper class
    ConvertUtils.register(new DateConverter(), Date.class); // Wrapper class
    ConvertUtils.register(new CalendarConverter(), GregorianCalendar.class); // Wrapper class
    ConvertUtils.register(new DurationConverter(), Duration.class); // Wrapper class
    ConvertUtils.register(new WorkConverter(), Work.class); // Wrapper class
    ConvertUtils.register(new MoneyConverter(), Money.class); // Wrapper class
    Converter longConverter = new LongConverter();
    ConvertUtils.register(longConverter, Long.TYPE); // Native type
    ConvertUtils.register(longConverter, Long.class); // Wrapper class
    Converter doubleConverter = new DoubleConverter();
    ConvertUtils.register(doubleConverter, Double.TYPE); // Native type
    ConvertUtils.register(doubleConverter, Double.class); // Wrapper class

    // short context converters
    HashMap<Class, Converter> compactMap = new HashMap<Class, Converter>();
    contextMaps.put(COMPACT_CONVERTER_CONTEXT, compactMap);
    compactMap.put(String.class, compactStringConverter);
    // no need for duration or money as parsing is done in long form

}

From source file:RealFunctionValidation.java

public static SummaryStatistics assessAccuracy(final Method method, final DataInputStream in,
        final DataOutputStream out)
        throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    if (method.getReturnType() != Double.TYPE) {
        throw new IllegalArgumentException("method must return a double");
    }//  ww  w .j  av a  2 s .co  m

    final Class<?>[] types = method.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        if (!types[i].isPrimitive()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("argument #").append(i + 1).append(" of method ").append(method.getName())
                    .append("must be of primitive of type");
            throw new IllegalArgumentException(builder.toString());
        }
    }

    final SummaryStatistics stat = new SummaryStatistics();
    final Object[] parameters = new Object[types.length];
    while (true) {
        try {
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = readAndWritePrimitiveValue(in, out, types[i]);
            }
            final double expected = in.readDouble();
            if (FastMath.abs(expected) > 1E-16) {
                final Object value = method.invoke(null, parameters);
                final double actual = ((Double) value).doubleValue();
                final double err = FastMath.abs(actual - expected);
                final double ulps = err / FastMath.ulp(expected);
                out.writeDouble(expected);
                out.writeDouble(actual);
                out.writeDouble(ulps);
                stat.addValue(ulps);
            }
        } catch (EOFException e) {
            break;
        }
    }
    return stat;
}

From source file:org.romaframework.core.schema.SchemaField.java

protected Object convertValue(Object iFieldValue) {
    if (type == null || isArray())
        return iFieldValue;

    SchemaClass typeClass = getType().getSchemaClass();
    if (typeClass.equals(Roma.schema().getSchemaClass(iFieldValue)))
        return iFieldValue;

    String textValue = null;//from w  ww. j  a  v  a 2s  .co  m
    if (iFieldValue instanceof String) {
        textValue = (String) iFieldValue;
    } else if (iFieldValue != null) {
        textValue = iFieldValue.toString();
    }

    Object value = null;

    if (textValue != null) {
        // TRY A SOFT CONVERSION
        if (typeClass.isOfType(Integer.class) || typeClass.isOfType(Integer.TYPE)) {
            try {
                value = textValue.equals("") ? null : Integer.parseInt(textValue);
            } catch (Exception e) {
                value = textValue.equals("") ? null : Double.valueOf(textValue).intValue();
            }
        } else if (typeClass.isOfType(Long.class) || typeClass.isOfType(Long.TYPE)) {
            value = textValue.equals("") ? null : Long.parseLong(textValue);
        } else if (typeClass.isOfType(Short.class) || typeClass.isOfType(Short.TYPE)) {
            value = textValue.equals("") ? null : Short.parseShort(textValue);
        } else if (typeClass.isOfType(Byte.class) || typeClass.isOfType(Byte.TYPE)) {
            value = textValue.equals("") ? null : Byte.parseByte(textValue);
        } else if (typeClass.isOfType(Character.class) || typeClass.isOfType(Character.TYPE)) {
            if (textValue.length() > 0) {
                value = new Character(textValue.charAt(0));
            }
        } else if (typeClass.isOfType(Float.class) || typeClass.isOfType(Float.TYPE)) {
            value = textValue.equals("") ? null : Float.parseFloat(textValue);
        } else if (typeClass.isOfType(Double.class) || typeClass.isOfType(Double.TYPE)) {
            value = textValue.equals("") ? null : Double.parseDouble(textValue);
        } else if (typeClass.isOfType(BigDecimal.class)) {
            value = textValue.equals("") ? null : new BigDecimal(textValue);
        } else if (iFieldValue != null && !typeClass.isArray() && iFieldValue.getClass().isArray()) {
            // DESTINATION VALUE IS NOT AN ARRAY: ASSIGN THE FIRST ONE ELEMENT
            value = ((Object[]) iFieldValue)[0];
        } else {
            value = iFieldValue;
        }
    }

    if (value != null) {
        // TODO is this the right place to do this...?
        Class<?> valueClass = value.getClass();
        // SUCH A MONSTER!!! MOVE THIS LOGIC IN SchemaClass.isAssignableFrom...
        if (value instanceof VirtualObject
                && !(typeClass.getLanguageType() instanceof Class<?>
                        && ((Class<?>) typeClass.getLanguageType()).isAssignableFrom(VirtualObject.class))
                && ((VirtualObject) value).getSuperClassObject() != null) {
            if (ComposedEntity.class
                    .isAssignableFrom(((VirtualObject) value).getSuperClassObject().getClass())) {
                value = ((VirtualObject) value).getSuperClassObject();
                valueClass = value.getClass();
            }
        }

        if (value instanceof ComposedEntity<?> && !typeClass.isAssignableFrom(valueClass)) {
            value = ((ComposedEntity<?>) value).getEntity();
        }
    }

    if (value == null && typeClass.isPrimitive()) {
        log.warn("Cannot set the field value to null for primitive types! Field: " + getEntity() + "." + name
                + " of class " + getType().getName() + ". Setting value to 0.");
        // SET THE VALUE TO 0
        value = SchemaHelper.assignDefaultValueToLiteral(typeClass);
    }
    return value;
}

From source file:org.eclipse.ice.viz.service.csv.CSVPlot.java

/**
 * Attempts to load the CSV series data from the specified file. This
 * operation ignores all data that is marked as comments (i.e. if the line
 * starts with #), and ignores comments after the data in a line as well.
 * This operation takes the first column of CSV data as the independent
 * series, and the rest as normal, dependent series to be added to the plot.
 * Note that only the first dependent series (the second column) will be
 * initially enabled to be drawn on the plot editor.
 * /*  w ww .ja  v a  2  s. co  m*/
 * @param file
 *            The file to load, assumed to be a valid file.
 */
private void load(File file) {
    // Initially set the name to the file name.
    String plotName = file.getName();
    setPlotTitle(plotName);

    // Configure the list
    ArrayList<String[]> lines = new ArrayList<String[]>();

    try {
        // Grab the contents of the file
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = reader.readLine()) != null) {
            // Skip lines that pure comments
            if (!line.startsWith("#")) {
                // Clip the line if it has a comment symbol in it to be
                // everything before the symbol
                if (line.contains("#")) {
                    int index = line.indexOf("#");
                    line = line.substring(0, index);
                }
                // Clean up any crap on the line
                String[] lineArray = line.trim().split(",");
                String[] trimmedLine = new String[lineArray.length];
                // And clean up any crap on each split piece
                for (int i = 0; i < lineArray.length; i++) {
                    trimmedLine[i] = lineArray[i].trim();
                }
                // Put the lines in the list
                lines.add(trimmedLine);
            }
        }

        reader.close();

    } catch (IOException e) {
        // Complain
        logger.error(
                getClass().getName() + " Exception! Could not read in data from file: " + file.getName() + ".",
                e);
    }

    if (!lines.isEmpty()) {

        // TODO- Some sort of implementation to read in the style
        // configurations for the plot, axes, and series. How to go about
        // this? A large part of the series implementation is not being
        // utilized without some sort of recognition here of the style
        // attributes!

        // Assume that the first line has information about the data
        String[] seriesNames = lines.remove(0);

        // Creates the series that contain the data loaded from the file.
        CSVSeries[] series = new CSVSeries[seriesNames.length];
        for (int i = 0; i < seriesNames.length; i++) {
            series[i] = new CSVSeries();
            series[i].setEnabled(false);
            series[i].setLabel(seriesNames[i]);
        }

        // Sets the first two series to be automatically plotted
        series[0].setEnabled(true);
        if (series.length > 1) {
            series[1].setEnabled(true);
        }

        // Load the data as doubles
        for (int i = 0; i < lines.size(); i++) {
            double[] values = (double[]) ConvertUtils.convert(lines.get(i), Double.TYPE);
            for (int j = 0; j < values.length; j++) {
                series[j].add(values[j]);
            }
        }

        // Just set the first series as the independent series for now
        setIndependentSeries(series[0]);

        // Add the rest of the series as dependent series
        List<ISeries> dependentSeries = new ArrayList<ISeries>(series.length - 1);
        dataSeries.put(IPlot.DEFAULT_CATEGORY, dependentSeries);
        for (int i = 1; i < series.length; i++) {
            dependentSeries.add(series[i]);
        }

    }

    // Loading has completed.
    loaded.set(true);

    // Notify the listeners that loading has completed.
    notifyPlotListeners("loaded", "true");

    return;
}