Example usage for java.lang.reflect Field getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the field represented by this Field object.

Usage

From source file:com.screenslicer.webapp.ScreenSlicerClient.java

@Path("create")
@POST//  w w  w.ja  v a  2 s.c  om
@Consumes("application/json")
@Produces("application/json")
public static final Response create(String reqString) {
    if (reqString != null) {
        final String reqDecoded = Crypto.decode(reqString, CommonUtil.ip());
        if (reqDecoded != null) {
            final Map<String, Object> args = CommonUtil.gson.fromJson(reqDecoded, CommonUtil.objectType);
            final Request request = CommonUtil.gson.fromJson(reqDecoded, Request.class);
            Field[] fields = request.getClass().getFields();
            for (Field field : fields) {
                args.remove(field.getName());
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String myInstance = null;
                    AtomicBoolean myDone = null;
                    try {
                        CommonFile.writeStringToFile(
                                new File("./data/" + request.runGuid + "-meta" + request.appId),
                                request.jobId + "\n" + request.jobGuid + "\n"
                                        + Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(),
                                false);
                        CommonFile.writeStringToFile(new File("./data/" + request.runGuid + "-context"),
                                Crypto.encode(reqDecoded), false);
                        Map<String, AtomicBoolean> myDoneMap = new HashMap<String, AtomicBoolean>();
                        synchronized (doneMapLock) {
                            for (int i = 0; i < request.instances.length; i++) {
                                if (!doneMap.containsKey(request.instances[i])) {
                                    doneMap.put(request.instances[i], new AtomicBoolean(true));
                                }
                            }
                            myDoneMap.putAll(doneMap);
                        }
                        long myThread = latestThread.incrementAndGet();
                        while (true) {
                            if (isCancelled(request.runGuid)) {
                                curThread.incrementAndGet();
                                throw new CancellationException();
                            }
                            if (myThread == curThread.get() + 1) {
                                for (Map.Entry<String, AtomicBoolean> done : myDoneMap.entrySet()) {
                                    if (done.getValue().compareAndSet(true, false)) {
                                        if (ScreenSlicer.isBusy(done.getKey())) {
                                            done.getValue().set(true);
                                        } else {
                                            myInstance = done.getKey();
                                            myDone = done.getValue();
                                            break;
                                        }
                                    }
                                }
                                if (myInstance != null) {
                                    break;
                                }
                            }
                            try {
                                Thread.sleep(WAIT);
                            } catch (Exception e) {
                                Log.exception(e);
                            }
                        }
                        curThread.incrementAndGet();
                        int outputNumber = 0;
                        request.instances = new String[] { myInstance };
                        Map<String, List<List<String>>> tables = customApp.tableData(request, args);
                        Map<String, Map<String, Object>> jsons = customApp.jsonData(request, args);
                        Map<String, byte[]> binaries = customApp.binaryData(request, args);
                        request.emailExport.attachments = new LinkedHashMap<String, byte[]>();
                        if (tables != null) {
                            for (Map.Entry<String, List<List<String>>> table : tables.entrySet()) {
                                if (table.getKey().toLowerCase().endsWith(".xls")) {
                                    byte[] result = Spreadsheet.xls(table.getValue());
                                    CommonFile.writeByteArrayToFile(
                                            new File("./data/" + request.runGuid + "-result" + outputNumber),
                                            result, false);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(), result);
                                    }
                                } else if (table.getKey().toLowerCase().endsWith(".csv")) {
                                    String result = Spreadsheet.csv(table.getValue());
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result" + outputNumber),
                                            result, false);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(),
                                                result.getBytes("utf-8"));
                                    }
                                } else if (table.getKey().toLowerCase().endsWith(".xcsv")) {
                                    String result = Spreadsheet.csv(table.getValue());
                                    CommonUtil.internalHttpCall(CommonUtil.ip(),
                                            "https://" + CommonUtil.ip() + ":8000/_/"
                                                    + Crypto.fastHash(table.getKey() + ":" + request.runGuid),
                                            "PUT", CommonUtil.asMap("Content-Type", "text/csv; charset=utf-8"),
                                            result.getBytes("utf-8"), null);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(),
                                                result.getBytes("utf-8"));
                                    }
                                } else {
                                    String result = CommonUtil.gson.toJson(table.getValue(),
                                            table.getValue().getClass());
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result" + outputNumber),
                                            result, false);
                                    CommonFile.writeStringToFile(
                                            new File("./data/" + request.runGuid + "-result-names"),
                                            escapeName(table.getKey()) + "\n", true);
                                    ++outputNumber;
                                    if (request.emailResults) {
                                        request.emailExport.attachments.put(table.getKey(),
                                                result.getBytes("utf-8"));
                                    }
                                }
                            }
                        }
                        if (jsons != null) {
                            for (Map.Entry<String, Map<String, Object>> json : jsons.entrySet()) {
                                String result = CommonUtil.gson.toJson(json.getValue(), CommonUtil.objectType);
                                CommonFile.writeStringToFile(
                                        new File("./data/" + request.runGuid + "-result" + outputNumber),
                                        result, false);
                                CommonFile.writeStringToFile(
                                        new File("./data/" + request.runGuid + "-result-names"),
                                        escapeName(json.getKey()) + "\n", true);
                                ++outputNumber;
                                if (request.emailResults) {
                                    request.emailExport.attachments.put(json.getKey(),
                                            result.getBytes("utf-8"));
                                }
                            }
                        }
                        if (binaries != null) {
                            for (Map.Entry<String, byte[]> binary : binaries.entrySet()) {
                                CommonFile.writeByteArrayToFile(
                                        new File("./data/" + request.runGuid + "-result" + outputNumber),
                                        binary.getValue(), false);
                                CommonFile.writeStringToFile(
                                        new File("./data/" + request.runGuid + "-result-names"),
                                        escapeName(binary.getKey()) + "\n", true);
                                ++outputNumber;
                                if (request.emailResults) {
                                    request.emailExport.attachments.put(binary.getKey(), binary.getValue());
                                }
                            }
                        }
                        if (request.emailResults) {
                            ScreenSlicer.export(request, request.emailExport);
                        }
                    } catch (Throwable t) {
                        Log.exception(t);
                    } finally {
                        try {
                            CommonFile.writeStringToFile(
                                    new File("./data/" + request.runGuid + "-meta" + request.appId),
                                    "\n" + Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(),
                                    true);
                        } catch (Throwable t) {
                            Log.exception(t);
                        }
                        myDone.set(true);
                        synchronized (cancelledLock) {
                            cancelledJobs.remove(request.runGuid);
                        }
                    }
                }
            }).start();
            return Response.ok(Crypto.encode(request.runGuid, CommonUtil.ip())).build();
        }
    }
    return null;
}

From source file:ml.shifu.shifu.container.meta.MetaFactory.java

/**
 * Validate the ModelConfig object, to make sure each item follow the constrain
 * /* w ww.j a  v a  2s. co  m*/
 * @param modelConfig
 *            - object to validate
 * @return ValidateResult
 *         If all items are OK, the ValidateResult.status will be true;
 *         Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons
 * @throws Exception
 *             any exception in validaiton
 */
public static ValidateResult validate(ModelConfig modelConfig) throws Exception {
    ValidateResult result = new ValidateResult(true);

    GridSearch gs = new GridSearch(modelConfig.getTrain().getParams(),
            modelConfig.getTrain().getGridConfigFileContent());

    Class<?> cls = modelConfig.getClass();
    Field[] fields = cls.getDeclaredFields();

    for (Field field : fields) {
        // skip log instance
        if (field.getName().equalsIgnoreCase("log") || field.getName().equalsIgnoreCase("logger")) {
            continue;
        }
        if (!field.isSynthetic()) {
            Method method = cls.getMethod("get" + getMethodName(field.getName()));
            Object value = method.invoke(modelConfig);

            if (value instanceof List) {
                List<?> objList = (List<?>) value;
                for (Object obj : objList) {
                    encapsulateResult(result, iterateCheck(gs.hasHyperParam(), field.getName(), obj));
                }
            } else {
                encapsulateResult(result, iterateCheck(gs.hasHyperParam(), field.getName(), value));
            }
        }
    }

    return result;
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

protected static Object getValueWithField(Field field, Object bean) {

    try {/*from w  w w .  jav a 2s .co  m*/
        field.setAccessible(true);
        return field.get(bean);
    } catch (Exception ex) {
        throw new RuntimeException("Unable to get property " + field.getName() + " on instance of "
                + bean.getClass().getName() + " using field " + field.getName(), ex);
    }
}

From source file:com.mh.commons.utils.Reflections.java

/**
 * ?? trim() /*from   w ww.j a v a  2  s  .  c  o  m*/
 * ?? trim();  ??
 * @param obj
 * @param escapeList ??trim()
 * @return
 */
public static Object trim(Object obj, List<String> escapeList) {
    if (obj == null)
        return null;
    try {
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.getModifiers() < 15 && field.getType().toString().equals("class java.lang.String")) {
                    Object val = FieldUtils.readField(field, obj, true);
                    if (val != null) {
                        if (escapeList != null && escapeList.indexOf(field.getName()) != -1)
                            continue;
                        FieldUtils.writeField(field, obj, val.toString().trim(), true);
                    }
                }
            }
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:com.microsoft.rest.Validator.java

/**
 * Validates a user provided required parameter to be not null.
 * A {@link ServiceException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws ServiceException failures wrapped in {@link ServiceException}
 *//*  w  ww .  ja  v a 2  s . c om*/
public static void validate(Object parameter) throws ServiceException {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }

    Class parameterType = parameter.getClass();
    if (ClassUtils.isPrimitiveOrWrapper(parameterType) || parameterType.isEnum()
            || ClassUtils.isAssignable(parameterType, LocalDate.class)
            || ClassUtils.isAssignable(parameterType, DateTime.class)
            || ClassUtils.isAssignable(parameterType, String.class)
            || ClassUtils.isAssignable(parameterType, DateTimeRfc1123.class)
            || ClassUtils.isAssignable(parameterType, Period.class)) {
        return;
    }

    Field[] fields = FieldUtils.getAllFields(parameterType);
    for (Field field : fields) {
        field.setAccessible(true);
        JsonProperty annotation = field.getAnnotation(JsonProperty.class);
        Object property;
        try {
            property = field.get(parameter);
        } catch (IllegalAccessException e) {
            throw new ServiceException(e);
        }
        if (property == null) {
            if (annotation != null && annotation.required()) {
                throw new ServiceException(
                        new IllegalArgumentException(field.getName() + " is required and cannot be null."));
            }
        } else {
            try {
                Class propertyType = property.getClass();
                if (ClassUtils.isAssignable(propertyType, List.class)) {
                    List<?> items = (List<?>) property;
                    for (Object item : items) {
                        Validator.validate(item);
                    }
                } else if (ClassUtils.isAssignable(propertyType, Map.class)) {
                    Map<?, ?> entries = (Map<?, ?>) property;
                    for (Map.Entry<?, ?> entry : entries.entrySet()) {
                        Validator.validate(entry.getKey());
                        Validator.validate(entry.getValue());
                    }
                } else if (parameter.getClass().getDeclaringClass() != propertyType) {
                    Validator.validate(property);
                }
            } catch (ServiceException ex) {
                IllegalArgumentException cause = (IllegalArgumentException) (ex.getCause());
                if (cause != null) {
                    // Build property chain
                    throw new ServiceException(
                            new IllegalArgumentException(field.getName() + "." + cause.getMessage()));
                } else {
                    throw ex;
                }
            }
        }
    }
}

From source file:com.taobao.android.builder.tools.guide.AtlasConfigHelper.java

private static void readConfig(Object object, String prefix, List<AtlasConfigField> configFieldList,
        int groupOrder, String variantName) throws IllegalAccessException {

    if (null == object) {
        return;/*from w  w w . j a v  a 2  s.  c o m*/
    }

    for (Field field : getAllFields(object.getClass())) {

        field.setAccessible(true);

        Config config = field.getAnnotation(Config.class);
        if (null != config) {
            AtlasConfigField configField = new AtlasConfigField();
            configField.name = prefix + "." + field.getName();
            configField.order = config.order();
            configField.desc = config.message();
            Object obj = field.get(object);
            configField.value = (null == obj ? null : String.valueOf(obj));
            configField.groupOrder = groupOrder;
            configField.variantName = variantName;
            configField.type = field.getType().getSimpleName();
            configField.advanced = config.advance();
            configField.group = config.group();
            configFieldList.add(configField);
            continue;
        }

        ConfigGroup configGroup = field.getAnnotation(ConfigGroup.class);
        if (null != configGroup) {

            Object nestedValue = field.get(object);

            if (nestedValue instanceof NamedDomainObjectContainer) {

                readConfig(((NamedDomainObjectContainer) nestedValue).maybeCreate("debug"),
                        prefix + "." + field.getName() + ".debug", configFieldList, configGroup.order(),
                        "debug");
                readConfig(((NamedDomainObjectContainer) nestedValue).maybeCreate("release"),
                        prefix + "." + field.getName() + ".release", configFieldList, configGroup.order(),
                        "release");
            } else {

                readConfig(nestedValue, prefix + "." + field.getName(), configFieldList, configGroup.order(),
                        "");
            }
        }
    }
}

From source file:com.plusub.lib.annotate.JsonParserUtils.java

/**
 * ?//  w ww .  j a  v  a2s.c  om
 * <p>Title: getType
 * <p>Description: 
 * @param field ?
 * @param defaultValue (Json?String)
 * @return defaultValue?obj
 */
private static Object getType(Field field, Object defaultValue, String fieldName) {
    Object value = defaultValue;
    if (showLog) {
        Logger.i(TAG,
                "getType:" + field.getName() + " " + field.getType().getName() + " " + " " + defaultValue);
    }
    if (defaultValue == null) {
        return value;
    }

    String type = field.getType().getName();
    Class clazz = field.getType();
    try {
        if (isBaseDataType(field.getType())) {
            String str = defaultValue + "";
            if (clazz.equals(String.class)) {
                value = defaultValue;
            } else if (clazz.equals(Integer.class) || type.equals("int")) {
                value = Integer.parseInt(str);
            } else if (clazz.equals(Boolean.class) || type.equals("boolean")) {
                String defaultStr = str;
                String result = defaultStr.toLowerCase();
                if (result.equals("true")) {
                    value = true;
                } else if (result.equals("false")) {
                    value = false;
                } else {
                    value = Integer.parseInt(result) > 0 ? true : false;
                }
            } else if (clazz.equals(Double.class) || type.equals("double")) {
                value = Double.parseDouble(str);
            } else if (clazz.equals(Float.class) || type.equals("float")) {
                value = Float.parseFloat(str);
            } else if (clazz.equals(Short.class) || type.equals("short")) {
                value = Short.parseShort(str);
            } else if (clazz.equals(Long.class) || type.equals("long")) {
                value = Long.parseLong(str);
            } else if (clazz.equals(Byte.class) || type.equals("byte")) {
                value = Byte.parseByte(str);
            }
        } else { //?
            if (showLog) {
                Logger.i(TAG, "?, " + defaultValue);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        if (showLog) {
            Logger.e(TAG, "?" + fieldName + "String-->" + field.getType().getName()
                    + ", " + value);
            e.printStackTrace();
        }
        return value;
    }
    return value;
}

From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java

/**
 * Copy source bean properties of type bean to target bean as detached beans
 * /*  ww w .  j  a  v  a2 s  .  c  o  m*/
 * @param sourceBean
 *            Source Bean
 * @param targetBean
 *            Target Bean
 * @param childrenBeanConverters
 *            List of converters needed to convert source bean children of
 *            type bean to target bean children of type bean
 * @param sourceFields
 *            Fields of source Bean
 * @throws Exception
 */
private static void convertBeanFields(AbstractBean sourceBean, AbstractBean targetBean,
        IBeanConverter[] childrenBeanConverters, Field[] sourceFields) throws Exception {

    // Arrays to hold bean field names, source types and target types
    String[] beanFieldNames = new String[0];
    Type[] sourceFieldTypes = new Type[0];
    Type[] targetFieldTypes = new Type[0];

    // For each source field...
    for (Field field : sourceFields) {
        // If source field is a bean...
        if (AbstractBean.class.isAssignableFrom(field.getType())) {
            // Fill Arrays with name, source field type and target type
            beanFieldNames = (String[]) ArrayUtils.add(beanFieldNames, field.getName());

            sourceFieldTypes = (Type[]) ArrayUtils.add(sourceFieldTypes, field.getType());

            targetFieldTypes = (Type[]) ArrayUtils.add(targetFieldTypes,
                    targetBean.getClass().getDeclaredField(field.getName()).getType());
        }
    }

    // For each field with bean type...
    for (int i = 0; i < beanFieldNames.length; i++) {
        String beanFieldName = beanFieldNames[i];
        Type sourceFieldType = sourceFieldTypes[i];
        Type targetFieldType = targetFieldTypes[i];

        // Select the proper converter...
        IBeanConverter converter = getConverter(childrenBeanConverters, sourceFieldType, targetFieldType);

        // Get the target bean constructor
        @SuppressWarnings("unchecked")
        Constructor<AbstractBean> constructor = ((Class<AbstractBean>) targetFieldType)
                .getConstructor(new Class[] {});
        // Create target child bean
        AbstractBean targetChildBean = constructor.newInstance(new Object[] {});
        // Detach target child bean with source child bean and converter
        ((Detachable) targetChildBean).detach(
                (AbstractBean) getGetterMethod(beanFieldName, sourceBean).invoke(sourceBean), converter);
        // Set the detached target bean
        getSetterMethod(beanFieldName, targetFieldType, targetBean).invoke(targetBean, targetChildBean);

    }
}

From source file:com.chuannuo.tangguo.net.TGHttpClient.java

public static void endEntityViaReflection(HttpEntity entity) {
    if (entity instanceof HttpEntityWrapper) {
        try {/*from   ww  w .  j  a  v  a 2 s .  c o m*/
            Field f = null;
            Field[] fields = HttpEntityWrapper.class.getDeclaredFields();
            for (Field ff : fields) {
                if (ff.getName().equals("wrappedEntity")) {
                    f = ff;
                    break;
                }
            }
            if (f != null) {
                f.setAccessible(true);
                HttpEntity wrapped = (HttpEntity) f.get(entity);
                if (wrapped != null) {
                    wrapped.consumeContent();
                }
            }
        } catch (Throwable t) {
            log.e(LOG_TAG, "wrappedEntity consume", t);
        }
    }
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

@SuppressWarnings("unchecked")
private static final void createIntegrationService(Field field, Object targetObject)
        throws AutomationFrameworkException {
    Class<IIntegrationService> clazz;
    try {//w w  w  .j av  a  2  s. c om
        clazz = (Class<IIntegrationService>) field.getType();
    } catch (Exception e) {
        throw new AutomationFrameworkException("Unexpected field type :" + field.getType().getSimpleName()
                + " field name: " + field.getName() + " class: " + targetObject.getClass().getSimpleName()
                + " Thread ID:" + Thread.currentThread().getId()
                + " \n\tThis field must be of the type that extends AbstractPageObject class.", e);
    }
    try {

        field.set(targetObject,
                createIntegrationService(clazz, field.getAnnotation(CCIntegrationService.class)));
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: "
                        + targetObject.getClass().getSimpleName() + " Thread ID:"
                        + Thread.currentThread().getId(),
                e);
    }

}