Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

In this page you can find the example usage for java.lang Enum valueOf.

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:org.projectforge.framework.xstream.XmlObjectReader.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object enumFromString(final Class<?> clazz, final Element element, final String attrName,
        final String attrValue) {
    final String val = attrValue != null ? attrValue : element.getText();
    Enum enumValue;/*from   www. jav  a  2  s  . c  o m*/
    if (StringUtils.isBlank(val) || "null".equals(val) == true) {
        enumValue = null;
    } else {
        try {
            enumValue = Enum.valueOf((Class) clazz, val);
        } catch (final IllegalArgumentException ex) {
            // Try toUpperCase:
            enumValue = Enum.valueOf((Class) clazz, val.toUpperCase());
        }
    }
    if (attrName != null) {
        putProcessedAttribute(element, attrName);
    } else {
        putProcessedElement(element);
    }
    return enumValue;
}

From source file:com.clover.sdk.GenericClient.java

/**
 * Generic method that replaces the "extract" methods which dealt with an Enum.
 *//*  ww w.  jav a 2 s . c  o  m*/
public <T extends Enum<T>> T extractEnum(String name, Class<T> clazz) {
    if (!getJSONObject().isNull(name)) {
        try {
            return Enum.valueOf(clazz, getJSONObject().optString(name));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:de.pixida.logtest.logreaders.GenericLogReader.java

private void readConfiguredHandlingOfNonHeadlineLinesSetting(final JSONObject configuration,
        final GenericLogReaderJsonKey jsonProperty) {
    if (configuration.has(jsonProperty.getKey())) {
        String value;//from  w  w w .j  a va 2s .c  o  m
        try {
            value = configuration.getString(jsonProperty.getKey());
        } catch (final JSONException jsonEx) {
            throw this.createJsonConfigException("string", jsonProperty.getKey());
        }
        try {
            this.handlingOfNonHeadlineLines = Enum.valueOf(HandlingOfNonHeadlineLines.class, value);
        } catch (final IllegalArgumentException iae) {
            LOG.error("Invalid value for setting '{}': '{}'. Allowed values: {}", jsonProperty.getKey(), value,
                    HandlingOfNonHeadlineLines.values());
            throw new LogReaderException("Invalid value for setting '" + jsonProperty.getKey() + "': '" + value
                    + "'. Allowed values: " + StringUtils.join(HandlingOfNonHeadlineLines.values(), ", "));
        }
    }
}

From source file:com.admc.jcreole.CreoleToHtmlHandler.java

public void handleRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    File css;//from   w  w w .  j  ava2s . c  om
    URL url;
    StringBuilder readmeSb = null;
    File fsDirFile = null;
    List<String> cssHrefs = new ArrayList<String>();
    File servletPathFile = new File(req.getServletPath());
    if (contextPath == null) {
        contextPath = application.getContextPath();
        iwUrls.put("home", contextPath);
        String appName = application.getServletContextName();
        iwLabels.put("home", ((appName == null) ? "Site" : appName) + " Home Page");
    }
    InputStream bpStream = null;
    Matcher matcher = servletFilePattern.matcher(servletPathFile.getName());
    if (!matcher.matches())
        throw new ServletException("Servlet " + getClass().getName()
                + " only supports servlet paths ending with '.html':  " + servletPathFile.getAbsolutePath());
    File crRootedDir = servletPathFile.getParentFile();
    // crRootedDir is the parent dir of the requested path.
    String pageBaseName = matcher.group(1);
    String absUrlDirPath = contextPath + crRootedDir.getAbsolutePath();
    String absUrlBasePath = absUrlDirPath + '/' + pageBaseName;
    File creoleFile = new File((isRootAbsolute ? "" : "/") + creoleRoot + crRootedDir.getAbsolutePath(),
            pageBaseName + ".creole");
    // creoleFile is a /-path either absolute or CR-rooted
    InputStream creoleStream = null;
    creoleStream = isRootAbsolute ? (creoleFile.isFile() ? new FileInputStream(creoleFile) : null)
            : application.getResourceAsStream(creoleFile.getAbsolutePath());
    if (indexer != null) {
        if (isRootAbsolute) {
            fsDirFile = creoleFile.getParentFile();
            if (!fsDirFile.isDirectory())
                fsDirFile = null;
        } else {
            fsDirFile = new File(application.getRealPath(creoleFile.getParentFile().getAbsolutePath()));
        }
        if (fsDirFile != null && !fsDirFile.isDirectory())
            throw new ServletException(
                    "fsDirFile unexpectedly not a directory: " + fsDirFile.getAbsolutePath());
    }
    if (pageBaseName.equals("index")) {
        File readmeFile = new File(creoleFile.getParentFile(), "readme.creole");
        InputStream readmeStream = isRootAbsolute
                ? (readmeFile.isFile() ? new FileInputStream(readmeFile) : null)
                : application.getResourceAsStream(readmeFile.getAbsolutePath());
        readmeSb = new StringBuilder("----\n");
        if (readmeStream == null) {
            readmeSb.append("{{{\n");
            readmeStream = application
                    .getResourceAsStream(new File(crRootedDir, "readme.txt").getAbsolutePath());
            if (readmeStream != null) {
                readmeSb.append(IOUtil.toStringBuilder(readmeStream));
                readmeSb.append("\n}}}\n");
            }
        } else {
            readmeSb.append(IOUtil.toStringBuilder(readmeStream));
        }
        if (readmeStream == null)
            readmeSb = null;
    }

    boolean inAncestorDir = false;
    File tmpDir;
    tmpDir = crRootedDir;
    while (tmpDir != null) {
        // Search from crRootedDir to creoleRoot for auxilliary files
        File curDir = new File((isRootAbsolute ? "" : "/") + creoleRoot + tmpDir.getAbsolutePath());
        File bpFile = new File(curDir, "boilerplate.html");
        if (bpStream == null)
            bpStream = isRootAbsolute ? (bpFile.isFile() ? new FileInputStream(bpFile) : null)
                    : application.getResourceAsStream(bpFile.getAbsolutePath());
        url = application.getResource(new File(tmpDir, "site.css").getAbsolutePath());
        if (url != null)
            cssHrefs.add(0, new File(contextPath + tmpDir, "site.css").getAbsolutePath());
        if (creoleStream == null && inAncestorDir && pageBaseName.equals("index") && autoIndexing) {
            File indexFile = new File(curDir, "index.creole");
            creoleStream = isRootAbsolute ? (indexFile.isFile() ? new FileInputStream(indexFile) : null)
                    : application.getResourceAsStream(indexFile.getAbsolutePath());
        }
        tmpDir = tmpDir.getParentFile();
        inAncestorDir = true;
    }
    if (creoleStream == null)
        throw new ServletException("Failed to access:  " + creoleFile.getAbsolutePath());
    if (bpStream == null)
        throw new ServletException("Failed to access 'boilerplate.html' " + "from creole dir or ancestor dir");
    tmpDir = crRootedDir;
    while (tmpDir != null) {
        url = application.getResource(new File(tmpDir, "jcreole.css").getAbsolutePath());
        if (url != null)
            cssHrefs.add(0, new File(contextPath + tmpDir, "jcreole.css").getAbsolutePath());
        tmpDir = tmpDir.getParentFile();
    }

    JCreole jCreole = new JCreole(IOUtil.toString(bpStream));
    Expander htmlExpander = jCreole.getHtmlExpander();
    Date now = new Date();
    htmlExpander.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    htmlExpander.put("isoDate", isoDateFormatter.format(now), false);
    htmlExpander.put("contextPath", contextPath, false);
    htmlExpander.put("pageBaseName", pageBaseName, false);
    htmlExpander.put("pageDirPath", absUrlDirPath, false);
    htmlExpander.put("pageTitle", absUrlBasePath, false);
    if (readmeSb == null) {
        htmlExpander.put("readmeContent", "");
    } else {
        JCreole readmeJCreole = new JCreole();
        readmeJCreole.setHtmlExpander(htmlExpander);
        readmeJCreole.setInterWikiMapper(this);
        readmeJCreole.setPrivileges(jcreolePrivs);
        htmlExpander.put("readmeContent", readmeJCreole.postProcess(readmeJCreole.parseCreole(readmeSb), "\n"),
                false);
    }
    if (fsDirFile != null) {
        FileComparator.SortBy sortBy = FileComparator.SortBy.NAME;
        boolean ascending = true;
        String sortStr = req.getParameter("sort");
        if (sortStr != null) {
            Matcher m = sortParamPattern.matcher(sortStr);
            if (!m.matches())
                throw new ServletException("Malformatted sort value: " + sortStr);
            ascending = m.group(1).equals("+");
            try {
                sortBy = Enum.valueOf(FileComparator.SortBy.class, m.group(2));
            } catch (Exception e) {
                throw new ServletException("Malformatted sort string: " + sortStr);
            }
        }
        htmlExpander.put("index",
                "\n" + indexer.generateTable(fsDirFile, absUrlDirPath, true, sortBy, ascending), false);
        // An alternative for using the Tomcat-like Indexer in a
        // htmlExpander would be to write a Creole table to a
        // creoleExpander.
    }

    /* Set up Creole macros like this:
    Expander creoleExpander =
        new Expander(Expander.PairedDelims.RECTANGULAR);
    creoleExpander.put("testMacro", "\n\n<<prettyPrint>>\n{{{\n"
        + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
    jCreole.setCreoleExpander(creoleExpander);
    */

    if (cssHrefs.size() > 0)
        jCreole.addCssHrefs(cssHrefs);
    jCreole.setInterWikiMapper(this);
    jCreole.setPrivileges(jcreolePrivs);
    String html = jCreole.postProcess(jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream)), "\n");
    resp.setBufferSize(1024);
    resp.setContentType("text/html");
    resp.getWriter().print(html);
}

From source file:org.datanucleus.store.scalaris.fieldmanager.FetchFieldManager.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object fetchObjectFieldInternal_RelationTypeNone(AbstractMemberMetaData mmd, String memberName,
        ClassLoaderResolver clr) throws JSONException {
    final Object returnValue;
    if (mmd.getTypeConverterName() != null) {
        // User-defined converter
        TypeConverter<Object, Object> conv = ec.getNucleusContext().getTypeManager()
                .getTypeConverterForName(mmd.getTypeConverterName());
        Class<?> datastoreType = TypeConverterHelper.getDatastoreTypeForTypeConverter(conv, mmd.getType());
        if (datastoreType == String.class) {
            returnValue = (Object) conv.toMemberType(result.getString(memberName));
        } else if (datastoreType == Boolean.class) {
            returnValue = conv.toMemberType(result.getBoolean(memberName));
        } else if (datastoreType == Double.class) {
            returnValue = conv.toMemberType(result.getDouble(memberName));
        } else if (datastoreType == Float.class) {
            returnValue = conv.toMemberType(result.getDouble(memberName));
        } else if (datastoreType == Integer.class) {
            returnValue = conv.toMemberType(result.getInt(memberName));
        } else if (datastoreType == Long.class) {
            returnValue = conv.toMemberType(result.getLong(memberName));
        } else {/*  ww  w . ja va 2s  .c  om*/
            returnValue = null;
        }
        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), returnValue, true);
        }
    } else if (Boolean.class.isAssignableFrom(mmd.getType())) {
        return result.getBoolean(memberName);
    } else if (Integer.class.isAssignableFrom(mmd.getType())) {
        return result.getInt(memberName);
    } else if (Long.class.isAssignableFrom(mmd.getType())) {
        return result.getLong(memberName);
    } else if (Double.class.isAssignableFrom(mmd.getType())) {
        return result.getDouble(memberName);
    } else if (Date.class.isAssignableFrom(mmd.getType())) {
        Long dateValue = result.getLong(memberName);
        return new Date(dateValue);
    } else if (Enum.class.isAssignableFrom(mmd.getType())) {
        if (mmd.getType().getEnumConstants() != null) {
            return mmd.getType().getEnumConstants()[result.getInt(memberName)];
        } else {
            return Enum.valueOf(mmd.getType(), (String) result.get(memberName));
        }
    } else if (BigDecimal.class.isAssignableFrom(mmd.getType())
            || BigInteger.class.isAssignableFrom(mmd.getType())) {
        return TypeConversionHelper.convertTo(result.get(memberName), mmd.getType());
    } else if (Collection.class.isAssignableFrom(mmd.getType())) {
        // Collection<Non-PC>
        Collection<Object> coll;
        try {
            Class<?> instanceType = SCOUtils.getContainerInstanceType(mmd.getType(),
                    mmd.getOrderMetaData() != null);
            coll = (Collection<Object>) instanceType.newInstance();
        } catch (Exception e) {
            throw new NucleusDataStoreException(e.getMessage(), e);
        }

        JSONArray array = result.getJSONArray(memberName);
        Class<?> elementCls = null;
        if (mmd.getCollection() != null && mmd.getCollection().getElementType() != null) {
            elementCls = clr.classForName(mmd.getCollection().getElementType());
        }
        for (int i = 0; i < array.length(); i++) {
            if (array.isNull(i)) {
                coll.add(null);
            } else {
                Object value = array.get(i);
                if (elementCls != null) {
                    coll.add(TypeConversionHelper.convertTo(value, elementCls));
                } else {
                    coll.add(value);
                }
            }
        }

        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), coll, true);
        }
        return coll;
    } else if (Map.class.isAssignableFrom(mmd.getType())) {
        // Map<Non-PC, Non-PC>
        Map map;
        try {
            Class<?> instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), false);
            map = (Map) instanceType.newInstance();
        } catch (Exception e) {
            throw new NucleusDataStoreException(e.getMessage(), e);
        }

        JSONObject mapValue = result.getJSONObject(memberName);
        Iterator<?> keyIter = mapValue.keys();
        Class<?> keyCls = null;
        if (mmd.getMap() != null && mmd.getMap().getKeyType() != null) {
            keyCls = clr.classForName(mmd.getMap().getKeyType());
        }
        Class<?> valCls = null;
        if (mmd.getMap() != null && mmd.getMap().getValueType() != null) {
            valCls = clr.classForName(mmd.getMap().getValueType());
        }

        while (keyIter.hasNext()) {
            Object jsonKey = keyIter.next();

            Object key = jsonKey;
            if (keyCls != null) {
                key = TypeConversionHelper.convertTo(jsonKey, keyCls);
            }

            Object jsonVal = mapValue.get((String) key);
            Object val = jsonVal;
            if (valCls != null) {
                val = TypeConversionHelper.convertTo(jsonVal, valCls);
            }
            map.put(key, val);
        }

        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), map, true);
        }
        return map;
    } else if (mmd.getType().isArray()) {
        // Non-PC[]
        JSONArray arrayJson = result.getJSONArray(memberName);
        Object array = Array.newInstance(mmd.getType().getComponentType(), arrayJson.length());
        for (int i = 0; i < arrayJson.length(); i++) {
            if (arrayJson.isNull(i)) {
                Array.set(array, i, null);
            } else {
                Object value = arrayJson.get(i);
                Array.set(array, i, TypeConversionHelper.convertTo(value, mmd.getType().getComponentType()));
            }
        }
        return array;
    } else {
        // Fallback to built-in type converters
        boolean useLong = false;
        ColumnMetaData[] colmds = mmd.getColumnMetaData();
        if (colmds != null && colmds.length == 1) {
            JdbcType jdbcType = colmds[0].getJdbcType();
            if (jdbcType != null) {
                String jdbc = jdbcType.name();
                if (jdbc != null && (jdbc.equalsIgnoreCase("INTEGER") || jdbc.equalsIgnoreCase("NUMERIC"))) {
                    useLong = true;
                }
            }
        }
        TypeConverter strConv = ec.getNucleusContext().getTypeManager().getTypeConverterForType(mmd.getType(),
                String.class);
        TypeConverter longConv = ec.getNucleusContext().getTypeManager().getTypeConverterForType(mmd.getType(),
                Long.class);

        if (useLong && longConv != null) {
            returnValue = longConv.toMemberType(result.getLong(memberName));
        } else if (!useLong && strConv != null) {
            returnValue = strConv.toMemberType((String) result.get(memberName));
        } else if (!useLong && longConv != null) {
            returnValue = longConv.toMemberType(result.getLong(memberName));
        } else {
            returnValue = TypeConversionHelper.convertTo(result.get(memberName), mmd.getType());
        }

        if (op != null) {
            return SCOUtils.wrapSCOField(op, mmd.getAbsoluteFieldNumber(), returnValue, true);
        }
    }
    return returnValue;
}

From source file:com.ottogroup.bi.spqr.repository.CachedComponentClassLoader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder// ww w .j a v a2 s .c om
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {

                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.byteCode.put(jarEntryName, loadBytes(jarInputStream));
                    } else {
                        // ...and add a mapping for resource to jar file as well
                        this.resources.put(jarEntryName, loadBytes(jarInputStream));
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation");

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.byteCode.keySet()) {

        try {
            Class<?> c = loadClass(cjf);
            Annotation spqrComponentAnnotation = getSPQRComponentAnnotation(c);
            if (spqrComponentAnnotation != null) {

                Method spqrAnnotationTypeMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_TYPE_METHOD, (Class[]) null);
                Method spqrAnnotationNameMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_NAME_METHOD, (Class[]) null);
                Method spqrAnnotationVersionMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_VERSION_METHOD, (Class[]) null);
                Method spqrAnnotationDescriptionMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_DESCRIPTION_METHOD, (Class[]) null);

                @SuppressWarnings("unchecked")
                Enum<MicroPipelineComponentType> o = (Enum<MicroPipelineComponentType>) spqrAnnotationTypeMethod
                        .invoke(spqrComponentAnnotation, (Object[]) null);
                final MicroPipelineComponentType componentType = Enum.valueOf(MicroPipelineComponentType.class,
                        o.name());
                final String componentName = (String) spqrAnnotationNameMethod.invoke(spqrComponentAnnotation,
                        (Object[]) null);
                final String componentVersion = (String) spqrAnnotationVersionMethod
                        .invoke(spqrComponentAnnotation, (Object[]) null);
                final String componentDescription = (String) spqrAnnotationDescriptionMethod
                        .invoke(spqrComponentAnnotation, (Object[]) null);

                this.managedComponents.put(getManagedComponentKey(componentName, componentVersion),
                        new ComponentDescriptor(c.getName(), componentType, componentName, componentVersion,
                                componentDescription));
                logger.info("pipeline component found [type=" + componentType + ", name=" + componentName
                        + ", version=" + componentVersion + "]");
                ;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("Failed to load class '" + cjf + "'. Error: " + e.getMessage());
        }
    }
}

From source file:info.pancancer.arch3.persistence.PostgreSQL.java

public List<Provision> getProvisions(ProvisionState status) {

    List<Provision> provisions = new ArrayList<>();
    Map<Object, Map<String, Object>> map;
    if (status != null) {
        map = this.runSelectStatement(
                "select * from provision where provision_id in (select max(provision_id) from provision group by ip_address) and status = ?",
                new KeyedHandler<>("provision_uuid"), status.toString());
    } else {//from w w  w .j  a va 2  s .c o  m
        map = this.runSelectStatement(
                "select * from provision where provision_id in (select max(provision_id) from provision group by ip_address)",
                new KeyedHandler<>("provision_uuid"));
    }

    for (Entry<Object, Map<String, Object>> entry : map.entrySet()) {

        Provision p = new Provision();
        p.setState(Enum.valueOf(ProvisionState.class, (String) entry.getValue().get("status")));
        p.setJobUUID((String) entry.getValue().get("job_uuid"));
        p.setProvisionUUID((String) entry.getValue().get("provision_uuid"));
        p.setIpAddress((String) entry.getValue().get("ip_address"));
        p.setCores((Integer) entry.getValue().get("cores"));
        p.setMemGb((Integer) entry.getValue().get("mem_gb"));
        p.setStorageGb((Integer) entry.getValue().get("storage_gb"));

        // timestamp
        Timestamp createTs = (Timestamp) entry.getValue().get("create_timestamp");
        Timestamp updateTs = (Timestamp) entry.getValue().get("update_timestamp");
        p.setCreateTimestamp(createTs);
        p.setUpdateTimestamp(updateTs);

        provisions.add(p);

    }

    return provisions;
}

From source file:connectivity.ClarolineService.java

/**
 * Gets the content of one specific resource.
 * // w w  w . j  ava2 s . co  m
 * @param syscode
 *            the course code
 * @param label
 *            the tool label
 * @param type
 *            the resource type
 * @param resourceIdentifier
 *            the resource unique identifier
 * @param handler
 *            the handler to execute after the request
 */
public void getSingleResource(final String syscode, final String label, final Class<? extends ModelBase> type,
        final String resourceIdentifier, final AsyncHttpResponseHandler handler) {
    RequestParams p = ClarolineClient.getRequestParams(Enum.valueOf(SupportedModules.class, label),
            SupportedMethods.getSingleResource, syscode, resourceIdentifier);
    mClient.serviceQuery(p, new JsonHttpResponseHandler() {

        @Override
        public void onFinish() {
            handler.onFinish();
        }

        @Override
        public void onSuccess(final JSONObject response) {
            ModelBase mb;
            try {
                mb = new Select().from(type)
                        .where("List = ? AND ResourceString = ?", response.get("resourceId")).executeSingle();
                if (mb == null) {
                    mb = App.getGSON().fromJson(response.toString(), type);
                } else {
                    mb.update(response);
                }
                mb.setLoadedDate(DateTime.now());
                mb.save();

            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            handler.onSuccess(response.toString());
        }
    });
}

From source file:org.apache.sqoop.model.ConfigUtils.java

/**
 * Move config values from config list into corresponding configuration object.
 *
 * @param configs Input config list/*from w  w w . j av  a 2 s.c  o m*/
 * @param configuration Output configuration object
 */
@SuppressWarnings("unchecked")
public static void fromConfigs(List<MConfig> configs, Object configuration) {
    Class klass = configuration.getClass();

    for (MConfig config : configs) {
        Field configField;
        try {
            configField = klass.getDeclaredField(config.getName());
        } catch (NoSuchFieldException e) {
            throw new SqoopException(ModelError.MODEL_006,
                    "Missing field " + config.getName() + " on config class " + klass.getCanonicalName(), e);
        }

        configField = getFieldFromName(klass, config.getName());
        // We need to access this field even if it would be declared as private
        configField.setAccessible(true);
        Class<?> configClass = configField.getType();
        Object newValue = ClassUtils.instantiate(configClass);

        if (newValue == null) {
            throw new SqoopException(ModelError.MODEL_006, "Can't instantiate new config " + configClass);
        }

        for (MInput input : config.getInputs()) {
            String[] splitNames = input.getName().split("\\.");
            if (splitNames.length != 2) {
                throw new SqoopException(ModelError.MODEL_009, "Invalid name: " + input.getName());
            }

            String inputName = splitNames[1];
            // TODO(jarcec): Names structures fix, handle error cases
            Field inputField;
            try {
                inputField = configClass.getDeclaredField(inputName);
            } catch (NoSuchFieldException e) {
                throw new SqoopException(ModelError.MODEL_006, "Missing field " + input.getName(), e);
            }

            // We need to access this field even if it would be declared as private
            inputField.setAccessible(true);

            try {
                if (input.isEmpty()) {
                    inputField.set(newValue, null);
                } else {
                    if (input.getType() == MInputType.ENUM) {
                        inputField.set(newValue, Enum.valueOf((Class<? extends Enum>) inputField.getType(),
                                (String) input.getValue()));
                    } else {
                        inputField.set(newValue, input.getValue());
                    }
                }
            } catch (IllegalAccessException e) {
                throw new SqoopException(ModelError.MODEL_005, "Issue with field " + inputField.getName(), e);
            }
        }

        try {
            configField.set(configuration, newValue);
        } catch (IllegalAccessException e) {
            throw new SqoopException(ModelError.MODEL_005, "Issue with field " + configField.getName(), e);
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.csv.CSVPersister.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected void setFieldValue(final AbstractEntity entity, final Field fd, final Object value) throws Exception {
    Object pvalue = value;/*from  w  w  w  .j a v a2 s  .c  o  m*/
    if (fd.getType().equals(String.class)) {
        pvalue = value;
    } else if (fd.getType().equals(Date.class)) {
        pvalue = DateUtils.fromString((String) value);
    } else if (EnumPrimitives.isPrimitiveType(fd.getType())) {
        EnumPrimitives pt = EnumPrimitives.type(fd.getType());
        switch (pt) {
        case ECharacter:
            pvalue = ((String) value).charAt(0);
            break;
        case EShort:
            pvalue = Short.parseShort((String) value);
            break;
        case EInteger:
            pvalue = Integer.parseInt((String) value);
            break;
        case ELong:
            pvalue = Long.parseLong((String) value);
            break;
        case EFloat:
            pvalue = Float.parseFloat((String) value);
            break;
        case EDouble:
            pvalue = Double.parseDouble((String) value);
            break;
        default:
            throw new Exception("Unsupported primitive type [" + pt.name() + "]");
        }
    } else if (fd.getType().isEnum()) {
        Class ecls = fd.getType();
        pvalue = Enum.valueOf(ecls, (String) value);
    } else if (pvalue.getClass().isAnnotationPresent(Entity.class)) {
        pvalue = value;
    } else
        throw new Exception("Field type [" + fd.getType().getCanonicalName() + "] is not supported.");
    PropertyUtils.setProperty(entity, fd.getName(), pvalue);
}