Example usage for java.lang.reflect Field isAnnotationPresent

List of usage examples for java.lang.reflect Field isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Field isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.dotweblabs.twirl.gae.GaeMarshaller.java

/**
 *
 * Create entity objects that can be persisted into the GAE Datastore,
 * including its Parent-Child relationships (if necessary).
 *
 * @param parent parent of the generated entity or Entities
 * @param instance to marshall/*from w w  w.j a v  a 2 s . c  o m*/
 * @return
 */
@Override
public IdentityHashMap marshall(Key parent, Object instance) {
    if (instance == null) {
        throw new RuntimeException("Object cannot be null");
    }
    Entity e = null;
    // Its possible that a Entity to be saved without id and just a parent key
    if (parent != null && hasNoIdField(instance)) {
        String kind = getKindOf(instance);
        e = new Entity(kind, parent);
    } else {
        Key key = createKeyFrom(parent, instance); // inspect kind and create key
        e = new Entity(key);
    }

    boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance);

    Map<String, Object> props = new LinkedHashMap<String, Object>();
    List<Entity> target = null;
    // Marshall java.util.Map
    if (instance instanceof Map) {
        Map map = (Map) instance;
        if (String.class.getName().equals(MapHelper.getKeyType(map))) {
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String entryKey = entry.getKey();
                Object entryVal = entry.getValue();
                if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY)
                        && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY)
                        && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) {
                    if (entryVal instanceof Map) {
                        setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed);
                    } else if (entryVal instanceof List) {
                        setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed);
                    } else {
                        setProperty(e, entryKey, entryVal, indexed);
                    }
                }
            }
        } else {
            throw new RuntimeException(
                    String.class.getName() + " is the only supported " + Map.class.getName() + " key");
        }
    } else {
        // Marshall all other object types
        Field[] fields = instance.getClass().getDeclaredFields();
        GeoPt geoPt = null;
        for (Field field : fields) {
            if (target == null) {
                target = new LinkedList<Entity>();
            }
            if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) {
                // do nothing for a final field
                // usually static UID fields
                continue;
            }
            String fieldName = field.getName();
            if (field.isAnnotationPresent(GaeObjectStore.key())) {
                // skip
                continue;
            } else if (field.isAnnotationPresent(GaeObjectStore.objectId())) {
                // skip
                continue;
            } else if (field.isAnnotationPresent(GaeObjectStore.kind())) {
                // skip
                continue;
            } else if (field.isAnnotationPresent(Volatile.class)) {
                // skip
                continue;
            }
            try {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                Object fieldValue = field.get(instance);
                if (fieldValue == null) {
                    e.setProperty(fieldName, null);
                } else if (fieldValue instanceof String) {
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof Number || fieldValue instanceof Long
                        || fieldValue instanceof Integer || fieldValue instanceof Short) {
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof Boolean) {
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof Date) {
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof User) { // GAE support this type
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof Blob) {
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof List) {
                    LOG.debug("Processing List valueType");
                    if (field.isAnnotationPresent(Embedded.class)) {
                        setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed);
                    } else {
                        boolean supported = true;
                        List list = (List) fieldValue;
                        for (Object item : list) {
                            if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) {
                                supported = false;
                            }
                        }
                        if (supported) {
                            setProperty(e, fieldName, fieldValue, indexed);
                        } else {
                            throw new RuntimeException("List should only include GAE supported types "
                                    + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded");
                        }
                    }
                } else if (fieldValue instanceof GeoPt) {
                    setProperty(e, fieldName, fieldValue, indexed);
                } else if (fieldValue instanceof Enum) {
                    String enumValue = fieldValue.toString();
                    LOG.info("Enum marshalled as \"" + enumValue + "\"");
                    setProperty(e, fieldName, enumValue, indexed);
                } else if (fieldValue instanceof Map) {
                    LOG.debug("Processing Map valueType");
                    if (field.isAnnotationPresent(Embedded.class)) {
                        setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed);
                    } else if (field.isAnnotationPresent(Flat.class)) {
                        Map<String, Object> flat = (Map) fieldValue;
                        Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator();
                        if (!it.hasNext()) {
                            LOG.debug("Iterator is empty");
                        }
                        while (it.hasNext()) {
                            Object entry = it.next();
                            try {
                                Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry;
                                Object entryKey = mapEntry.getKey();
                                Object entryVal = mapEntry.getValue();
                                if (entryVal == null) {
                                    setProperty(e, (String) entryKey, null, indexed);
                                } else if (entryVal instanceof Map) {
                                    setProperty(e, (String) entryKey,
                                            createEmbeddedEntityFromMap((Map) entryVal), indexed);
                                } else if (entryVal instanceof List) {
                                    throw new RuntimeException("List values are not yet supported");
                                } else if (entryVal instanceof String || entryVal instanceof Number
                                        || entryVal instanceof Boolean || entryVal instanceof Date
                                        || entryVal instanceof User || entryVal instanceof EmbeddedEntity) {
                                    setProperty(e, (String) entryKey, entryVal, indexed);
                                } else {
                                    throw new RuntimeException(
                                            "Unsupported GAE property type: " + entryVal.getClass().getName());
                                }
                                if (e == null) {
                                    throw new RuntimeException("Entity is null");
                                }
                            } catch (ClassCastException ex) {
                                // Something is wrong here
                                ex.printStackTrace();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else {
                        throw new TwirlException("Map type should be annotated with @Embedded or @Flat");
                    }
                } else {
                    // For primitives
                    if (fieldType.equals(int.class)) {
                        int i = (Integer) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(boolean.class)) {
                        boolean i = (Boolean) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(byte.class)) {
                        byte i = (Byte) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(short.class)) {
                        short i = (Short) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(long.class)) {
                        long i = (Long) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(float.class)) {
                        float i = (Float) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(double.class)) {
                        double i = (Double) fieldValue;
                        setProperty(e, fieldName, i, indexed);
                    } else if (fieldType.equals(byte.class)) {
                        byte b = (byte) fieldValue;
                        Blob blob = new Blob(new byte[b]);
                        setProperty(e, fieldName, blob, indexed);
                    } else if (fieldType.equals(byte[].class)) {
                        byte[] bytes = (byte[]) fieldValue;
                        Blob blob = new Blob(bytes);
                        setProperty(e, fieldName, blob, indexed);
                    } else if (fieldType.equals(Enum.class)) {
                        throw new RuntimeException("Enum primitive type not yet implemented");
                    } else { // POJO
                        if (field.isAnnotationPresent(Embedded.class)) {
                            Map<String, Object> map = createMapFrom(fieldValue);
                            EmbeddedEntity ee = createEmbeddedEntityFromMap(map);
                            setProperty(e, fieldName, ee, indexed);
                        } else if (field.isAnnotationPresent(GaeObjectStore.parent())) {
                            // @Parent first before @Child, don't switch. @Child needs parent Key.
                            if (field.getType().equals(Key.class)) {
                                // skip it
                                continue;
                            } else {
                                if (parent != null) {
                                    // Case where a Parent entity is marshalled then during the
                                    // iteration process, a @Child entity is found
                                    Entity _target = new Entity(createKeyFrom(parent, instance));
                                    _target.setPropertiesFrom(e);
                                    e = _target;
                                } else {
                                    // Case where a Child entity is first marshalled
                                    // at this point this child is not yet in the stack
                                    // and the Parent entity is not yet also in the stack
                                    // so we will create a Key from the "not yet marshalled" parent instance
                                    // or is it not? Let's check.
                                    Object parentField = field.get(instance);
                                    Entity parentEntity = stack.get(parentField);
                                    if (parentEntity != null) {
                                        Entity _target = new Entity(
                                                createKeyFrom(parentEntity.getKey(), instance));
                                        _target.setPropertiesFrom(e);
                                        e = _target;
                                    } else {
                                        Key generatedParentKey = createKeyFrom(null, parentField);
                                        Entity _target = new Entity(
                                                createKeyFrom(generatedParentKey, instance));
                                        _target.setPropertiesFrom(e);
                                        e = _target;
                                        marshall(null, parentField);
                                    }
                                }
                            }
                        } else if (field.isAnnotationPresent(GaeObjectStore.child())) {
                            Object childField = field.get(instance);
                            marshall(e.getKey(), childField);
                            Entity childEntity = stack.get(childField);
                            Key childEntityKey = childEntity.getKey();
                            setProperty(e, fieldName, childEntityKey, indexed);
                        } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) {
                            // already processed above, skip it
                        } else {
                            throw new RuntimeException(
                                    "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field "
                                            + fieldName);
                        }
                    }
                }
                field.setAccessible(isAccessible);
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
    }
    stack.put(instance, e);
    return stack;
}

From source file:com.logsniffer.util.value.ConfigInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
        @Override/*  w ww .  j  av  a 2s  .co  m*/
        public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
            LOGGER.debug("Injecting value={} for bean={}", field.getName(), beanName);
            field.setAccessible(true);
            final String key = field.getAnnotation(Configured.class).value();
            final String defaultValue = field.getAnnotation(Configured.class).defaultValue();
            final Class<?> targetValueType = (Class<?>) ((ParameterizedType) field.getGenericType())
                    .getActualTypeArguments()[0];
            field.set(bean, new ConfigValue<Object>() {
                private String oldTextValue;
                private Object oldValue;

                @Override
                public Object get() {
                    String textValue = getSource().getValue(key);
                    if (textValue == null) {
                        textValue = defaultValue;
                    }
                    if (oldTextValue != null && oldTextValue.equals(textValue)) {
                        return oldValue;
                    } else {
                        oldValue = conversionService.convert(textValue, targetValueType);
                        oldTextValue = textValue;
                        return oldValue;
                    }
                }
            });

        }
    }, new FieldFilter() {
        @Override
        public boolean matches(final Field field) {
            return field.getType().equals(ConfigValue.class) && field.isAnnotationPresent(Configured.class);
        }
    });

    return bean;
}

From source file:com.madrobot.di.wizard.json.JSONSerializer.java

/**
 * Serialize a specific java object recursively.
 * //from www . jav a 2s.c  om
 * @param jsonObject
 *            Object whose fields need to be set
 * 
 * @param stack
 *            Stack of {@link ClassInfo} - entity type under consideration
 * 
 * @throws JSONException
 *             If an exception occurs during parsing
 */
private void serializer(JSONObject jsonObject, final Stack<Object> stack) throws JSONException {

    Object userObject = stack.peek();
    Class<?> userClass = userObject.getClass();
    Field[] fields = userClass.getDeclaredFields();

    for (Field field : fields) {

        String fieldName = field.getName();
        Class<?> classType = field.getType();
        String jsonKeyName = getKeyName(field);

        try {

            String getMethodName = getGetMethodName(fieldName, classType);
            Method getMethod = userClass.getDeclaredMethod(getMethodName);
            Object returnValue = getMethod.invoke(userObject, new Object[] {});

            if (Converter.isPseudoPrimitive(classType)) {
                Converter.storeValue(jsonObject, jsonKeyName, returnValue, field);
            } else if (Converter.isCollectionType(classType)) {

                JSONArray jsonArray = new JSONArray();
                boolean canAdd = true;

                if (returnValue instanceof Collection) {
                    Collection<?> userCollectionObj = (Collection<?>) returnValue;

                    if (userCollectionObj.size() != 0) {

                        Iterator<?> iterator = userCollectionObj.iterator();

                        while (iterator.hasNext()) {
                            Object itemObject = iterator.next();
                            JSONObject object = new JSONObject();
                            stack.push(itemObject);
                            serializer(object, stack);
                            jsonArray.put(object);
                        }
                    } else if (field.isAnnotationPresent(ItemType.class)) {
                        ItemType itemType = field.getAnnotation(ItemType.class);
                        canAdd = itemType.canEmpty();
                    }

                    if (canAdd)
                        jsonObject.put(jsonKeyName, jsonArray);
                } else if (returnValue instanceof Map) {
                    Map<?, ?> userMapObj = (Map<?, ?>) returnValue;
                    JSONObject object = new JSONObject(userMapObj);
                    jsonArray.put(object);
                    jsonObject.put(jsonKeyName, jsonArray);
                }
            } else {
                stack.push(returnValue);
                JSONObject object = new JSONObject();
                serializer(object, stack);
                jsonObject.put(jsonKeyName, object);
            }

        } catch (NoSuchMethodException e) {
            Log.e(TAG, e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.getMessage());
        } catch (InvocationTargetException e) {
            Log.e(TAG, e.getMessage());
        }
    }
}

From source file:org.jdbcluster.domain.DomainCheckerImpl.java

/**
 * IMPLEMENTATION calculates set of valid domain values (master or slave)
 * /*from   w  w w . ja v a  2  s  . com*/
 * @param cluster Cluster object to use
 * @param propPath path to the master or slave property
 * @return ValidDomainEntries<String> with the valid domain values
 */
public ValidDomainEntries<String> getValidDomainEntries(ICluster cluster, String propPath) {

    Assert.notNull(cluster, "Cluster may not be null");
    Assert.hasLength(propPath, "propPath may not be null");

    if (logger.isDebugEnabled())
        logger.debug("getValidDomainEntries for Cluster [" + cluster.getClass().getName() + "]"
                + " and property path [" + propPath + "]");

    String masterDomainId;
    String masterValue;
    String slaveDomainId;

    Field fMaster;
    Field fSlave;

    fSlave = JDBClusterUtil.getField(propPath, cluster);

    DomainDependancy dd = fSlave.getAnnotation(DomainDependancy.class);
    if (dd == null) {
        Domain d = fSlave.getAnnotation(Domain.class);
        if (d == null)
            throw new ConfigurationException(
                    "no annotation @DomainDependancy or @Domain found on: " + propPath);

        if (logger.isDebugEnabled())
            logger.debug("getValidDomainEntries doing rightsIntersection for domain id[" + d.domainId() + "]"
                    + " and Field [" + fSlave.getName() + "]");

        return rightsIntersection(cluster.getUser(), getPossibleDomainEntries(d.domainId()), d.domainId(),
                fSlave);
    }
    slaveDomainId = dd.domainId();

    String propMasterPath = dd.dependsFromProperty();
    fMaster = JDBClusterUtil.getField(propMasterPath, cluster);
    masterDomainId = getDomainIdFromField(fMaster, false);

    masterValue = (String) JDBClusterUtil.invokeGetPropertyMethod(dd.dependsFromProperty(), cluster);
    if (!fSlave.isAnnotationPresent(AddDomainDependancy.class)) {

        if (logger.isDebugEnabled())
            logger.debug("getValidDomainEntries doing rightsIntersection for master domain id[" + masterDomainId
                    + "]" + " and masterValue [" + masterValue + "]" + " and slaveDomainId [" + slaveDomainId
                    + "] and Field [" + fSlave.getName() + "]");

        return rightsIntersection(cluster.getUser(),
                getValidDomainEntries(masterDomainId, masterValue, slaveDomainId), slaveDomainId, fSlave);
    }

    AddDomainDependancy aDD = fSlave.getAnnotation(AddDomainDependancy.class);
    String[] addDomIdArr = new String[aDD.addDepFromProp().length];
    String[] addDomValArr = new String[aDD.addDepFromProp().length];
    for (int i = 0; i < aDD.addDepFromProp().length; i++) {

        Field faddMaster = JDBClusterUtil.getField(aDD.addDepFromProp()[i], cluster);
        String addMasterDomainId = getDomainIdFromField(faddMaster, false);

        addDomIdArr[i] = addMasterDomainId;
        addDomValArr[i] = (String) JDBClusterUtil.invokeGetPropertyMethod(aDD.addDepFromProp()[i], cluster);
    }

    if (logger.isDebugEnabled())
        logger.debug("getValidDomainEntries (additional master) doing rightsIntersection for master domain id["
                + masterDomainId + "]" + " and masterValue [" + masterValue + "]" + " and slaveDomainId ["
                + slaveDomainId + "] and Field [" + fSlave.getName() + "]");

    return rightsIntersection(cluster.getUser(),
            getValidDomainEntries(masterDomainId, masterValue, slaveDomainId, addDomIdArr, addDomValArr),
            slaveDomainId, fSlave);
}

From source file:com.cloudera.sqoop.SqoopOptions.java

/**
 * Return a Properties instance that encapsulates all the "sticky"
 * state of this SqoopOptions that should be written to a metastore
 * to restore the job later./*from  ww  w . ja  v a2  s . c  om*/
 */
public Properties writeProperties() {
    Properties props = new Properties();

    try {
        Field[] fields = getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    putProperty(props, propName, Integer.toString(f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    putProperty(props, propName, Boolean.toString(f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    putProperty(props, propName, Long.toString(f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    putProperty(props, propName, (String) f.get(this));
                } else if (typ.equals(Integer.class)) {
                    putProperty(props, propName, f.get(this) == null ? "null" : f.get(this).toString());
                } else if (typ.isEnum()) {
                    putProperty(props, propName, f.get(this).toString());
                } else {
                    throw new RuntimeException("Could not set property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    if (this.getConf().getBoolean(METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) {
        // If the user specifies, we may store the password in the metastore.
        putProperty(props, "db.password", this.password);
        putProperty(props, "db.require.password", "false");
    } else if (this.password != null) {
        // Otherwise, if the user has set a password, we just record
        // a flag stating that the password will need to be reentered.
        putProperty(props, "db.require.password", "true");
    } else {
        // No password saved or required.
        putProperty(props, "db.require.password", "false");
    }

    putProperty(props, "db.column.list", arrayToList(this.columns));
    setDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    setDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);
    setArgArrayProperties(props, "tool.arguments", this.extraArgs);

    return props;
}

From source file:org.apache.usergrid.persistence.Schema.java

private <T extends Annotation> T getAnnotation(Class<? extends Entity> entityClass,
        PropertyDescriptor descriptor, Class<T> annotationClass) {
    try {/* ww w.j  av a 2  s  . c  o m*/
        if ((descriptor.getReadMethod() != null)
                && descriptor.getReadMethod().isAnnotationPresent(annotationClass)) {
            return descriptor.getReadMethod().getAnnotation(annotationClass);
        }
        if ((descriptor.getWriteMethod() != null)
                && descriptor.getWriteMethod().isAnnotationPresent(annotationClass)) {
            return descriptor.getWriteMethod().getAnnotation(annotationClass);
        }
        Field field = FieldUtils.getField(entityClass, descriptor.getName(), true);
        if (field != null) {
            if (field.isAnnotationPresent(annotationClass)) {
                return field.getAnnotation(annotationClass);
            }
        }
    } catch (Exception e) {
        logger.error("Could not retrieve the annotations", e);
    }
    return null;
}

From source file:com.cloudera.sqoop.SqoopOptions.java

@SuppressWarnings("unchecked")
/**/*  ww  w.  ja  v a 2s  . c o  m*/
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

    try {
        Field[] fields = getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    f.setInt(this, getIntProperty(props, propName, f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    f.setLong(this, getLongProperty(props, propName, f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    f.set(this, props.getProperty(propName, (String) f.get(this)));
                } else if (typ.equals(Integer.class)) {
                    String value = props.getProperty(propName,
                            f.get(this) == null ? "null" : f.get(this).toString());
                    f.set(this, value.equals("null") ? null : new Integer(value));
                } else if (typ.isEnum()) {
                    f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString())));
                } else {
                    throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    // Now load properties that were stored with special types, or require
    // additional logic to set.

    if (getBooleanProperty(props, "db.require.password", false)) {
        // The user's password was stripped out from the metastore.
        // Require that the user enter it now.
        setPasswordFromConsole();
    } else {
        this.password = props.getProperty("db.password", this.password);
    }

    if (this.jarDirIsAuto) {
        // We memoized a user-specific nonce dir for compilation to the data
        // store.  Disregard that setting and create a new nonce dir.
        String localUsername = System.getProperty("user.name", "unknown");
        this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile");
    }

    String colListStr = props.getProperty("db.column.list", null);
    if (null != colListStr) {
        this.columns = listToArray(colListStr);
    }

    this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);

    this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs);

    // Delimiters were previously memoized; don't let the tool override
    // them with defaults.
    this.areDelimsManuallySet = true;
}

From source file:it.isislab.dmason.tools.batch.BatchWizard.java

private ArrayList<Param> loadParams() {

    suggestion = new HashMap<String, ValueAnnotation>();

    URL url;// w w w.jav a  2s  . c  om
    try {
        url = new URL("file:" + simulationFile.getAbsolutePath());

        JarClassLoader cl = new JarClassLoader(url);

        cl.addToClassPath();

        String main = cl.getMainClassName();

        Class c = cl.loadClass(main);

        Object instance = Class.forName(main).newInstance();

        Field[] fields = c.getDeclaredFields();

        ArrayList<Param> paramList = new ArrayList<Param>();

        for (Field field : fields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(BatchAnnotation.class)) {
                ParamFixed pf = new ParamFixed(field.getName(), field.getType().toString(), 1,
                        field.get(instance).toString());
                paramList.add(pf);

                BatchAnnotation ann = field.getAnnotation(BatchAnnotation.class);

                suggestion.put(field.getName(), new ValueAnnotation(ann.domain(), ann.suggestedValue()));
            }
        }

        return paramList;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:com.impetus.client.cassandra.thrift.CQLTranslator.java

/**
 * On translation.// w  w w  . j  ava  2  s  .c  o  m
 * 
 * @param record
 *            the record
 * @param m
 *            the m
 * @param type
 *            the type
 * @param metaModel
 *            the meta model
 * @param entityClazz
 *            the entity clazz
 * @param entityType
 *            the entity type
 * @param builders
 *            the builders
 * @param columnBuilders
 *            the column builders
 * @param externalProperties
 *            the external properties
 * @param kunderaMetadata
 *            the kundera metadata
 */
private void onTranslation(final Object record, final EntityMetadata m, TranslationType type,
        MetamodelImpl metaModel, Class entityClazz, EntityType entityType, Map<String, StringBuilder> builders,
        Map<String, StringBuilder> columnBuilders, Map<String, Object> externalProperties,
        final KunderaMetadata kunderaMetadata) {
    Set<Attribute> attributes = entityType.getAttributes();
    Iterator<Attribute> iterator = attributes.iterator();
    while (iterator.hasNext()) {
        Attribute attribute = iterator.next();

        // Populating table name.
        String tableName = ((AbstractAttribute) attribute).getTableName() != null
                ? ((AbstractAttribute) attribute).getTableName()
                : m.getTableName();

        StringBuilder columnBuilder = columnBuilders.get(tableName);
        if (columnBuilder == null) {
            columnBuilder = new StringBuilder();
            columnBuilders.put(tableName, columnBuilder);
        }

        StringBuilder builder = builders.get(tableName);
        if (builder == null) {
            builder = new StringBuilder();
            builders.put(tableName, builder);
        }
        Field field = (Field) attribute.getJavaMember();
        if (!attribute.equals(m.getIdAttribute()) && !((AbstractAttribute) attribute).getJPAColumnName()
                .equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName())) {
            if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                // create embedded entity persisting format
                if (field.isAnnotationPresent(ElementCollection.class)) {
                    // handle embeddable collection
                    // check list, map, set
                    // build embedded value
                    StringBuilder elementCollectionValue = buildElementCollectionValue(field, record, metaModel,
                            attribute);
                    columnBuilder.append(Constants.ESCAPE_QUOTE);
                    columnBuilder.append(((AbstractAttribute) attribute).getJPAColumnName());
                    columnBuilder.append(Constants.ESCAPE_QUOTE);
                    columnBuilder.append(Constants.COMMA);
                    builder.append(elementCollectionValue);
                    builder.append(Constants.COMMA);
                } else {
                    EmbeddableType embeddableKey = metaModel.embeddable(field.getType());
                    Object embeddableKeyObj = PropertyAccessorHelper.getObject(record, field);
                    if (embeddableKeyObj != null) {

                        StringBuilder embeddedValueBuilder = new StringBuilder(Constants.OPEN_CURLY_BRACKET);

                        for (Field embeddableColumn : field.getType().getDeclaredFields()) {
                            if (!ReflectUtils.isTransientOrStatic(embeddableColumn)) {
                                AbstractAttribute subAttribute = (AbstractAttribute) embeddableKey
                                        .getAttribute(embeddableColumn.getName());
                                if (metaModel.isEmbeddable(subAttribute.getBindableJavaType())) {
                                    // construct map; recursive
                                    // send attribute
                                    if (embeddableColumn.isAnnotationPresent(ElementCollection.class)) {
                                        // build element collection value
                                        StringBuilder elementCollectionValue = buildElementCollectionValue(
                                                embeddableColumn, embeddableKeyObj, metaModel,
                                                (Attribute) subAttribute);

                                        appendColumnName(embeddedValueBuilder,
                                                ((AbstractAttribute) (embeddableKey
                                                        .getAttribute(embeddableColumn.getName())))
                                                                .getJPAColumnName());
                                        embeddedValueBuilder.append(Constants.COLON);
                                        embeddedValueBuilder.append(elementCollectionValue);
                                    } else {
                                        buildEmbeddedValue(embeddableKeyObj, metaModel, embeddedValueBuilder,
                                                (SingularAttribute) subAttribute);
                                    }
                                } else {
                                    // append key value
                                    appendColumnName(embeddedValueBuilder,
                                            ((AbstractAttribute) (embeddableKey
                                                    .getAttribute(embeddableColumn.getName())))
                                                            .getJPAColumnName());
                                    embeddedValueBuilder.append(Constants.COLON);
                                    appendColumnValue(embeddedValueBuilder, embeddableKeyObj, embeddableColumn);
                                }
                                embeddedValueBuilder.append(Constants.COMMA);
                            }
                        }
                        // strip last char and append '}'
                        embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1);
                        embeddedValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);
                        // add to columnbuilder and builder
                        columnBuilder.append(Constants.ESCAPE_QUOTE);
                        columnBuilder.append(((AbstractAttribute) attribute).getJPAColumnName());
                        columnBuilder.append(Constants.ESCAPE_QUOTE);
                        columnBuilder.append(Constants.COMMA);
                        builder.append(embeddedValueBuilder);
                        builder.append(Constants.COMMA);
                        // end if
                    }
                }
            } else if (!ReflectUtils.isTransientOrStatic(field) && !attribute.isAssociation()) {
                onTranslation(type, builder, columnBuilder, ((AbstractAttribute) attribute).getJPAColumnName(),
                        record, field);
            }
        }
    }

    for (String tableName : columnBuilders.keySet()) {
        translateCompositeId(record, m, type, metaModel, builders, columnBuilders, externalProperties,
                kunderaMetadata, tableName, m.getIdAttribute());
    }

    // on inherited columns.
    onDiscriminatorColumn(builders.get(m.getTableName()), columnBuilders.get(m.getTableName()), entityType);
}