Example usage for java.lang Class getFields

List of usage examples for java.lang Class getFields

Introduction

In this page you can find the example usage for java.lang Class getFields.

Prototype

@CallerSensitive
public Field[] getFields() throws SecurityException 

Source Link

Document

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

Usage

From source file:com.streamsets.pipeline.maven.rbgen.RBGenMojo.java

@SuppressWarnings("unchecked")
private LinkedHashMap<String, String> extractResources(Class klass) throws Exception {
    LinkedHashMap<String, String> map = new LinkedHashMap<>();
    if (klass.isEnum()) {
        Object[] enums = klass.getEnumConstants();
        for (Object e : enums) {
            String name = ((Enum) e).name();
            String text = name;//  w w w.  j  ava  2 s.c  om
            if (errorCodeClass.isAssignableFrom(klass)) {
                text = invokeMessageMethod(errorCodeClass, "getMessage", e);
            }
            if (labelClass.isAssignableFrom(klass)) {
                text = invokeMessageMethod(labelClass, "getLabel", e);
            }
            map.put(name, text);
        }
    } else if (stageClass.isAssignableFrom(klass)) {
        Annotation stageDef = klass.getAnnotation(stageDefClass);
        if (stageDef != null) {
            String labelText = invokeMessageMethod(stageDefClass, "label", stageDef);
            map.put("stageLabel", labelText);
            String descriptionText = invokeMessageMethod(stageDefClass, "description", stageDef);
            map.put("stageDescription", descriptionText);
            Annotation errorStage = klass.getAnnotation(errorStageClass);
            if (errorStage != null) {
                String errorLabelText = invokeMessageMethod(errorStageClass, "label", errorStage);
                if (errorLabelText.isEmpty()) {
                    errorLabelText = labelText;
                }
                map.put("errorStageLabel", errorLabelText);
                String errorDescriptionText = invokeMessageMethod(errorStageClass, "description", errorStage);
                if (!errorDescriptionText.isEmpty()) {
                    errorDescriptionText = descriptionText;
                }
                map.put("errorStageDescription", errorDescriptionText);

            }
        }
        for (Field field : klass.getFields()) {
            Annotation configDef = field.getAnnotation(configDefClass);
            if (configDef != null) {
                String labelText = invokeMessageMethod(configDefClass, "label", configDef);
                map.put("configLabel." + field.getName(), labelText);
                String descriptionText = invokeMessageMethod(configDefClass, "description", configDef);
                map.put("configDescription." + field.getName(), descriptionText);
            }
        }

    }
    return map;
}

From source file:test.unit.be.fedict.eid.applet.shared.AppletProtocolMessageCatalogTest.java

private void describeClass(Class<?> catalogClass, PrintWriter writer)
        throws IllegalArgumentException, IllegalAccessException {
    writer.println("<section id=\"" + catalogClass.getSimpleName() + "\">");
    writer.println("<title>" + catalogClass.getSimpleName() + "</title>");

    StartRequestMessage startRequestMessage = catalogClass.getAnnotation(StartRequestMessage.class);
    if (null != startRequestMessage) {
        writer.println("<para>");
        writer.println(/*from  w ww.  ja v  a  2s.c  o m*/
                "This message starts a communication session between eID Applet and eID Applet Service.");
        writer.println("It sets the protocol state to: " + startRequestMessage.value());
        writer.println("</para>");
    }

    StopResponseMessage stopResponseMessage = catalogClass.getAnnotation(StopResponseMessage.class);
    if (null != stopResponseMessage) {
        writer.println("<para>");
        writer.println(
                "This message stops a communication session between eID Applet and the eID Applet Service.");
        writer.println("</para>");
    }

    ProtocolStateAllowed protocolStateAllowed = catalogClass.getAnnotation(ProtocolStateAllowed.class);
    if (null != protocolStateAllowed) {
        writer.println("<para>");
        writer.println("This message is only accepted if the eID Applet Service protocol state is: "
                + protocolStateAllowed.value());
        writer.println("</para>");
    }

    Field bodyField = null;

    writer.println("<table>");
    writer.println("<title>" + catalogClass.getSimpleName() + " HTTP headers</title>");
    writer.println("<tgroup cols=\"3\">");
    {
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<colspec colwidth=\"1*\" />");
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<thead>");
        writer.println("<row>");
        writer.println("<entry>Header name</entry>");
        writer.println("<entry>Required</entry>");
        writer.println("<entry>Value</entry>");
        writer.println("</row>");
        writer.println("</thead>");
        writer.println("<tbody>");
        {
            Field[] fields = catalogClass.getFields();
            for (Field field : fields) {
                if (field.getAnnotation(HttpBody.class) != null) {
                    bodyField = field;
                }
                HttpHeader httpHeaderAnnotation = field.getAnnotation(HttpHeader.class);
                if (null == httpHeaderAnnotation) {
                    continue;
                }
                writer.println("<row>");
                writer.println("<entry>");
                writer.println("<code>" + httpHeaderAnnotation.value() + "</code>");
                writer.println("</entry>");
                writer.println("<entry>");
                writer.println((null != field.getAnnotation(NotNull.class))
                        || (0 != (field.getModifiers() & Modifier.FINAL)));
                writer.println("</entry>");
                writer.println("<entry>");
                if (0 != (field.getModifiers() & Modifier.FINAL)) {
                    Object value = field.get(null);
                    writer.println("<code>" + value.toString() + "</code>");
                } else {
                    writer.println("Some " + field.getType().getSimpleName() + " value.");
                }
                writer.println("</entry>");
                writer.println("</row>");
            }
        }
        writer.println("</tbody>");
    }
    writer.println("</tgroup>");
    writer.println("</table>");

    if (null != bodyField) {
        writer.println("<para>HTTP body should contain the data.</para>");
    }

    ResponsesAllowed responsesAllowedAnnotation = catalogClass.getAnnotation(ResponsesAllowed.class);
    if (null != responsesAllowedAnnotation) {
        Class<?>[] responsesAllowed = responsesAllowedAnnotation.value();
        writer.println("<para>");
        writer.println("Allowed eID Applet Service response messages are: ");
        for (Class<?> responseAllowed : responsesAllowed) {
            writer.println("<xref linkend=\"" + responseAllowed.getSimpleName() + "\"/>");
        }
        writer.println("</para>");
    }

    StateTransition stateTransition = catalogClass.getAnnotation(StateTransition.class);
    if (null != stateTransition) {
        writer.println("<para>");
        writer.println("This message will perform an eID Applet protocol state transition to: "
                + stateTransition.value());
        writer.println("</para>");
    }

    writer.println("</section>");
}

From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java

@Override
public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass,
        final Class destinationClass) {
    List<Binding> result = new LinkedList<>();
    BeanInfo sourceBeanInfo, destinationBeanInfo;

    try {/*from w w  w.  j a va 2s .co m*/
        destinationBeanInfo = Introspector.getBeanInfo(destinationClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex);
    }

    try {
        sourceBeanInfo = Introspector.getBeanInfo(sourceClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex);
    }

    boolean allDestinationMembersMapped = true;

    for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) {
        Method destinationMember = destinationProperty.getWriteMethod();

        if (destinationMember != null) {
            BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty);

            if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
                continue;
            }

            List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                    destinationProperty.getName(), MemberAccessType.PROPERTY);

            if (sourceBindingSide != null) {
                BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

                Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                        sourceBindingSideArray, destinationBindingSide);

                if (binding != null) {
                    result.add(binding);
                }
            } else {
                allDestinationMembersMapped = false;
            }
        }
    }

    for (Field destinationMember : destinationClass.getFields()) {
        BindingSide destinationBindingSide = new FieldBindingSide(destinationMember);

        if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
            continue;
        }

        List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                destinationMember.getName(), MemberAccessType.FIELD);

        if (sourceBindingSide != null) {

            BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

            Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                    sourceBindingSideArray, destinationBindingSide);

            if (binding != null) {
                result.add(binding);
            }
        } else {
            allDestinationMembersMapped = false;
        }
    }

    if (_failIfNotAllDestinationMembersMapped) {
        if (allDestinationMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all destination members are mapped." + " This exception has been trown because "
                            + "failIfNotAllDestinationMembersMapped option is enabled.");
        }
    }

    if (_failIfNotAllSourceMembersMapped) {
        boolean allSourceMembersMapped = true;

        for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) {
            Method sourceMember = sourceProperty.getReadMethod();

            if (sourceMember != null) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        // if all properties are mapped we still need to check fields
        if (allSourceMembersMapped) {
            for (Field sourceMember : sourceClass.getFields()) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new FieldBindingSide(sourceMember);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        if (allSourceMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all source members are mapped." + " This exception has been trown because "
                            + "failIfNotAllSourceMembersMapped option is enabled.");
        }
    }

    return result;
}

From source file:be.fedict.eid.applet.maven.DocbookMojo.java

private void describeClass(Class<?> catalogClass, PrintWriter writer)
        throws IllegalArgumentException, IllegalAccessException {
    writer.println("<section id=\"" + catalogClass.getSimpleName() + "\">");
    writer.println("<title>" + catalogClass.getSimpleName() + "</title>");

    StartRequestMessage startRequestMessage = catalogClass.getAnnotation(StartRequestMessage.class);
    if (null != startRequestMessage) {
        writer.println("<para>");
        writer.println(//from w w  w . j av a  2  s.  c o  m
                "This message starts a communication session between eID Applet and eID Applet Service.");
        writer.println("It sets the protocol state to: " + startRequestMessage.value());
        writer.println("</para>");
    }

    StopResponseMessage stopResponseMessage = catalogClass.getAnnotation(StopResponseMessage.class);
    if (null != stopResponseMessage) {
        writer.println("<para>");
        writer.println(
                "This message stops a communication session between eID Applet and the eID Applet Service.");
        writer.println("</para>");
    }

    ProtocolStateAllowed protocolStateAllowed = catalogClass.getAnnotation(ProtocolStateAllowed.class);
    if (null != protocolStateAllowed) {
        writer.println("<para>");
        writer.println("This message is only accepted if the eID Applet Service protocol state is: "
                + protocolStateAllowed.value());
        writer.println("</para>");
    }

    Field bodyField = null;

    writer.println("<table>");
    writer.println("<title>" + catalogClass.getSimpleName() + " HTTP headers</title>");
    writer.println("<tgroup cols=\"3\">");
    {
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<colspec colwidth=\"1*\" />");
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<thead>");
        writer.println("<row>");
        writer.println("<entry>Header name</entry>");
        writer.println("<entry>Required</entry>");
        writer.println("<entry>Value</entry>");
        writer.println("</row>");
        writer.println("</thead>");
        writer.println("<tbody>");
        {
            Field[] fields = catalogClass.getFields();
            for (Field field : fields) {
                if (field.getAnnotation(HttpBody.class) != null) {
                    bodyField = field;
                }
                HttpHeader httpHeaderAnnotation = field.getAnnotation(HttpHeader.class);
                if (null == httpHeaderAnnotation) {
                    continue;
                }
                writer.println("<row>");
                writer.println("<entry>");
                writer.println("<code>" + httpHeaderAnnotation.value() + "</code>");
                writer.println("</entry>");
                writer.println("<entry>");
                writer.println((null != field.getAnnotation(NotNull.class))
                        || (0 != (field.getModifiers() & Modifier.FINAL)));
                writer.println("</entry>");
                writer.println("<entry>");
                if (0 != (field.getModifiers() & Modifier.FINAL)) {
                    Object value = field.get(null);
                    writer.println("<code>" + value.toString() + "</code>");
                } else {
                    writer.println("Some " + field.getType().getSimpleName() + " value.");
                }
                writer.println("</entry>");
                writer.println("</row>");
            }
        }
        writer.println("</tbody>");
    }
    writer.println("</tgroup>");
    writer.println("</table>");

    if (null != bodyField) {
        writer.println("<para>HTTP body should contain the data.</para>");
        Description description = bodyField.getAnnotation(Description.class);
        if (null != description) {
            writer.println("<para>Body content: ");
            writer.println(description.value());
            writer.println("</para>");
        }
    }

    ResponsesAllowed responsesAllowedAnnotation = catalogClass.getAnnotation(ResponsesAllowed.class);
    if (null != responsesAllowedAnnotation) {
        Class<?>[] responsesAllowed = responsesAllowedAnnotation.value();
        writer.println("<para>");
        writer.println("Allowed eID Applet Service response messages are: ");
        for (Class<?> responseAllowed : responsesAllowed) {
            writer.println("<xref linkend=\"" + responseAllowed.getSimpleName() + "\"/>");
        }
        writer.println("</para>");
    }

    StateTransition stateTransition = catalogClass.getAnnotation(StateTransition.class);
    if (null != stateTransition) {
        writer.println("<para>");
        writer.println("This message will perform an eID Applet protocol state transition to: "
                + stateTransition.value());
        writer.println("</para>");
    }

    writer.println("</section>");
}

From source file:com.sos.JSHelper.Options.JSOptionsClass.java

public StringBuffer IterateAllDataElementsByAnnotation(final Class<?> objC, final Object objP,
        final IterationTypes enuIterate4What, StringBuffer pstrBuffer) {
    final String conMethodName = conClassName + "::IterateAllDataElementsByAnnotation";
    String strCommandLineOptions = "";
    if (objC == null) {
        throw new JobSchedulerException(conMethodName + ": objSegment is null, but must be not null");
    }/* w  w  w . j  a v  a 2  s.  c  o  m*/
    Field objField = null;
    SOSOptionElement.gflgProcessHashMap = true;
    try {
        final Field objFields[] = objC.getFields();
        final StringBuffer strXML = new StringBuffer("");
        final String strT = objC.getName();
        if (enuIterate4What == IterationTypes.createXML) {
            strXML.append("<" + strT + " id=" + XmlId.QuotedValue() + ">");
        }
        for (final Field objField2 : objFields) {
            objField = objField2;
            try {
                if (objField.isAnnotationPresent(JSOptionDefinition.class)) {
                    final SOSOptionElement objDE = (SOSOptionElement) objField.get(objP);
                    if (objDE == null) {
                        // final JSOptionsClass objO = (JSOptionsClass) objField.get(objField);
                        // if (objO != null) {
                        // System.out.println("oooooooField : " + objField.getName());
                        //
                        // this.IterateAllDataElementsByAnnotation(objO.getClass(), objO, enuIterate4What, pstrBuffer);
                        // }
                        // else {
                        // System.out.println("*******Field : " + objField.getName());
                        // final Object objO2 = objField.getDeclaringClass();
                        // System.out.println(objField.getType().toString());
                        // // objField.Iterate(enuIterate4What);
                        // // this.IterateAllDataElementsByAnnotation(objO.getClass(), objO, enuIterate4What, pstrBuffer);
                        // }
                    } else {
                        if (enuIterate4What == IterationTypes.setPrefix) {
                            objDE.setPrefix(strAlternativePrefix);
                        }
                        if (enuIterate4What == IterationTypes.setRecord) {
                            SOSOptionElement.gflgProcessHashMap = true;
                            objDE.gflgProcessHashMap = true;
                            objDE.MapValue();
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.getRecord) {
                            // objDE.BuildRecord(pstrBuffer);
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.CheckMandatory) {
                            objDE.CheckMandatory();
                        }
                        if (enuIterate4What == IterationTypes.toOut) {
                            System.out.println(objDE.toString());
                        }
                        if (enuIterate4What == IterationTypes.toString) {
                            pstrBuffer.append(objDE.toString() + "\n");
                        }
                        if (enuIterate4What == IterationTypes.DirtyToString) {
                            if (objDE.isDirty() == true) {
                                pstrBuffer.append(objDE.DirtyToString() + "\n");
                            }
                        }
                        if (enuIterate4What == IterationTypes.createXML) {
                            strXML.append(objDE.toXml());
                        }
                        if (enuIterate4What == IterationTypes.setDefaultValues) {
                            final String strV = objDE.Value();
                            if (strV.length() <= 0) {
                                objDE.Value(objDE.DefaultValue());
                            }
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.clearAllValues) {
                            objDE.Value("");
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.getCommandLine) {
                            pstrBuffer.append(objDE.toCommandLine());
                        }

                        if (enuIterate4What == IterationTypes.countSegmentFields) {
                            // System.out.println("+++++Field : " + objField.getName());
                        }
                        /**
                         * hier versuchen wir herauszubekommen, ob es
                         * in dieser Instanz (weitere) geschachtelte Optionen gibt.
                         * Falls ja, wird die geforderte Funktion auch fr alle diese
                         * Instanzen ausgefhrt.
                         */
                        IterateAllDataElementsByAnnotation(objDE.getClass(), objDE, enuIterate4What,
                                pstrBuffer);
                    }
                } // if (objField.isAnnotationPresent(IDocSegmentField.class))
            } // try
            catch (final ClassCastException objException) {
            } catch (final Exception objE) {
                objE.printStackTrace();
                throw new RuntimeException(objE);
            } finally {
                //
            } // finally
        }
        if (enuIterate4What == IterationTypes.createXML) { // CreateXML
            strXML.append("</" + strT + ">");
            pstrBuffer = strXML;
        }
    } catch (final Exception objException) {
        objException.printStackTrace();
        throw new RuntimeException(objException);
    } finally {
        SOSOptionElement.gflgProcessHashMap = false;
        //
    } // finally
    return pstrBuffer;
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

/**
 * Creates a JSONObject from a POJO.<br>
 * Supports nested maps, POJOs, and arrays/collections.
 *
 * @param bean An object with POJO conventions
 * @throws JSONException if the bean can not be converted to a proper
 *         JSONObject.//from w  w w  .j av  a 2  s. co m
 */
private static JSONObject _fromBean(Object bean, JsonConfig jsonConfig) {
    if (!addInstance(bean)) {
        try {
            return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(bean);
        } catch (JSONException jsone) {
            removeInstance(bean);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        } catch (RuntimeException e) {
            removeInstance(bean);
            JSONException jsone = new JSONException(e);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        }
    }
    fireObjectStartEvent(jsonConfig);

    JsonBeanProcessor processor = jsonConfig.findJsonBeanProcessor(bean.getClass());
    if (processor != null) {
        JSONObject json = null;
        try {
            json = processor.processBean(bean, jsonConfig);
            if (json == null) {
                json = (JSONObject) jsonConfig.findDefaultValueProcessor(bean.getClass())
                        .getDefaultValue(bean.getClass());
                if (json == null) {
                    json = new JSONObject(true);
                }
            }
            removeInstance(bean);
            fireObjectEndEvent(jsonConfig);
        } catch (JSONException jsone) {
            removeInstance(bean);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        } catch (RuntimeException e) {
            removeInstance(bean);
            JSONException jsone = new JSONException(e);
            fireErrorEvent(jsone, jsonConfig);
            throw jsone;
        }
        return json;
    }

    Class beanClass = bean.getClass();
    PropertyNameProcessor propertyNameProcessor = jsonConfig.findJsonPropertyNameProcessor(beanClass);
    Collection exclusions = jsonConfig.getMergedExcludes(beanClass);
    JSONObject jsonObject = new JSONObject();
    try {
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
        PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
        for (int i = 0; i < pds.length; i++) {
            boolean bypass = false;
            String key = pds[i].getName();
            if (exclusions.contains(key)) {
                continue;
            }

            if (jsonConfig.isIgnoreTransientFields() && isTransientField(key, beanClass)) {
                continue;
            }

            Class type = pds[i].getPropertyType();
            try {
                pds[i].getReadMethod();
            } catch (Exception e) {
                // bug 2565295
                String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED";
                fireWarnEvent(warning, jsonConfig);
                log.info(warning);
                continue;
            }
            if (pds[i].getReadMethod() != null) {
                Object value = PropertyUtils.getProperty(bean, key);
                if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) {
                    continue;
                }
                JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type, key);
                if (jsonValueProcessor != null) {
                    value = jsonValueProcessor.processObjectValue(key, value, jsonConfig);
                    bypass = true;
                    if (!JsonVerifier.isValidJsonValue(value)) {
                        throw new JSONException("Value is not a valid JSON value. " + value);
                    }
                }
                if (propertyNameProcessor != null) {
                    key = propertyNameProcessor.processPropertyName(beanClass, key);
                }
                setValue(jsonObject, key, value, type, jsonConfig, bypass);
            } else {
                String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED";
                fireWarnEvent(warning, jsonConfig);
                log.info(warning);
            }
        }
        // inspect public fields, this operation may fail under
        // a SecurityManager so we will eat all exceptions
        try {
            if (!jsonConfig.isIgnorePublicFields()) {
                Field[] fields = beanClass.getFields();
                for (int i = 0; i < fields.length; i++) {
                    boolean bypass = false;
                    Field field = fields[i];
                    String key = field.getName();
                    if (exclusions.contains(key)) {
                        continue;
                    }

                    if (jsonConfig.isIgnoreTransientFields() && isTransientField(field)) {
                        continue;
                    }

                    Class type = field.getType();
                    Object value = field.get(bean);
                    if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) {
                        continue;
                    }
                    JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type,
                            key);
                    if (jsonValueProcessor != null) {
                        value = jsonValueProcessor.processObjectValue(key, value, jsonConfig);
                        bypass = true;
                        if (!JsonVerifier.isValidJsonValue(value)) {
                            throw new JSONException("Value is not a valid JSON value. " + value);
                        }
                    }
                    if (propertyNameProcessor != null) {
                        key = propertyNameProcessor.processPropertyName(beanClass, key);
                    }
                    setValue(jsonObject, key, value, type, jsonConfig, bypass);
                }
            }
        } catch (Exception e) {
            log.trace("Couldn't read public fields.", e);
        }
    } catch (JSONException jsone) {
        removeInstance(bean);
        fireErrorEvent(jsone, jsonConfig);
        throw jsone;
    } catch (Exception e) {
        removeInstance(bean);
        JSONException jsone = new JSONException(e);
        fireErrorEvent(jsone, jsonConfig);
        throw jsone;
    }

    removeInstance(bean);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
}

From source file:net.sf.json.JSONObject.java

private static JSONObject defaultBeanProcessing(Object bean, JsonConfig jsonConfig) {
    Class beanClass = bean.getClass();
    PropertyNameProcessor propertyNameProcessor = jsonConfig.findJsonPropertyNameProcessor(beanClass);
    Collection exclusions = jsonConfig.getMergedExcludes(beanClass);
    JSONObject jsonObject = new JSONObject();
    try {/*from   w ww .j ava2  s . co  m*/
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
        PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
        for (int i = 0; i < pds.length; i++) {
            boolean bypass = false;
            String key = pds[i].getName();
            if (exclusions.contains(key)) {
                continue;
            }

            if (jsonConfig.isIgnoreTransientFields() && isTransientField(key, beanClass, jsonConfig)) {
                continue;
            }

            Class type = pds[i].getPropertyType();
            try {
                pds[i].getReadMethod();
            } catch (Exception e) {
                // bug 2565295
                String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED";
                fireWarnEvent(warning, jsonConfig);
                log.info(warning);
                continue;
            }
            if (pds[i].getReadMethod() != null) {
                /*
                if( jsonConfig.isIgnoreJPATransient() ){
                   try{
                      Class transientClass = Class.forName( "javax.persistence.Transient" );
                      if( pds[i].getReadMethod()
                   .getAnnotation( transientClass ) != null ){
                continue;
                      }
                   }catch( ClassNotFoundException cnfe ){
                      // ignore
                   }
                }
                */
                if (isTransient(pds[i].getReadMethod(), jsonConfig))
                    continue;

                Object value = PropertyUtils.getProperty(bean, key);
                if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) {
                    continue;
                }
                JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type, key);
                if (jsonValueProcessor != null) {
                    value = jsonValueProcessor.processObjectValue(key, value, jsonConfig);
                    bypass = true;
                    if (!JsonVerifier.isValidJsonValue(value)) {
                        throw new JSONException("Value is not a valid JSON value. " + value);
                    }
                }
                if (propertyNameProcessor != null) {
                    key = propertyNameProcessor.processPropertyName(beanClass, key);
                }
                setValue(jsonObject, key, value, type, jsonConfig, bypass);
            } else {
                String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED";
                fireWarnEvent(warning, jsonConfig);
                log.info(warning);
            }
        }
        // inspect public fields, this operation may fail under
        // a SecurityManager so we will eat all exceptions
        try {
            if (!jsonConfig.isIgnorePublicFields()) {
                Field[] fields = beanClass.getFields();
                for (int i = 0; i < fields.length; i++) {
                    boolean bypass = false;
                    Field field = fields[i];
                    String key = field.getName();
                    if (exclusions.contains(key)) {
                        continue;
                    }

                    if (jsonConfig.isIgnoreTransientFields() && isTransient(field, jsonConfig)) {
                        continue;
                    }

                    Class type = field.getType();
                    Object value = field.get(bean);
                    if (jsonPropertyFilter != null && jsonPropertyFilter.apply(bean, key, value)) {
                        continue;
                    }
                    JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass, type,
                            key);
                    if (jsonValueProcessor != null) {
                        value = jsonValueProcessor.processObjectValue(key, value, jsonConfig);
                        bypass = true;
                        if (!JsonVerifier.isValidJsonValue(value)) {
                            throw new JSONException("Value is not a valid JSON value. " + value);
                        }
                    }
                    if (propertyNameProcessor != null) {
                        key = propertyNameProcessor.processPropertyName(beanClass, key);
                    }
                    setValue(jsonObject, key, value, type, jsonConfig, bypass);
                }
            }
        } catch (Exception e) {
            log.trace("Couldn't read public fields.", e);
        }
    } catch (JSONException jsone) {
        removeInstance(bean);
        fireErrorEvent(jsone, jsonConfig);
        throw jsone;
    } catch (Exception e) {
        removeInstance(bean);
        JSONException jsone = new JSONException(e);
        fireErrorEvent(jsone, jsonConfig);
        throw jsone;
    }
    return jsonObject;
}

From source file:org.regenstrief.util.Util.java

/**
 * Writes information about a .jar/*  w  w w  . j a va 2  s  .  c o  m*/
 * 
 * @param path the path of the .jar
 * @param w the Writer
 * @throws Exception if an I/O problem occurs
 **/
public final static void jarInfo(final String path, final Writer w) throws Exception {
    final JarFile jar = new JarFile(new File(path));
    final Enumeration<JarEntry> en = jar.entries();
    final PrintWriter pw = getPrintWriter(w);

    while (en.hasMoreElements()) {
        final String name = en.nextElement().getName();
        if (!name.endsWith(".class")) {
            continue;
        }
        try {
            Class<?> c = Class.forName(name.substring(0, name.length() - 6).replace('/', '.'));
            final Member[][] allMembers = new Member[][] { c.getFields(), c.getConstructors(), c.getMethods() };
            pw.print(c);
            for (c = c.getSuperclass(); c != null; c = c.getSuperclass()) {
                pw.print(" extends ");
                pw.print(c.getName());
            }
            pw.println();
            pw.println('{');
            for (int j = 0; j < allMembers.length; j++) {
                final Member[] members = allMembers[j];
                for (final Member member : members) {
                    if (!Modifier.isPublic(member.getModifiers())) {
                        continue;
                    }
                    pw.print('\t');
                    pw.print(member);
                    pw.println(';');
                }
                if ((members.length > 0) && (j < allMembers.length - 1)) {
                    pw.println();
                }
            }
            pw.println('}');
        } catch (final Throwable e) {
            pw.println(e);
        }
        pw.println();
    }

    pw.flush();
    jar.close();
}

From source file:com.fluidops.iwb.api.ReadDataManagerImpl.java

/**
 * RDF string to Java Object/*from  w  w  w  . j av  a2  s .  c  o m*/
 */
@SuppressWarnings({ "unchecked" })
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception caught for robustness.")
private <T> T convert(Value s, Class<T> t, Map<Value, Object> resourceStack) {
    if (s == null)
        return null;

    // avoid endless recursion
    if (resourceStack != null) {
        Object alreadySeen = resourceStack.get(s);
        if (alreadySeen != null) {
            if (alreadySeen.getClass().isAssignableFrom(t))
                return (T) alreadySeen;
            else
                // TODO: theoretically, a subject could be accessed as Type
                // T1 and later
                // as Type T2. So really, the stack should be Map<String,
                // Map<Class, Object>>
                // but this seems like a bit of overkill, so we just return
                // null if the type
                // seen for this resource before in the stack does not match
                return null;
        }
    }

    try {
        if (t == short.class || t == Short.class)
            return (T) new Short(s.stringValue());
        if (t == byte.class || t == Byte.class)
            return (T) new Byte(s.stringValue());
        if (t == boolean.class || t == Boolean.class)
            return (T) Boolean.valueOf(s.stringValue());
        if (t == long.class || t == Long.class)
            return (T) new Long(s.stringValue());
        if (t == float.class || t == Float.class)
            return (T) new Float(s.stringValue());
        if (t == double.class || t == Double.class)
            return (T) new Double(s.stringValue());
        if (t == int.class || t == Integer.class)
            return (T) new Integer(s.stringValue());
        if (t == String.class)
            return (T) s.stringValue();
        if (t == Date.class)
            return (T) literal2HumanDate(s.stringValue());
        if (t == Calendar.class) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(literal2HumanDate(s.stringValue()));
            return (T) cal;
        }
        if (t == URL.class)
            return (T) new URL(s.stringValue());
        if (t == java.net.URI.class)
            return (T) new java.net.URI(s.stringValue());
        if (t == org.openrdf.model.URI.class)
            return (T) s;
        /*
         * todo // interface - use dynamic proxy if ( t.isInterface() ||
         * Proxy.class.isAssignableFrom( t ) ) return (T)Proxy.newInstance(
         * s, this, t );
         */

        T instance = t.newInstance();

        // create object only if it is necessary
        if (resourceStack == null)
            resourceStack = new HashMap<Value, Object>();
        resourceStack.put(s, instance);

        for (Field f : t.getFields()) {
            if (Modifier.isStatic(f.getModifiers()))
                continue;
            if (Modifier.isFinal(f.getModifiers()))
                continue;

            if (List.class.isAssignableFrom(f.getType())) {
                @SuppressWarnings("rawtypes")
                Class listTypeValue = String.class;
                if (f.getGenericType() instanceof ParameterizedType)
                    listTypeValue = (Class<?>) ((ParameterizedType) f.getGenericType())
                            .getActualTypeArguments()[0];

                if (f.getAnnotation(RDFMapping.class) == null ? false
                        : f.getAnnotation(RDFMapping.class).inverse()) {
                    List<String> x = getInverseProps(s, RDFMappingUtil.uri(f), listTypeValue, false);
                    f.set(instance, x);
                } else {
                    List<T> x = new ArrayList<T>();
                    for (Value v : getProps((Resource) s, RDFMappingUtil.uri(f)))
                        x.add((T) convert(v, listTypeValue, resourceStack));
                    f.set(instance, x);
                }
            } else {
                if (f.getName().equals("__resource"))
                    f.set(instance, s);
                else if (f.getAnnotation(RDFMapping.class) == null ? false
                        : f.getAnnotation(RDFMapping.class).inverse()) {
                    Object x = getInversePropInternal(s, RDFMappingUtil.uri(f), f.getType(), resourceStack);
                    f.set(instance, x);
                } else if (s instanceof Resource) {
                    // for Resources, traverse deeper, for Literals, there
                    // is no substructure
                    Object x = getPropInternal(getProp((Resource) s, RDFMappingUtil.uri(f)), f.getType(),
                            resourceStack);
                    f.set(instance, x);
                }
            }
        }
        return instance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}