Search in sources :

Example 26 with Resource

use of gate.Resource in project gate-core by GateNLP.

the class Parameter method calculateValueFromString.

// calculateDefaultValue()
/**
 * Calculate and return the value for this parameter starting from a String
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object calculateValueFromString(String stringValue) throws ParameterException {
    // if we have no string we can't construct a value
    Object value = null;
    // get the Class for the parameter via Class.forName or CREOLE register
    Class<?> paramClass = getParameterClass();
    if (substituteClasses.containsKey(paramClass)) {
        paramClass = substituteClasses.get(paramClass);
    }
    // collectionSubstituteClasses and create a value of that type.
    if (Collection.class.isAssignableFrom(paramClass) && !paramClass.isInterface()) {
        // Create an collection object belonging to paramClass
        Collection<?> colection = null;
        try {
            colection = paramClass.asSubclass(Collection.class).getConstructor(new Class<?>[] {}).newInstance(new Object[] {});
        } catch (Exception ex) {
            throw new ParameterException("Could not construct an object of type " + typeName + " for param " + name + "\nProblem was: " + ex.toString());
        }
        // string tokens to the collection.
        if (itemClassName == null) {
            // Read the tokens from the default value and try to create items
            // belonging to the itemClassName
            StringTokenizer strTokenizer = new StringTokenizer(stringValue, ";");
            while (strTokenizer.hasMoreTokens()) {
                String itemStringValue = strTokenizer.nextToken();
                ((Collection<String>) colection).add(itemStringValue);
            }
        // End while
        } else {
            Class<?> itemClass = null;
            try {
                itemClass = Gate.getClassLoader().loadClass(itemClassName);
            } catch (ClassNotFoundException e) {
                throw new ParameterException("Could not construct a class object for " + itemClassName + " for param " + name + ", with type name=" + typeName);
            }
            // End try
            // Read the tokens from the default value and try to create items
            // belonging to the itemClassName
            StringTokenizer strTokenizer = new StringTokenizer(stringValue, ";");
            while (strTokenizer.hasMoreTokens()) {
                // Read a string item and construct an object belonging to
                // itemClassName
                String itemStringValue = strTokenizer.nextToken();
                Object itemValue = null;
                try {
                    itemValue = itemClass.getConstructor(new Class<?>[] { String.class }).newInstance(new Object[] { itemStringValue });
                } catch (Exception e) {
                    throw new ParameterException("Could not create an object of " + itemClassName + " for param name " + name + ", with type name =" + typeName);
                }
                // End try
                // Add the item value object to the collection
                ((Collection<Object>) colection).add(itemValue);
            }
        // End while
        }
        // End if(itemClassName == null)
        return colection;
    }
    if (FeatureMap.class.isAssignableFrom(paramClass)) {
        // a null string value means a null FeatureMap
        if (stringValue == null)
            return null;
        FeatureMap fm = null;
        // then just create a normal feature map using the factory
        if (paramClass.isInterface()) {
            fm = Factory.newFeatureMap();
        } else {
            try {
                fm = paramClass.asSubclass(FeatureMap.class).getConstructor(new Class<?>[] {}).newInstance(new Object[] {});
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                throw new ParameterException("Could not construct an object of type " + typeName + " for param " + name + "\nProblem was: " + e.toString());
            }
        }
        // Read the tokens from the default value and try to create items
        // belonging to the itemClassName
        StringTokenizer strTokenizer = new StringTokenizer(stringValue, ";");
        while (strTokenizer.hasMoreTokens()) {
            String keyAndValue = strTokenizer.nextToken();
            int indexOfEquals = keyAndValue.indexOf('=');
            if (indexOfEquals == -1) {
                throw new ParameterException("Error parsing string \"" + stringValue + "\" for parameter " + name + " of type " + typeName + ". Value string must be of the form " + "name1=value1;name2=value2;...");
            }
            String featName = keyAndValue.substring(0, indexOfEquals);
            String featValue = keyAndValue.substring(indexOfEquals + 1);
            fm.put(featName, featValue);
        }
        return fm;
    }
    // Java 5.0 enum types
    if (paramClass.isEnum()) {
        if (stringValue == null) {
            value = null;
        } else {
            try {
                value = Enum.valueOf(paramClass.<Enum>asSubclass(Enum.class), stringValue);
            } catch (IllegalArgumentException e) {
                throw new ParameterException("Invalid enum constant name " + stringValue + " for type " + typeName);
            }
        }
    } else if (typeName.equals("gate.creole.ResourceReference")) {
        if (stringValue != null && !stringValue.equals("")) {
            try {
                value = new ResourceReference(plugin, stringValue);
            } catch (URISyntaxException e) {
                throw new ParameterException("Malformed ResourceReference parameter value: " + stringValue, e);
            }
        }
    } else // empty string value, but just leave value as null
    if (typeName.startsWith("java.")) {
        if (typeName.equals("java.lang.Boolean"))
            value = Boolean.valueOf(stringValue);
        else if (typeName.equals("java.lang.Long")) {
            if (stringValue != null && !stringValue.equals("")) {
                value = Long.valueOf(stringValue);
            }
        } else if (typeName.equals("java.lang.Integer")) {
            if (stringValue != null && !stringValue.equals("")) {
                value = Integer.valueOf(stringValue);
            }
        } else if (typeName.equals("java.lang.String"))
            value = stringValue;
        else if (typeName.equals("java.lang.Double")) {
            if (stringValue != null && !stringValue.equals("")) {
                value = Double.valueOf(stringValue);
            }
        } else if (typeName.equals("java.lang.Float")) {
            if (stringValue != null && !stringValue.equals("")) {
                value = Float.valueOf(stringValue);
            }
        } else if (typeName.equals("java.net.URL")) {
            try {
                if (stringValue != null && !stringValue.equals("")) {
                    value = new URL(plugin.getBaseURL(), stringValue);
                }
            } catch (MalformedURLException mue) {
                // value = null;
                throw new ParameterException("Malformed URL parameter value: " + stringValue, mue);
            }
        } else {
            // e.g. for URLs
            try {
                if (!paramClass.isAssignableFrom(String.class)) {
                    value = paramClass.getConstructor(new Class<?>[] { String.class }).newInstance(new Object[] { stringValue });
                }
            } catch (Exception e) {
                throw new ParameterException("Unsupported parameter type " + typeName);
            }
        }
    } else {
        // null string value means null target value
        if (stringValue != null) {
            // otherwise, if it's a GATE resource type pick the first registered instance
            if (resData == null)
                resData = Gate.getCreoleRegister().get(typeName);
            if (resData == null) {
                // unknown type
                return null;
            }
            List<Resource> instantiations = resData.getInstantiations();
            if (!instantiations.isEmpty())
                value = instantiations.get(0);
        }
    }
    return value;
}
Also used : MalformedURLException(java.net.MalformedURLException) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) Resource(gate.Resource) MalformedURLException(java.net.MalformedURLException) URISyntaxException(java.net.URISyntaxException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GateRuntimeException(gate.util.GateRuntimeException) InvocationTargetException(java.lang.reflect.InvocationTargetException) FeatureMap(gate.FeatureMap) StringTokenizer(java.util.StringTokenizer) Collection(java.util.Collection)

Aggregations

Resource (gate.Resource)26 LanguageResource (gate.LanguageResource)9 CreoleResource (gate.creole.metadata.CreoleResource)9 FeatureMap (gate.FeatureMap)8 ProcessingResource (gate.ProcessingResource)8 VisualResource (gate.VisualResource)6 GateException (gate.util.GateException)5 GateRuntimeException (gate.util.GateRuntimeException)5 URL (java.net.URL)5 AbstractVisualResource (gate.creole.AbstractVisualResource)4 Corpus (gate.Corpus)3 AbstractResource (gate.creole.AbstractResource)3 ResourceData (gate.creole.ResourceData)3 ResourceInstantiationException (gate.creole.ResourceInstantiationException)3 PersistenceException (gate.persist.PersistenceException)3 ArrayList (java.util.ArrayList)3 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)3 Controller (gate.Controller)2 Document (gate.Document)2 ResourceInfo (gate.Gate.ResourceInfo)2