Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

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

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#subtract(java.lang.Object, java.lang.Number, java.lang.Class)}.
 *//*from w  ww.  j a  va  2s .  com*/
@SuppressWarnings("unchecked")
@Test
public void testSubtractObjectNumberClassOfT() {
    assertEquals("null", null, subtract(null, null, null));
    assertEquals("null", null, subtract("123.456", null, null));
    assertEquals("null", null, subtract("123.456", 1, null));
    assertEquals("null", null, subtract("", 10, null));
    assertEquals("null", null, subtract(null, 10, null));
    assertEquals("null", null, subtract(123.456, 10, null));
    assertEquals("123.456 - .456", (Object) 123, subtract(123.456, .456, int.class));
    assertEquals("123.456 - .456: Float", (Object) 123f, subtract(123.456, .456, Float.class));

    assertEquals("123.912 - .456: Float", (Object) 123.456d, subtract(123.912, .456, Double.class));
    assertEquals("123.912 - .456: Float", (Object) 123, subtract(123.912, .456, Integer.class));

    assertEquals("123.456 - .456: Float", (Object) Float.class,
            subtract(123.912d, .456, Float.class).getClass());
    assertEquals("123.456 - .456: Float", (Object) Float.class,
            subtract(123.456, .456d, Float.class).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            assertEquals("null: default: " + type.getSimpleName(), valueOf(null, typeOfN),
                    subtract(null, null, typeOfN));
            assertEquals("123.456: " + type.getSimpleName(), valueOf(123.912 - .456, typeOfN),
                    subtract("123.912", .456, typeOfN));
            assertEquals("123.456 - NaN: " + type.getSimpleName(), valueOf(123.456, typeOfN),
                    subtract(123.456, Float.NaN, typeOfN));
            assertEquals("NaN - 123.456: " + type.getSimpleName(), valueOf(123.456, typeOfN),
                    subtract("NaN", 123.456, typeOfN));
            assertEquals("invalid - 123.456: " + type.getSimpleName(), valueOf(123.456, typeOfN),
                    subtract("not a number", 123.456, typeOfN));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = valueOf(-Double.MAX_VALUE, typeOfN);
            } else if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = new BigDecimal("123.456").subtract(INFINITY_DOUBLE);
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("123.456 - Infinity: " + type.getSimpleName(), expected,
                    subtract(123.456, Double.POSITIVE_INFINITY, typeOfN));

            if (ObjectUtils.isAny(wrapper, Float.class)) {
                expected = valueOf("Infinity", typeOfN);
            } else if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = INFINITY_DOUBLE.subtract(new BigDecimal("123.456"));
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("Infinity - 123.456: " + type.getSimpleName(), expected,
                    subtract("Infinity", 123.456, typeOfN));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String),
 * for the specified property./*from www.  j  a va  2s  .co m*/
 * @param propertyName name of the property
 * @param oldValue the previous value, if available (may be <code>null</code>)
 * @param newValue the proposed new value
 * @param requiredType the type we must convert to
 * (or <code>null</code> if not known, for example in case of a collection element)
 * @param descriptor the JavaBeans descriptor for the property
 * @param methodParam the method parameter that is the target of the conversion
 * (may be <code>null</code>)
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException if type conversion failed
 */
protected Object convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class requiredType,
        PropertyDescriptor descriptor, MethodParameter methodParam) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (editor == null) {
            editor = findDefaultEditor(requiredType, descriptor);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (String.class.equals(requiredType)
                    && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return convertedValue.toString();
            } else if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                return convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection
                    && CollectionFactory.isApproximableCollectionType(requiredType)) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName,
                        methodParam);
            } else if (convertedValue instanceof Map && CollectionFactory.isApproximableMapType(requiredType)) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map) convertedValue, propertyName, methodParam);
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                String strValue = ((String) convertedValue).trim();
                if (JdkVersion.isAtLeastJava15() && requiredType.isEnum() && "".equals(strValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                // Try field lookup as fallback: for JDK 1.5 enum or custom enum
                // with values defined as static fields. Resulting value still needs
                // to be checked, hence we don't return it right away.
                try {
                    Field enumField = requiredType.getField(strValue);
                    convertedValue = enumField.get(null);
                } catch (Exception ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Field [" + convertedValue + "] isn't an enum value", ex);
                    }
                }
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            // Definitely doesn't match: throw IllegalArgumentException.
            StringBuffer msg = new StringBuffer();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '" + propertyName + "'");
            }
            if (editor != null) {
                msg.append(
                        ": PropertyEditor [" + editor.getClass().getName() + "] returned inappropriate value");
            } else {
                msg.append(": no matching editors or conversion strategy found");
            }
            throw new IllegalArgumentException(msg.toString());
        }
    }

    return convertedValue;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#ceil(java.lang.Object, java.lang.Class)}.
 *///from  w ww  .  jav a2s .  c o  m
@SuppressWarnings("unchecked")
@Test
public void testCeilObjectClassOfT() {
    assertEquals("null", null, ceil(null, null));
    assertEquals("null", null, ceil("", null));
    assertEquals("null", null, ceil("not a number.", null));
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "4");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("4");
            }
            assertEquals("PI: String: " + type.getSimpleName(), expected, ceil("3.14", typeOfN));
            assertEquals("PI: Float: " + type.getSimpleName(), expected, ceil(3.141592653589793f, typeOfN));
            assertEquals("PI: Double: " + type.getSimpleName(), expected, ceil(Math.PI, typeOfN));
            assertEquals("PI: BigDecimal: " + type.getSimpleName(), expected,
                    ceil(BigDecimal.valueOf(Math.PI), typeOfN));
            assertEquals("(Double) (10 / 3): " + type.getSimpleName(), expected, ceil(
                    (Object) (BigDecimal.TEN.divide(new BigDecimal("3"), MathContext.DECIMAL128)), typeOfN));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
                assertEquals("Huge: " + type.getSimpleName(), expected,
                        ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), typeOfN));
            } else if (BigDecimal.class.equals(type)) {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toPlainString();
                Object actual = ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), BigDecimal.class)
                        .toPlainString();
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            } else {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toBigInteger();
                Object actual = ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigInteger.class);
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#floor(java.lang.Object, java.lang.Class)}.
 *//*from   w ww. j av  a  2  s.c  o  m*/
@SuppressWarnings("unchecked")
@Test
public void testFloorObjectClassOfT() {
    assertEquals("null", null, floor(null, null));
    assertEquals("null", null, floor("", null));
    assertEquals("null", null, floor("not a number.", null));
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "3");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("3");
            }
            assertEquals("PI: String: " + type.getSimpleName(), expected, floor("3.14", typeOfN));
            assertEquals("PI: Float: " + type.getSimpleName(), expected, floor(3.141592653589793f, typeOfN));
            assertEquals("PI: Double: " + type.getSimpleName(), expected, floor(Math.PI, typeOfN));
            assertEquals("PI: BigDecimal: " + type.getSimpleName(), expected,
                    floor(BigDecimal.valueOf(Math.PI), typeOfN));
            assertEquals("(Double) (10 / 3): " + type.getSimpleName(), expected, floor(
                    (Object) (BigDecimal.TEN.divide(new BigDecimal("3"), MathContext.DECIMAL128)), typeOfN));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
                assertEquals("Huge: " + type.getSimpleName(), expected,
                        floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), typeOfN));
            } else if (BigDecimal.class.equals(type)) {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toPlainString();
                Object actual = floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigDecimal.class).toPlainString();
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            } else {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toBigInteger();
                Object actual = floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigInteger.class);
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:org.cloudgraph.store.mapping.StoreMapping.java

private CloudGraphStoreMapping deriveMapping() throws NoSuchFieldException, SecurityException {
    if (log.isDebugEnabled())
        log.debug("deriving mapping");
    CloudGraphStoreMapping result = new CloudGraphStoreMapping();
    for (Class<?> c : this.annotatedClasses) {
        org.cloudgraph.store.mapping.annotation.Table tableAnnot = c
                .getAnnotation(org.cloudgraph.store.mapping.annotation.Table.class);
        if (log.isDebugEnabled())
            log.debug("discovered " + tableAnnot.name() + " table mapping");
        Table table = new Table();
        result.getTables().add(table);// w w w  .j a va  2  s.c o m
        table.setName(tableAnnot.name());
        table.setDataColumnFamilyName(tableAnnot.dataColumnFamilyName());
        table.setTombstoneRows(tableAnnot.tombstoneRows());
        table.setTombstoneRowsOverwriteable(tableAnnot.tombstoneRowsOverwriteable());
        table.setUniqueChecks(tableAnnot.uniqueChecks());
        if (tableAnnot.hashAlgorithm().ordinal() != HashAlgorithmName.NONE.ordinal()) {
            HashAlgorithm hash = new HashAlgorithm();
            hash.setName(tableAnnot.hashAlgorithm());
            table.setHashAlgorithm(hash);
        }
        // add properties

        DataGraph dataGraph = new DataGraph();
        table.getDataGraphs().add(dataGraph);
        org.plasma.sdo.annotation.Type typeAnnot = c.getAnnotation(org.plasma.sdo.annotation.Type.class);

        String typeName = typeAnnot.name();
        if (typeName == null || typeName.trim().length() == 0)
            typeName = c.getSimpleName(); // use the enumeration class name
        dataGraph.setType(typeName);
        org.plasma.sdo.annotation.Namespace namespaceAnnot = c.getPackage()
                .getAnnotation(org.plasma.sdo.annotation.Namespace.class);
        dataGraph.setUri(namespaceAnnot.uri());
        if (log.isDebugEnabled())
            log.debug("added data graph for type: " + dataGraph.getUri() + "#" + dataGraph.getType());

        ColumnKeyModel columnModel = new ColumnKeyModel();
        columnModel.setFieldDelimiter("|");
        columnModel.setReferenceMetadataDelimiter("#");
        columnModel.setSequenceDelimiter("@");
        dataGraph.setColumnKeyModel(columnModel);
        ColumnKeyField pkgColKeyField = new ColumnKeyField();
        pkgColKeyField.setName(MetaFieldName.PKG);
        columnModel.getColumnKeyFields().add(pkgColKeyField);
        ColumnKeyField typeColKeyField = new ColumnKeyField();
        typeColKeyField.setName(MetaFieldName.TYPE);
        columnModel.getColumnKeyFields().add(typeColKeyField);
        ColumnKeyField propColKeyField = new ColumnKeyField();
        propColKeyField.setName(MetaFieldName.PROPERTY);
        columnModel.getColumnKeyFields().add(propColKeyField);

        RowKeyModel rowKeyModel = new RowKeyModel();
        dataGraph.setRowKeyModel(rowKeyModel);
        rowKeyModel.setFieldDelimiter(tableAnnot.rowKeyFieldDelimiter());

        for (Object o : c.getEnumConstants()) {
            Enum<?> enm = (Enum<?>) o;
            Field field = c.getField(enm.name());
            org.cloudgraph.store.mapping.annotation.RowKeyField rowKeyFieldAnnot = field
                    .getAnnotation(org.cloudgraph.store.mapping.annotation.RowKeyField.class);
            if (rowKeyFieldAnnot != null) {
                RowKeyField rowKeyField = new RowKeyField();
                rowKeyModel.getRowKeyFields().add(rowKeyField);
                DataField userDefinedField = new DataField();
                rowKeyField.setDataField(userDefinedField);
                userDefinedField.setPath(field.getName());

                userDefinedField.setCodecType(rowKeyFieldAnnot.codecType());
            }
        }

    }

    return result;
}

From source file:pt.iflow.flows.FlowData.java

@Deprecated
private InstantiationResult instantiateSubFlow(UserInfoInterface ui, XmlBlock xmlblock, int anFlowId,
        List<FlowSetting> alSettings, Hashtable<Integer, Block> htBlocks, int offset) throws Exception {
    Class<?>[] argsClass = new Class[] { int.class, int.class, int.class, String.class };
    String subflow = null;/*from ww  w  .j  av  a2 s .c  o m*/
    Attribute attrActiv = null;
    final int FLOW = 0;
    final int SUBFLOW = 1;
    final int TYPE = 2;

    offset += iOFFSET;

    int size = (xmlblock.getXmlAttributeCount() - 1) / 4; // raio de conta

    String[][] saInVars = new String[size][3];
    String[][] saOutVars = new String[size][3];

    // Attributes do block In & Out
    for (int attrNumber = 0; attrNumber < xmlblock.getXmlAttributeCount(); attrNumber++) {
        XmlAttribute xmlAttribute = xmlblock.getXmlAttribute(attrNumber);
        String name = xmlAttribute.getName();

        int pos = -1;
        try {
            pos = Integer.parseInt(name.substring(8, 9));
        } catch (NumberFormatException nfe) {
        }

        if (name.charAt(0) == 'I') {
            if (name.substring(1, 8).equals("bigflow")) {
                saInVars[pos][FLOW] = xmlAttribute.getValue();
            } else {
                saInVars[pos][SUBFLOW] = xmlAttribute.getValue();
            }
        } else if (name.charAt(0) == 'O') {
            if (name.substring(1, 8).equals("bigflow")) {
                saOutVars[pos][FLOW] = xmlAttribute.getValue();
            } else {
                saOutVars[pos][SUBFLOW] = xmlAttribute.getValue();
            }
        } else if (name.charAt(0) == 'M') {
            subflow = xmlAttribute.getValue();
        } else if (name.charAt(0) == 'A') {
            attrActiv = new Attribute(xmlAttribute.getName(), xmlAttribute.getValue());
        } else if (name.charAt(0) == 'T') {
            saInVars[pos][TYPE] = xmlAttribute.getValue();
            saOutVars[pos][TYPE] = xmlAttribute.getValue();
        }
    }

    if (!this.hasSubFlow(subflow)) {
        this._htSubFlows.put(subflow, subflow);
    } else {
        throw new Exception("Recursividade de Fluxos encontrada!");
    }
    byte[] sXml = BeanFactory.getFlowHolderBean().readSubFlowData(ui, subflow);
    XmlFlow xmlSubFlow = FlowMarshaller.unmarshal(sXml);
    InstantiationResult flowResult = instantiateFlow(ui, xmlSubFlow, anFlowId, alSettings, htBlocks, offset);

    if (flowResult == null) {
        throw new Exception("N&atilde;o foi possivel instanciar o subfluxo " + subflow);
    } else if (flowResult.start == null) {
        throw new Exception("O subfluxo " + subflow + " n&atilde;o tem BlockStart");
    } else if (flowResult.end == null || flowResult.end.size() == 0) {
        throw new Exception("O subfluxo " + subflow + " n&atilde;o tem BlockEnd");
    }

    if (!_htSubFlowEndPorts.containsKey(subflow)) {
        Hashtable<Integer, Object[]> htPorts = new Hashtable<Integer, Object[]>();
        this.buildConnEndPorts(ui, htBlocks, htPorts, flowResult.start);
        _htSubFlowEndPorts.put(subflow, htPorts);
    }

    // remove the start & end blocks
    // replace them by BlockSubFlowIn & BlockSubFlowOut
    htBlocks.remove(new Integer(flowResult.start.getId()));
    this._vFlow.remove(flowResult.start);
    Iterator<Block> it = flowResult.getEndIterator();
    while (it.hasNext()) {
        Block bEnd = it.next();
        htBlocks.remove(new Integer(bEnd.getId()));
        this._vFlow.remove(bEnd);
    }

    // BlockSubFlowIn
    Integer blockIdIn = new Integer(flowResult.start.getId() - 100000);
    Object[] args = new Object[] { new Integer(anFlowId), blockIdIn, new Integer(0), new String(subflow) };
    String className = "pt.iflow.blocks.BlockSubFlowIn";
    Class<? extends Block> blockClassIn = loadBlockClass(ui, className);
    Constructor<? extends Block> argsConstructor = blockClassIn.getConstructor(argsClass);
    Block bBlockIn = argsConstructor.newInstance(args);

    // attributes
    for (int i = 0; i < saInVars.length; i++) {
        if (StringUtils.isEmpty(saInVars[i][FLOW]) || StringUtils.isEmpty(saInVars[i][SUBFLOW]))
            continue;
        Attribute attr = new Attribute();
        attr.setName(saInVars[i][FLOW]);
        attr.setValue(saInVars[i][SUBFLOW]);
        bBlockIn.addAttribute(attr);
        attr = new Attribute("Type_" + saInVars[i][FLOW], saInVars[i][TYPE]);
        bBlockIn.addAttribute(attr);
    }

    // BlockSubFlowOut
    Integer blockIdOut = new Integer(flowResult.end.get(0).getId() - 100000);
    args = new Object[] { new Integer(anFlowId), blockIdOut, new Integer(0), new String(subflow) };
    className = "pt.iflow.blocks.BlockSubFlowOut";
    Class<? extends Block> blockClassOut = loadBlockClass(ui, className);
    argsConstructor = blockClassOut.getConstructor(argsClass);
    Block bBlockOut = argsConstructor.newInstance(args);

    for (int i = 0; i < saOutVars.length; i++) {
        if (saOutVars[i][FLOW] == null || saOutVars[i][FLOW].equals("") || saOutVars[i][SUBFLOW] == null
                || saOutVars[i][SUBFLOW].equals(""))
            continue;
        Attribute attr = new Attribute();
        attr.setName(saOutVars[i][FLOW]);
        attr.setValue(saOutVars[i][SUBFLOW]);
        bBlockOut.addAttribute(attr);
        attr = new Attribute("Type_" + saOutVars[i][FLOW], saOutVars[i][TYPE]);
        bBlockOut.addAttribute(attr);
    }
    if (attrActiv != null)
        bBlockOut.addAttribute(attrActiv);

    // portos do BlockSubFlowIn
    Port port = null;
    try {
        XmlPort xmlPort = xmlblock.getXmlPort(0); // portIn -> portIn
        port = new Port();
        port.setName("portIn");
        port.setConnectedBlockId(xmlPort.getConnectedBlockId() + (offset - iOFFSET));
        port.setConnectedPortName(xmlPort.getConnectedPortName());
        Field fPort = blockClassIn.getField("portIn");
        fPort.set(bBlockIn, port);

        port = new Port(); // portOutThread
        port.setName("portOutThread");
        port.setConnectedBlockId(bBlockOut.getId());
        port.setConnectedPortName("portInThread");
        fPort = blockClassIn.getField("portOutThread");
        fPort.set(bBlockIn, port);

        port = new Port(); // portOut
        port.setName("portOut");
        fPort = blockClassIn.getField("portOut");
        fPort.set(bBlockIn, port);

        Port[] patmp = flowResult.start.getOutPorts(ui);
        for (int p = 0; patmp != null && p < patmp.length; p++) {
            if (patmp[p] == null)
                continue;

            Integer iBId = new Integer(patmp[p].getConnectedBlockId());
            Block bInnerBlock = (Block) htBlocks.get(iBId);
            if (bInnerBlock == null)
                continue;

            bInnerBlock.getInPorts(ui)[0].setConnectedBlockId(bBlockIn.getId());
            bBlockIn.getOutPorts(ui)[0].setConnectedBlockId(patmp[p].getConnectedBlockId());
            bBlockIn.getOutPorts(ui)[0].setConnectedPortName(patmp[p].getConnectedPortName());
        }

        //       xmlPort = xmlblock.getXmlPort(2); // portError -> portError
        //       port = new Port();
        //       port.setName("portError");
        //       port.setConnectedBlockId(xmlPort.getConnectedBlockId()
        //           + (offset - iOFFSET));
        //       port.setConnectedPortName(xmlPort.getConnectedPortName());
        //       fPort = blockClassIn.getField("portError");
        //       fPort.set(bBlockIn, port);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Erro ao criar porto " + port.getName() + " para o bloco SubFlowIn");
    }

    // portos do BlockSubFlowOut
    try {
        port = new Port(); // portIn
        port.setName("portIn");
        Field fPort = blockClassOut.getField("portIn");
        fPort.set(bBlockOut, port);

        Hashtable<Integer, Object[]> htPorts = _htSubFlowEndPorts.get(subflow);
        Iterator<Integer> portIt = htPorts.keySet().iterator();
        while (portIt.hasNext()) {
            Integer itmp = portIt.next();
            Object[] otmp = (Object[]) htPorts.get(itmp);
            Port outPort = (Port) otmp[0];

            outPort.setConnectedBlockId(bBlockOut.getId());
            outPort.setConnectedPortName(port.getName());

            bBlockOut.getInPorts(ui)[0].setConnectedBlockId(itmp.intValue());
            bBlockOut.getInPorts(ui)[0].setConnectedPortName(outPort.getName());
        }

        port = new Port(); // portInThread
        port.setName("portInThread");
        port.setConnectedBlockId(bBlockIn.getId());
        port.setConnectedPortName("portOutThread");
        fPort = blockClassOut.getField("portInThread");
        fPort.set(bBlockOut, port);

        XmlPort xmlPort = xmlblock.getXmlPort(1); // portSuccess -> portOut
        port = new Port();
        port.setName("portOut");
        port.setConnectedBlockId(xmlPort.getConnectedBlockId() + (offset - iOFFSET));
        port.setConnectedPortName(xmlPort.getConnectedPortName());
        fPort = blockClassOut.getField("portOut");
        fPort.set(bBlockOut, port);

        //       xmlPort = xmlblock.getXmlPort(2); // portError
        //       port = new Port();
        //       port.setName("portError");
        //       port.setConnectedBlockId(xmlPort.getConnectedBlockId()
        //           + (offset - iOFFSET));
        //       port.setConnectedPortName(xmlPort.getConnectedPortName());
        //       fPort = blockClassOut.getField("portError");
        //       fPort.set(bBlockOut, port);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Erro ao criar porto " + port.getName() + " para o bloco SubFlowOut");
    }

    this._vFlow.add(bBlockIn);
    this._vFlow.add(bBlockOut);

    htBlocks.put(blockIdIn, bBlockIn);
    htBlocks.put(blockIdOut, bBlockOut);

    ArrayList<Block> altmp = new ArrayList<Block>();
    altmp.add(bBlockOut);

    return new InstantiationResult(bBlockIn, altmp);
}

From source file:pt.iflow.flows.FlowData.java

private InstantiationResult instantiateFlow(UserInfoInterface ui, XmlFlow aXmlFlow, int anFlowId,
        List<FlowSetting> alSettings, Hashtable<Integer, Block> htBlocks, int offset) throws Exception {

    Block blockStart = null;/*from   w  ww  . ja  va  2s .co  m*/
    ArrayList<Block> alBlockEnd = null;
    Hashtable<Integer, Integer> htPortMapIn = new Hashtable<Integer, Integer>();
    Hashtable<Integer, Integer> htPortMapOut = new Hashtable<Integer, Integer>();
    Class<? extends Block> blockClass = null;
    LicenseService licService = LicenseServiceFactory.getLicenseService();

    for (int b = 0; b < aXmlFlow.getXmlBlockCount(); b++) {
        XmlBlock block = aXmlFlow.getXmlBlock(b);
        String blockType = block.getType();

        try {
            licService.canInstantiateBlock(ui, blockType);
        } catch (LicenseServiceException e) {
            throw new ForbiddenBlockException(blockType);
        }

        // 10/01/2012 - P.Ussman - No longer used due to issue 578 solution  
        //       if (blockType.equals("BlockSubFlow")) {
        //         InstantiationResult subflowResult = this.instantiateSubFlow(ui,
        //             block, anFlowId, alSettings, htBlocks, offset);
        //         htPortMapIn.put(new Integer(block.getId()), new Integer(
        //             subflowResult.start.getId()));
        //         Iterator<Block> it = subflowResult.getEndIterator();
        //         while (it.hasNext()) {
        //           Block bEnd = it.next();
        //           htPortMapOut.put(new Integer(block.getId()), new Integer(
        //               bEnd.getId()));
        //         }

        //         continue;
        //       }

        Integer blockId = new Integer(block.getId() + offset);

        try {
            String stmp = BLOCK_PACKAGE + blockType;
            blockClass = loadBlockClass(ui, stmp);
        } catch (ClassNotFoundException cnfe) {
            throw new Exception("Erro ao criar bloco " + blockType, cnfe);
        }

        Logger.debug(null, this, "constructor", "Processing block " + blockClass.getName());
        Constructor<? extends Block> argsConstructor = blockClass.getConstructor(int.class, int.class,
                int.class, String.class);
        Block bBlock = argsConstructor.newInstance(anFlowId, blockId, block.getId(), aXmlFlow.getName());

        XmlPort xmlPort = null;
        try {
            // Ports
            for (int portNumber = 0; portNumber < block.getXmlPortCount(); portNumber++) {
                xmlPort = block.getXmlPort(portNumber);
                Logger.debug(null, this, "constructor", "Processing port " + xmlPort.getName());

                Port port = new Port();
                port.setName(xmlPort.getName());
                port.setConnectedBlockId(xmlPort.getConnectedBlockId() + offset);
                port.setConnectedPortName(xmlPort.getConnectedPortName());
                if (xmlPort.getName().equals("portEvent"))
                    bBlock.setHasEvent(true);

                Field fPort = blockClass.getField(xmlPort.getName());
                fPort.set(bBlock, port);
            }
        } catch (Exception e) {
            throw new Exception("Erro ao criar porto " + xmlPort.getName() + " para o bloco " + block.getType(),
                    e);
        }

        HashMap<String, String> hmtmp = new HashMap<String, String>();
        // Attributes
        for (int attrNumber = 0; attrNumber < block.getXmlAttributeCount(); attrNumber++) {
            XmlAttribute xmlAttribute = block.getXmlAttribute(attrNumber);

            String name = xmlAttribute.getName();
            String value = xmlAttribute.getValue();

            if (value == null)
                value = "";

            if (name.startsWith(IFlowData.sSETTING) || name.startsWith(IFlowData.sSETTING_DESC)) {
                hmtmp.put(name, value);
                continue;
            }

            try {
                Logger.debug(null, this, "constructor", "Processing attribute " + name + "=" + value);

                Attribute attribute = new Attribute();
                attribute.setName(name);
                attribute.setValue(value);
                bBlock.addAttribute(attribute);
            } catch (Exception e) {
                throw new Exception("Erro ao criar atributo " + name + " para o bloco " + blockType, e);
            }
        }

        HashSet<String> hsSettings = new HashSet<String>();
        Iterator<String> iter = hmtmp.keySet().iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next();
            if (!name.startsWith(IFlowData.sSETTING))
                continue;

            String stmp = name.substring(IFlowData.sSETTING.length());
            name = hmtmp.get(name);
            if (hsSettings.contains(name))
                continue;

            try {
                String value = hmtmp.get(IFlowData.sSETTING_DESC + stmp);
                Logger.debug(null, this, "constructor", "Processing setting " + name + " (" + value + ")");
                alSettings.add(new FlowSetting(anFlowId, name, value));
                hsSettings.add(name);
            } catch (Exception e) {
                throw new Exception("Erro ao criar propriedade " + name + " para o bloco " + blockType, e);
            }
        }

        //Updates PopUp flow conected block id
        bBlock.setBlockRunningInPopup(block.getPopupReturnBlockId());

        // refresh block's cache
        bBlock.refreshCache(ui);

        // Add the block to the vector
        this._vFlow.add(bBlock);

        // keeps a reference to Start Block to build ForkJoin dependency
        // path
        if (bBlock.isStartBlock()) {
            blockStart = bBlock;
        } else if (bBlock.isEndBlock()) {
            if (alBlockEnd == null)
                alBlockEnd = new ArrayList<Block>();
            alBlockEnd.add(bBlock);
        }

        htBlocks.put(blockId, bBlock);
    } // for

    Iterator<Integer> it = htPortMapIn.keySet().iterator();
    while (it.hasNext()) {
        Integer key = (Integer) it.next();
        Integer substId = (Integer) htPortMapIn.get(key);
        Block bBlock = (Block) htBlocks.get(substId); // blockIn

        Port[] inPorts = bBlock.getInPorts(ui);
        for (int ip = 0; inPorts != null && ip < inPorts.length; ip++) {
            if (inPorts[ip] == null)
                continue;
            Integer iConId = new Integer(inPorts[ip].getConnectedBlockId());
            Block btmp = (Block) htBlocks.get(iConId);

            Port[] outPorts = btmp.getOutPorts(ui);
            for (int op = 0; outPorts != null && op < outPorts.length; op++) {
                if (outPorts[op] == null)
                    continue;

                int iOutBlockId = outPorts[op].getConnectedBlockId();
                if (iOutBlockId == (key.intValue() + offset)) {
                    outPorts[op].setConnectedBlockId(substId.intValue());
                }
            }
        }
    }

    it = htPortMapOut.keySet().iterator();
    while (it.hasNext()) {
        Integer key = (Integer) it.next();
        Integer substId = (Integer) htPortMapOut.get(key);
        Block bBlock = (Block) htBlocks.get(substId); // blockOut

        Port[] outPorts = bBlock.getOutPorts(ui);
        for (int op = 0; outPorts != null && op < outPorts.length; op++) {
            if (outPorts[op] == null)
                continue;
            Integer iConId = new Integer(outPorts[op].getConnectedBlockId());
            Block btmp = (Block) htBlocks.get(iConId);

            Port[] inPorts = btmp.getInPorts(ui);
            for (int ip = 0; inPorts != null && ip < inPorts.length; ip++) {
                if (inPorts[ip] == null)
                    continue;

                int iInBlockId = inPorts[ip].getConnectedBlockId();
                if (iInBlockId == (key.intValue() + offset)) {
                    inPorts[ip].setConnectedBlockId(substId.intValue());
                }
            }
        }
    }

    // uncomment to check Port Mapping
    if (Const.CHECK_PORT_MAPPING) {

        // should return a warning if any bad block port exist

        Logger.debug("", this, "", "\n******* Checking Port Mapping *******\n");
        it = htBlocks.keySet().iterator();
        while (it.hasNext()) {
            Integer key = (Integer) it.next();
            Block bBlock = (Block) htBlocks.get(key);

            Logger.debug("", this, "", "\nBlockId: " + key + "  block: " + bBlock);
            if (bBlock == null)
                continue;

            Port[] ports = bBlock.getInPorts(ui);
            for (int i = 0; ports != null && i < ports.length; i++) {
                if (ports[i] == null)
                    Logger.debug("", this, "", "  null -> b");
                else
                    Logger.debug("", this, "", "  " + ports[i].getConnectedPortName() + ": "
                            + ports[i].getConnectedBlockId() + " -> b " + ports[i].getName());
            }
            ports = bBlock.getOutPorts(ui);
            for (int i = 0; ports != null && i < ports.length; i++) {
                if (ports[i] == null)
                    Logger.debug("", this, "", "  b -> null");
                else
                    Logger.debug("", this, "",
                            " " + ports[i].getName() + " b -> " + ports[i].getConnectedBlockId());
            }
        }
    }
    return new InstantiationResult(blockStart, alBlockEnd);
}

From source file:com.twinsoft.convertigo.beans.CheckBeans.java

private static void analyzeJavaClass(String javaClassName) {
    try {//from  w w  w  .  j  a v a2s.  c om
        Class<?> javaClass = Class.forName(javaClassName);
        String javaClassSimpleName = javaClass.getSimpleName();

        if (!DatabaseObject.class.isAssignableFrom(javaClass)) {
            //Error.NON_DATABASE_OBJECT.add(javaClassName);
            return;
        }

        nBeanClass++;

        String dboBeanInfoClassName = javaClassName + "BeanInfo";
        MySimpleBeanInfo dboBeanInfo = null;
        try {
            dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance();
        } catch (ClassNotFoundException e) {
            if (!Modifier.isAbstract(javaClass.getModifiers())) {
                Error.MISSING_BEAN_INFO
                        .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")");
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor();

        // Check abstract class
        if (Modifier.isAbstract(javaClass.getModifiers())) {
            // Check icon (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check icon (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check display name
            if (!beanDescriptor.getDisplayName().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (!beanDescriptor.getShortDescription().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName);
            }
        } else {
            nBeanClassNotAbstract++;

            // Check bean declaration in database_objects.xml
            if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) {
                Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName);
            }

            // Check icon name policy (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            String expectedIconName = javaClassName.replace(javaClassSimpleName,
                    "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (16x16)
            File iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check icon name policy (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (32x32)
            iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check display name
            if (beanDescriptor.getDisplayName().equals("?")) {
                Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (beanDescriptor.getShortDescription().equals("?")) {
                Error.BEAN_MISSING_DESCRIPTION.add(javaClassName);
            }
        }

        // Check declared bean properties
        PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            try {
                javaClass.getDeclaredField(propertyName);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    // Try to find it in the upper classes
                    javaClass.getField(propertyName);
                } catch (SecurityException e1) {
                    // printStackTrace();
                } catch (NoSuchFieldException e1) {
                    Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName);
                }
            }
        }

        Method[] methods = javaClass.getDeclaredMethods();
        List<Method> listMethods = Arrays.asList(methods);
        List<String> listMethodNames = new ArrayList<String>();
        for (Method method : listMethods) {
            listMethodNames.add(method.getName());
        }

        Field[] fields = javaClass.getDeclaredFields();

        for (Field field : fields) {
            int fieldModifiers = field.getModifiers();

            // Ignore static fields (constants)
            if (Modifier.isStatic(fieldModifiers))
                continue;

            String fieldName = field.getName();

            String errorMessage = javaClassName + ": " + field.getName();

            // Check bean info
            PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo);
            if (propertyDescriptor != null) {
                // Check bean property name policy
                if (!propertyDescriptor.getName().equals(fieldName)) {
                    Error.PROPERTY_NAMING_POLICY.add(errorMessage);
                }

                String declaredGetter = propertyDescriptor.getReadMethod().getName();
                String declaredSetter = propertyDescriptor.getWriteMethod().getName();

                String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                String expectedGetter = "get" + formattedFieldName;
                String expectedSetter = "set" + formattedFieldName;

                // Check getter name policy
                if (!declaredGetter.equals(expectedGetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared getter: " + declaredGetter + "\n"
                                    + "      Expected getter: " + expectedGetter);
                }

                // Check setter name policy
                if (!declaredSetter.equals(expectedSetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared setter: " + declaredSetter + "\n"
                                    + "      Expected setter: " + expectedSetter);
                }

                // Check required private modifiers for bean property
                if (!Modifier.isPrivate(fieldModifiers)) {
                    Error.PROPERTY_NOT_PRIVATE.add(errorMessage);
                }

                // Check getter
                if (!listMethodNames.contains(declaredGetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared getter not found: " + declaredGetter);
                }

                // Check setter
                if (!listMethodNames.contains(declaredSetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared setter not found: " + declaredGetter);
                }

                // Check non transient modifier
                if (Modifier.isTransient(fieldModifiers)) {
                    Error.PROPERTY_TRANSIENT.add(errorMessage);
                }
            } else if (!Modifier.isTransient(fieldModifiers)) {
                Error.FIELD_NOT_TRANSIENT.add(errorMessage);
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("ERROR on " + javaClassName);
        e.printStackTrace();
    }
}

From source file:org.openTwoFactor.server.util.TwoFactorServerUtilsElSafe.java

/**
 * <p>Checks whether this <code>Throwable</code> class can store a cause.</p>
 * /*  w w w. ja  v a  2 s  .c  o m*/
 * <p>This method does <b>not</b> check whether it actually does store a cause.<p>
 *
 * @param throwable  the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0
 */
@SuppressWarnings("unchecked")
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    if (throwable instanceof Nestable) {
        return true;
    } else if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class cls = throwable.getClass();
    for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
        try {
            Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], (Class[]) null);
            if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                return true;
            }
        } catch (NoSuchMethodException ignored) {
        } catch (SecurityException ignored) {
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
    } catch (SecurityException ignored) {
    }

    return false;
}