Example usage for java.lang.reflect Method getDeclaringClass

List of usage examples for java.lang.reflect Method getDeclaringClass

Introduction

In this page you can find the example usage for java.lang.reflect Method getDeclaringClass.

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Make an OperationDesc from a Java method.
 *
 * In the absence of deployment metadata, this code will introspect a
 * Method and create an appropriate OperationDesc.  If the class
 * implements the Skeleton interface, we will use the metadata from there
 * in constructing the OperationDesc.  If not, we use parameter names
 * from the bytecode debugging info if available, or "in0", "in1", etc.
 * if not./*ww  w  .j av  a  2 s.  c  o m*/
 */
private void createOperationForMethod(Method method) {
    // If we've already got it, never mind
    if (method2OperationMap.get(method) != null) {
        return;
    }

    Class[] paramTypes = method.getParameterTypes();

    // And if we've already got an exact match (i.e. an override),
    // never mind

    ArrayList overloads = name2OperationsMap == null ? null
            : (ArrayList) name2OperationsMap.get(method.getName());
    if (overloads != null && !overloads.isEmpty()) {
        // Search each OperationDesc that already has a Method
        // associated with it, and check for parameter type equivalence.
        for (int i = 0; i < overloads.size(); i++) {
            OperationDesc op = (OperationDesc) overloads.get(i);
            Method checkMethod = op.getMethod();
            if (checkMethod != null) {
                Class[] others = checkMethod.getParameterTypes();
                if (paramTypes.length == others.length) {
                    int j = 0;
                    for (; j < others.length; j++) {
                        if (!others[j].equals(paramTypes[j]))
                            break;
                    }
                    // If we got all the way through, we have a match.
                    if (j == others.length)
                        return;
                }
            }
        }
    }

    boolean isWSICompliant = JavaUtils.isTrue(AxisProperties.getProperty(Constants.WSIBP11_COMPAT_PROPERTY));

    // Make an OperationDesc, fill in common stuff
    OperationDesc operation = new OperationDesc();

    // If we're WS-I compliant, we can't have overloaded operation names.
    // If we find duplicates, we generate unique names for them and map
    // those names to the correct Method.
    String name = method.getName();
    if (isWSICompliant && name2OperationsMap != null) {
        Collection methodNames = name2OperationsMap.keySet();
        name = JavaUtils.getUniqueValue(methodNames, name);
    }
    operation.setName(name);
    String defaultNS = "";
    if (namespaceMappings != null && !namespaceMappings.isEmpty()) {
        // If we have a default namespace mapping, require callers to
        // use that namespace.
        defaultNS = (String) namespaceMappings.get(0);
    }
    if (defaultNS.length() == 0) {
        defaultNS = Namespaces.makeNamespace(method.getDeclaringClass().getName());
    }
    operation.setElementQName(new QName(defaultNS, name));
    operation.setMethod(method);

    // If this is a MESSAGE style service, set up the OperationDesc
    // appropriately.
    if (style == Style.MESSAGE) {
        int messageOperType = checkMessageMethod(method);
        if (messageOperType == OperationDesc.MSG_METHOD_NONCONFORMING)
            return;
        if (messageOperType == -1) {
            throw new InternalException(
                    "Couldn't match method to any of the allowable message-style patterns!");
        }
        operation.setMessageOperationStyle(messageOperType);
        operation.setReturnClass(Object.class);
        operation.setReturnType(Constants.XSD_ANYTYPE);
    } else {
        // For other styles, continue here.
        Class retClass = method.getReturnType();
        operation.setReturnClass(retClass);
        QName typeQName = getTypeQName(retClass);
        operation.setReturnType(typeQName);

        String[] paramNames = getParamNames(method);

        for (int k = 0; k < paramTypes.length; k++) {
            Class type = paramTypes[k];
            ParameterDesc paramDesc = new ParameterDesc();
            // param should be unqualified if we're using rpc style,
            // or should use the operation's namespace if its document style
            String paramNamespace = (this.style == Style.RPC ? ""
                    : operation.getElementQName().getNamespaceURI());

            // If we have a name for this param, use it, otherwise call
            // it "in*"
            if (paramNames != null && paramNames[k] != null && paramNames[k].length() > 0) {
                paramDesc.setQName(new QName(paramNamespace, paramNames[k]));
            } else {
                paramDesc.setQName(new QName(paramNamespace, "in" + k));
            }

            // If it's a Holder, mark it INOUT, and set the XML type QName
            // to the held type.  Otherwise it's IN.

            Class heldClass = JavaUtils.getHolderValueType(type);
            if (heldClass != null) {
                paramDesc.setMode(ParameterDesc.INOUT);
                paramDesc.setTypeQName(getTypeQName(heldClass));
            } else {
                paramDesc.setMode(ParameterDesc.IN);
                paramDesc.setTypeQName(getTypeQName(type));
            }
            paramDesc.setJavaType(type);
            operation.addParameter(paramDesc);
        }
    }

    createFaultMetadata(method, operation);

    addOperationDesc(operation);
    method2OperationMap.put(method, operation);
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/** This just catches and wraps IllegalArgumentException. */
private Object invokeMethod(final Method method, final Object bean, final Object[] values)
        throws IllegalAccessException, InvocationTargetException {

    if (bean == null) {
        throw new IllegalArgumentException(
                "No bean specified " + "- this should have been checked before reaching this method");
    }/*from   w w w .j ava  2  s .  c  om*/

    try {

        return method.invoke(bean, values);

    } catch (final NullPointerException cause) {
        // JDK 1.3 and JDK 1.4 throw NullPointerException if an argument is
        // null for a primitive value (JDK 1.5+ throw
        // IllegalArgumentException)
        String valueString = "";
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    valueString += ", ";
                }
                if (values[i] == null) {
                    valueString += "<null>";
                } else {
                    valueString += values[i].getClass().getName();
                }
            }
        }
        String expectedString = "";
        final Class<?>[] parTypes = method.getParameterTypes();
        if (parTypes != null) {
            for (int i = 0; i < parTypes.length; i++) {
                if (i > 0) {
                    expectedString += ", ";
                }
                expectedString += parTypes[i].getName();
            }
        }
        final IllegalArgumentException e = new IllegalArgumentException(
                "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName()
                        + " on bean class '" + bean.getClass() + "' - " + cause.getMessage()
                        // as per
                        // https://issues.apache.org/jira/browse/BEANUTILS-224
                        + " - had objects of type \"" + valueString + "\" but expected signature \""
                        + expectedString + "\"");
        if (!initCause(e, cause)) {
            log.error("Method invocation failed", cause);
        }
        throw e;
    } catch (final IllegalArgumentException cause) {
        String valueString = "";
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    valueString += ", ";
                }
                if (values[i] == null) {
                    valueString += "<null>";
                } else {
                    valueString += values[i].getClass().getName();
                }
            }
        }
        String expectedString = "";
        final Class<?>[] parTypes = method.getParameterTypes();
        if (parTypes != null) {
            for (int i = 0; i < parTypes.length; i++) {
                if (i > 0) {
                    expectedString += ", ";
                }
                expectedString += parTypes[i].getName();
            }
        }
        final IllegalArgumentException e = new IllegalArgumentException(
                "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName()
                        + " on bean class '" + bean.getClass() + "' - " + cause.getMessage()
                        // as per
                        // https://issues.apache.org/jira/browse/BEANUTILS-224
                        + " - had objects of type \"" + valueString + "\" but expected signature \""
                        + expectedString + "\"");
        if (!initCause(e, cause)) {
            log.error("Method invocation failed", cause);
        }
        throw e;

    }
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

private XmlDataModelSchema(final Class bean) {
    propertyNames = new HashMap();
    attributeTypes = new HashMap();
    attributeSetters = new HashMap();
    attributeSetterMethods = new HashMap();
    attributeAccessors = new HashMap();
    flagsAttributeAccessors = new HashMap();
    nestedTypes = new HashMap();
    nestedCreators = new HashMap();
    nestedAltClassNameCreators = new HashMap();
    nestedAdders = new HashMap();
    nestedStorers = new HashMap();

    this.bean = bean;

    Options customOptions = (Options) getStaticFieldValue(bean, XMLDATAMODEL_SCHEMA_OPTIONS_FIELD_NAME);
    options = customOptions != null ? customOptions : new Options();

    Method[] methods = bean.getMethods();
    for (int i = 0; i < methods.length; i++) {
        final Method m = methods[i];
        final String name = m.getName();
        Class returnType = m.getReturnType();
        Class[] args = m.getParameterTypes();

        if (name.equals(options.pcDataHandlerMethodName) && java.lang.Void.TYPE.equals(returnType)
                && args.length == 1 && java.lang.String.class.equals(args[0])) {
            addText = methods[i];/*from   w  w  w . j a va2s . com*/
        } else if (name.startsWith("get") && args.length == 0) {
            String[] propNames = getPropertyNames(name, "get");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                AttributeAccessor aa = createAttributeAccessor(m, propNames[pn], returnType);
                if (aa != null)
                    attributeAccessors.put(propNames[pn], aa);
            }
        } else if (name.startsWith("is") && args.length == 0) {
            String[] propNames = getPropertyNames(name, "is");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                AttributeAccessor aa = createAttributeAccessor(m, propNames[pn], returnType);
                if (aa != null)
                    attributeAccessors.put(propNames[pn], aa);
            }
        } else if (name.startsWith("set") && java.lang.Void.TYPE.equals(returnType) && args.length == 1
                && (!args[0].isArray() || java.lang.String[].class.equals(args[0]))) {
            String[] propNames = getPropertyNames(name, "set");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                attributeSetterMethods.put(propNames[pn], m);
                AttributeSetter as = createAttributeSetter(m, propNames[pn], args[0]);
                if (as != null) {
                    attributeTypes.put(propNames[pn], args[0]);
                    attributeSetters.put(propNames[pn], as);
                }
            }
        } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive()
                && (args.length == 0)) {
            // prevent infinite recursion for nested recursive elements
            if (!returnType.getClass().equals(bean.getClass()))
                getSchema(returnType);
            String[] propNames = getPropertyNames(name, "create");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedTypes.put(propNames[pn], returnType);
                nestedCreators.put(propNames[pn], new NestedCreator() {
                    public Object create(Object parent)
                            throws InvocationTargetException, IllegalAccessException {
                        return m.invoke(parent, new Object[] {});
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive()
                && (args.length == 1 && args[0] == Class.class)) {
            // prevent infinite recursion for nested recursive elements
            if (!returnType.getClass().equals(bean.getClass()))
                getSchema(returnType);
            String[] propNames = getPropertyNames(name, "create");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedTypes.put(propNames[pn], returnType);
                nestedAltClassNameCreators.put(propNames[pn], new NestedAltClassCreator() {
                    public Object create(Object parent, Class cls)
                            throws InvocationTargetException, IllegalAccessException {
                        return m.invoke(parent, new Object[] { cls });
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        } else if (name.startsWith("add") && java.lang.Void.TYPE.equals(returnType) && args.length == 1
                && !java.lang.String.class.equals(args[0]) && !args[0].isArray() && !args[0].isPrimitive()) {
            String[] propNames = getPropertyNames(name, "add");
            try {
                final Constructor c = args[0].getConstructor(new Class[] {});
                for (int pn = 0; pn < propNames.length; pn++) {
                    if (propNames[pn].length() == 0)
                        continue;

                    if (!nestedCreators.containsKey(propNames[pn])) {
                        nestedTypes.put(propNames[pn], args[0]);
                        nestedCreators.put(propNames[pn], new NestedCreator() {
                            public boolean allowAlternateClass() {
                                return false;
                            }

                            public Object create(Object parent) throws InvocationTargetException,
                                    IllegalAccessException, InstantiationException {
                                return c.newInstance(new Object[] {});
                            }

                            public Object create(Object parent, Class cls) throws InvocationTargetException,
                                    IllegalAccessException, InstantiationException {
                                return c.newInstance(new Object[] { cls });
                            }

                            public boolean isInherited() {
                                return !m.getDeclaringClass().equals(bean);
                            }

                            public Class getDeclaringClass() {
                                return m.getDeclaringClass();
                            }
                        });
                    }
                }
            } catch (NoSuchMethodException nse) {
                //log.warn("Unable to create nestedCreator for " + name + " " + args[0] + ", registering type only without a creator.", nse);
                for (int pn = 0; pn < propNames.length; pn++) {
                    if (propNames[pn].length() > 0)
                        nestedTypes.put(propNames[pn], args[0]);
                }
            }

            // prevent infinite recursion for nested recursive elements
            if (!args[0].getClass().equals(bean.getClass()))
                getSchema(args[0]);
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedStorers.put(propNames[pn], new NestedStorer() {
                    public void store(Object parent, Object child)
                            throws InvocationTargetException, IllegalAccessException {
                        m.invoke(parent, new Object[] { child });
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        }
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.UploadTable.java

/**
 * @param row//from w  w  w .  j ava2 s. c om
 * @param recNum
 * @return
 * @throws UploaderException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws ParseException
 * @throws NoSuchMethodException
 */
protected List<ParentMatchInfo> getMatchInfoInternal(int row, int recNum, Set<Integer> invalidColNums,
        List<Pair<UploadTable, List<DataModelObjBase>>> matchChildrenParents)
        throws UploaderException, InvocationTargetException, IllegalAccessException, ParseException,
        NoSuchMethodException, InstantiationException, SQLException {
    //XXX still need to follow matchChildren links
    //XXX when doing children need to do all recnums - collector1 2 3 ...
    //XXX need to skip tables with invalid columns
    //XXX what about ...Attribute tables? Do they need special treatment?
    //XXX if CE is embedded? 

    int adjustedRecNum = uploadFields.size() == 1 ? 0 : recNum;
    //XXX assuming that an upload is NOT in progress!!
    wbCurrentRow = row;

    List<ParentMatchInfo> result = new Vector<ParentMatchInfo>();
    Vector<List<ParentMatchInfo>> parentMatches = new Vector<List<ParentMatchInfo>>();
    Vector<List<ParentMatchInfo>> childMatches = new Vector<List<ParentMatchInfo>>();
    List<UploadTable> childTables = new ArrayList<UploadTable>(specialChildren);

    if (this instanceof UploadTableTree && parentTables.size() == 0) {
        DataModelObjBase p = getParentRecord(recNum, this /*only the type of the 2nd param is relevant*/);
        List<DataModelObjBase> m = new ArrayList<DataModelObjBase>();
        m.add(p);
        List<ParentMatchInfo> pm = new ArrayList<ParentMatchInfo>();
        pm.add(new ParentMatchInfo(m, this, isBlankRow(row, uploader.getUploadData(), adjustedRecNum), false,
                recNum, false));
        parentMatches.add(pm);
    } else {
        for (Vector<ParentTableEntry> ptes : parentTables) {
            for (ParentTableEntry pte : ptes) {
                if (!pte.getImportTable().specialChildren.contains(this)
                        || !pte.getImportTable().needToMatchChild(tblClass)) {
                    if (pte.getImportTable().isOneToOneChild()) {
                        if (childTables.indexOf(pte.getImportTable()) == -1) {
                            childTables.add(pte.getImportTable());
                        }
                    } else {
                        parentMatches.add(pte.getImportTable().getMatchInfoInternal(row, adjustedRecNum,
                                invalidColNums, null));
                    }
                }
            }
        }
    }
    HashMap<UploadTable, DataModelObjBase> parentParams = new HashMap<UploadTable, DataModelObjBase>();
    boolean doMatch = true;
    boolean matched = false;
    boolean blankParentage = true;
    boolean blank = isBlankRow(row, uploader.getUploadData(), adjustedRecNum);
    boolean stopAlready = false;
    ArrayList<DataModelObjBase> matches = new ArrayList<DataModelObjBase>();
    ArrayList<DataModelObjBase> myMatches = new ArrayList<DataModelObjBase>();
    //XXX need to include matchChildrenParents in parentParams 
    ParentMatchInfo nearest = null;
    for (List<ParentMatchInfo> pm : parentMatches) {
        if (doMatch && pm.size() > 0) {
            nearest = pm.get(pm.size() - 1);
            int b = 2;
            while (pm.size() - b >= 0 && nearest.isSkipped() && !nearest.getStoppedAlready()) {
                nearest = pm.get(pm.size() - b++);
            }
            blankParentage &= nearest != null & nearest.isBlank();
            if (nearest.getMatches().size() == 1 || (!nearest.getStoppedAlready()
                    && nearest.getMatches().size() == 0 && (nearest.isBlank() || nearest.isSkipped()))) {
                DataModelObjBase match = nearest.getMatches().size() == 1 ? nearest.getMatches().get(0) : null;
                stopAlready = this instanceof UploadTableTree && nearest.getMatches().size() == 0
                        && (nearest.isBlank() || nearest.isSkipped());
                parentParams.put(nearest.getTable(), match);
            } else {
                doMatch = false;
                stopAlready = nearest.getStoppedAlready();
            }
        }
        result.addAll(pm);
    }
    if (doMatch && (!blank || !blankParentage)) {
        for (Vector<UploadField> ufs : uploadFields) {
            for (UploadField uf : ufs) {
                if (uf.getIndex() != -1) {
                    uf.setValue(uploader.getUploadData().get(row, uf.getIndex()));
                }
            }
        }
        //if (!this.getTblClass().equals(CollectingEvent.class)) {
        skipChildrenMatching.set(true);
        //}
        try {
            if (matchChildrenParents == null || matchChildrenParents.size() == 0) {
                if (!blank) {
                    findMatch(adjustedRecNum, false, myMatches, parentParams);
                } else if (nearest != null) {
                    myMatches.add(parentParams.get(nearest.getTable()));
                }
            } else {
                //XXX assuming matchChildrenParents is only being used for ...Attribute tables and will only have one item
                Pair<UploadTable, List<DataModelObjBase>> mp = matchChildrenParents.get(0);
                for (DataModelObjBase p : mp.getSecond()) {
                    parentParams.put(mp.getFirst(), p);
                    findMatch(adjustedRecNum, false, myMatches, parentParams);
                    parentParams.remove(mp.getFirst());
                }
            }
            matched = true;
        } finally {
            //if (!this.getTblClass().equals(CollectingEvent.class)) {
            skipChildrenMatching.set(false);
            //}
        }

    }

    //XXX add this table to matchChildrenParents
    //taking advantage of this mysterious structure to deal with ...Attribute tbls.
    if (matchChildrenParents == null) {
        matchChildrenParents = new ArrayList<Pair<UploadTable, List<DataModelObjBase>>>();
    }
    for (UploadTable ut : childTables) {
        for (int rc = 0; rc < ut.getUploadFields().size(); rc++) {
            if (!this.tblClass.equals(CollectionObject.class)) {
                matchChildrenParents.add(new Pair<UploadTable, List<DataModelObjBase>>(this, myMatches));
            }
            childMatches.add(ut.getMatchInfoInternal(row, rc, invalidColNums, matchChildrenParents));
            if (!this.tblClass.equals(CollectionObject.class)) {
                matchChildrenParents.remove(matchChildrenParents.size() - 1);
            }
        }
    }
    //XXX what the hell to do with childMatches??? Need to add them to result to get Agent, taxon matches, but how to 
    //Use them in findMatch?? Does findMatch need to be done first?? WTF?
    // XXX what the hell happens for matchchildren in findMatch??
    //OK. Current plan is to match children in a way similar to the above - create a parentParam for this object and pass
    //it to findMatch for the children...
    // XXX this is not the final word on matchchildren matches

    //XXX the new way of handling child matches...
    if (!this.tblClass.equals(CollectionObject.class) && childMatches.size() > 0) {
        List<DataModelObjBase> keeperMatches = new ArrayList<DataModelObjBase>(myMatches);
        for (DataModelObjBase mine : myMatches) {
            boolean go = true;
            for (List<ParentMatchInfo> cm : childMatches) {
                for (ParentMatchInfo pmi : cm) {
                    try {
                        ParentTableEntry pte = findParentTableEntry(pmi.getTable());
                        if (pte != null) {
                            //System.out.println(pte.getImportTable());
                            Method getter = pte.getGetter();
                            boolean invokeMe = getter.getDeclaringClass().equals(this.getTblClass());
                            if (pmi.getMatches().size() == 0) {
                                if (invokeMe) {
                                    go = pmi.isBlank() ? getter.invoke(mine) == null : false;
                                } else {
                                    //System.out.println("one-to-many count check");
                                    String sql = "select count(*) from "
                                            + pmi.getTable().getTable().getTableInfo().getName() + " where "
                                            + this.getTable().getTableInfo().getPrimaryKeyName() + " = "
                                            + mine.getId();
                                    go = pmi.isBlank() ? BasicSQLUtils.getCount(sql) == 0 : false;
                                }
                            } else {
                                for (DataModelObjBase theirs : pmi.getMatches()) {
                                    DataModelObjBase objA = (DataModelObjBase) (invokeMe ? getter.invoke(mine)
                                            : getter.invoke(theirs));
                                    DataModelObjBase objB = invokeMe ? theirs : mine;
                                    if (objA != null && objB != null && objA.getId().equals(objB.getId())) {
                                        //System.out.println("  match (" + invokeMe +")");
                                        //all is well
                                    } else {
                                        //System.out.println("  no match (" + invokeMe + ")");
                                        go = false;
                                        break;
                                    }
                                }
                            }
                        } else {
                            //System.out.println("no pte; wtf");
                            //whatever
                        }
                        if (!go) {
                            //childMatchesForLosers.add(cm);
                            break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (!go) {
                    keeperMatches.remove(mine);
                    break;
                }
            }
        }

        //remove incomplete matches
        for (int m = myMatches.size() - 1; m >= 0; m--) {
            if (keeperMatches.indexOf(myMatches.get(m)) == -1) {
                myMatches.remove(m);
            }
        }

        //if no matches, we know all children are also unmatched
        //technically should only clear/remove matches stemming from matches removed above, but... too much work for too little benefit
        if (myMatches.size() == 0) {
            for (List<ParentMatchInfo> cmis : childMatches) {
                for (ParentMatchInfo cmi : cmis) {
                    UploadTable cmit = cmi.getTable();
                    if (cmit.isMatchChild() || cmit.isOneToOneChild() || cmit.isZeroToOneMany()
                            || specialChildren.indexOf(cmit) >= 0) {
                        cmi.getMatches().clear();
                    }
                }
            }
        }

    }

    matches.addAll(myMatches);

    //I think this loop eliminates chains of no-match indications??
    boolean invalid = containsInvalidCol(adjustedRecNum, invalidColNums);
    for (List<ParentMatchInfo> cm : childMatches) {
        if (!invalid && matched) {
            result.addAll(cm);
        } else {
            for (int i = cm.size() - 1; i > -1; i--) {
                ParentMatchInfo mi = cm.get(i);
                if (mi.getTable().isOneToOneChild()) {
                    if (invalid) {
                        cm.remove(i);
                    } else if (!matched) {
                        mi.setIsSkipped(true);
                    }
                }
            }
            result.addAll(cm);
        }
    }

    if (!containsInvalidCol(adjustedRecNum, invalidColNums)) {
        //          if (!matched)
        //          {
        //             for (List<ParentMatchInfo> cm : childMatches)
        //             {
        //                for (ParentMatchInfo mi : cm)
        //                {
        //                   if (mi.getTable().isOneToOneChild())
        //                   {
        //                      mi.setIsSkipped(true);
        //                   }
        //                }
        //             }
        //          }
        result.add(new ParentMatchInfo(matches, this, blank && blankParentage, !matched, recNum, stopAlready));
    }

    return result;
}

From source file:com.meidusa.venus.client.RemotingInvocationHandler.java

protected Object invokeRemoteService(Service service, Endpoint endpoint, Method method,
        EndpointParameter[] params, Object[] args) throws Exception {
    String apiName = VenusAnnotationUtils.getApiname(method, service, endpoint);

    AthenaTransactionId athenaTransactionId = null;
    if (service.athenaFlag()) {
        athenaTransactionId = AthenaTransactionDelegate.getDelegate().startClientTransaction(apiName);
    }/*from   w  w w. j  a v a  2s  .co m*/
    boolean async = false;

    if (endpoint.async()) {
        async = true;
    }

    byte[] traceID = VenusTracerUtil.getTracerID();

    if (traceID == null) {
        traceID = VenusTracerUtil.randomTracerID();
    }

    Serializer serializer = SerializerFactory.getSerializer(serializeType);

    SerializeServiceRequestPacket serviceRequestPacket = new SerializeServiceRequestPacket(serializer, null);

    serviceRequestPacket.clientId = PacketConstant.VENUS_CLIENT_ID;
    serviceRequestPacket.clientRequestId = sequenceId.getAndIncrement();
    serviceRequestPacket.traceId = traceID;
    serviceRequestPacket.apiName = apiName;
    serviceRequestPacket.serviceVersion = service.version();
    serviceRequestPacket.parameterMap = new HashMap<String, Object>();

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (args[i] instanceof InvocationListener) {
                async = true;
                ReferenceInvocationListener listener = new ReferenceInvocationListener();
                ServicePacketBuffer buffer = new ServicePacketBuffer(16);
                buffer.writeLengthCodedString(args[i].getClass().getName(), "utf-8");
                buffer.writeInt(System.identityHashCode(args[i]));
                listener.setIdentityData(buffer.toByteBuffer().array());
                Type type = method.getGenericParameterTypes()[i];
                if (type instanceof ParameterizedType) {
                    ParameterizedType genericType = ((ParameterizedType) type);
                    container.putInvocationListener((InvocationListener) args[i],
                            genericType.getActualTypeArguments()[0]);
                } else {
                    throw new InvalidParameterException("invocationListener is not generic");
                }

                serviceRequestPacket.parameterMap.put(params[i].getParamName(), listener);
            } else {
                serviceRequestPacket.parameterMap.put(params[i].getParamName(), args[i]);
            }

        }
    }
    setTransactionId(serviceRequestPacket, athenaTransactionId);

    PerformanceLevel pLevel = AnnotationUtil.getAnnotation(method.getAnnotations(), PerformanceLevel.class);
    long start = TimeUtil.currentTimeMillis();
    long borrowed = start;

    if (async) {
        if (!this.isEnableAsync()) {
            throw new VenusConfigException("service async call disabled");
        }

        BackendConnection conn = null;
        try {

            if (nioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (BackendConnection) ((RequestLoadbalanceObjectPool) nioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = nioConnPool.borrowObject();
            }
            borrowed = TimeUtil.currentTimeMillis();

            conn.write(serviceRequestPacket.toByteBuffer());
            VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                    JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
            return null;
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            if (performanceLogger.isDebugEnabled()) {
                long end = TimeUtil.currentTimeMillis();
                long time = end - borrowed;
                StringBuffer buffer = new StringBuffer();
                buffer.append("[").append(borrowed - start).append(",").append(time)
                        .append("]ms (*client,async*) traceID=").append(UUID.toString(traceID)).append(", api=")
                        .append(serviceRequestPacket.apiName);

                performanceLogger.debug(buffer.toString());
            }

            if (conn != null) {
                nioConnPool.returnObject(conn);
            }
        }
    } else {
        AbstractBIOConnection conn = null;
        int soTimeout = 0;
        int oldTimeout = 0;
        boolean success = true;
        int errorCode = 0;
        AbstractServicePacket packet = null;
        String remoteAddress = null;
        boolean invalided = false;
        try {
            if (bioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (AbstractBIOConnection) ((RequestLoadbalanceObjectPool) bioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = (AbstractBIOConnection) bioConnPool.borrowObject();
            }
            remoteAddress = conn.getRemoteAddress();
            borrowed = TimeUtil.currentTimeMillis();
            ServiceConfig config = this.serviceFactory.getServiceConfig(method.getDeclaringClass());

            oldTimeout = conn.getSoTimeout();
            if (config != null) {
                EndpointConfig endpointConfig = config.getEndpointConfig(endpoint.name());
                if (endpointConfig != null) {
                    int eTimeOut = endpointConfig.getTimeWait();
                    if (eTimeOut > 0) {
                        soTimeout = eTimeOut;
                    }
                } else {
                    if (config.getTimeWait() > 0) {
                        soTimeout = config.getTimeWait();
                    } else {
                        if (endpoint.timeWait() > 0) {
                            soTimeout = endpoint.timeWait();
                        }
                    }
                }

            } else {

                if (endpoint.timeWait() > 0) {
                    soTimeout = endpoint.timeWait();
                }
            }

            byte[] bts;

            try {

                if (soTimeout > 0) {
                    conn.setSoTimeout(soTimeout);
                }
                conn.write(serviceRequestPacket.toByteArray());
                VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                        JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                bts = conn.read();
            } catch (IOException e) {
                try {
                    conn.close();
                } catch (Exception e1) {
                    // ignore
                }

                bioConnPool.invalidateObject(conn);
                invalided = true;
                Class<?>[] eClass = method.getExceptionTypes();

                if (eClass != null && eClass.length > 0) {
                    for (Class<?> clazz : eClass) {
                        if (e.getClass().isAssignableFrom(clazz)) {
                            throw e;
                        }
                    }
                }

                throw new RemoteSocketIOException("api=" + serviceRequestPacket.apiName + ", remoteIp="
                        + conn.getRemoteAddress() + ",(" + e.getMessage() + ")", e);
            }

            int type = AbstractServicePacket.getType(bts);
            switch (type) {
            case PacketConstant.PACKET_TYPE_ERROR:
                ErrorPacket error = new ErrorPacket();
                error.init(bts);
                packet = error;
                Exception e = venusExceptionFactory.getException(error.errorCode, error.message);
                if (e == null) {
                    throw new DefaultVenusException(error.errorCode, error.message);
                } else {
                    if (error.additionalData != null) {
                        Map<String, Type> tmap = Utils.getBeanFieldType(e.getClass(), Exception.class);
                        if (tmap != null && tmap.size() > 0) {
                            Object obj = serializer.decode(error.additionalData, tmap);
                            BeanUtils.copyProperties(e, obj);
                        }
                    }
                    throw e;
                }
            case PacketConstant.PACKET_TYPE_OK:
                OKPacket ok = new OKPacket();
                ok.init(bts);
                packet = ok;
                return null;
            case PacketConstant.PACKET_TYPE_SERVICE_RESPONSE:
                ServiceResponsePacket response = new SerializeServiceResponsePacket(serializer,
                        method.getGenericReturnType());
                response.init(bts);
                packet = response;
                return response.result;
            default: {
                logger.warn("unknow response type=" + type);
                success = false;
                return null;
            }
            }
        } catch (Exception e) {
            success = false;

            if (e instanceof CodedException
                    || (errorCode = venusExceptionFactory.getErrorCode(e.getClass())) != 0
                    || e instanceof RuntimeException) {
                if (e instanceof CodedException) {
                    errorCode = ((CodedException) e).getErrorCode();
                }
                throw e;
            } else {
                RemoteException code = e.getClass().getAnnotation(RemoteException.class);
                if (code != null) {
                    errorCode = code.errorCode();
                    throw e;
                } else {
                    ExceptionCode eCode = e.getClass().getAnnotation(ExceptionCode.class);
                    if (eCode != null) {
                        errorCode = eCode.errorCode();
                        throw e;
                    } else {
                        errorCode = -1;
                        if (conn == null) {
                            throw new DefaultVenusException(e.getMessage(), e);
                        } else {
                            throw new DefaultVenusException(
                                    e.getMessage() + ". remoteAddress=" + conn.getRemoteAddress(), e);
                        }
                    }
                }
            }
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            long end = TimeUtil.currentTimeMillis();
            long time = end - borrowed;
            StringBuffer buffer = new StringBuffer();
            buffer.append("[").append(borrowed - start).append(",").append(time)
                    .append("]ms (*client,sync*) traceID=").append(UUID.toString(traceID)).append(", api=")
                    .append(serviceRequestPacket.apiName);
            if (remoteAddress != null) {
                buffer.append(", remote=").append(remoteAddress);
            } else {
                buffer.append(", pool=").append(bioConnPool.toString());
            }
            buffer.append(", clientID=").append(PacketConstant.VENUS_CLIENT_ID).append(", requestID=")
                    .append(serviceRequestPacket.clientRequestId);

            if (packet != null) {
                if (packet instanceof ErrorPacket) {
                    buffer.append(", errorCode=").append(((ErrorPacket) packet).errorCode);
                    buffer.append(", message=").append(((ErrorPacket) packet).message);
                } else {
                    buffer.append(", errorCode=0");
                }
            }

            if (pLevel != null) {

                if (pLevel.printParams()) {
                    buffer.append(", params=");
                    buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                }

                if (time > pLevel.error() && pLevel.error() > 0) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time > pLevel.warn() && pLevel.warn() > 0) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time > pLevel.info() && pLevel.info() > 0) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            } else {
                buffer.append(", params=");
                buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));

                if (time >= 30 * 1000) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time >= 10 * 1000) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time >= 5 * 1000) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            }

            if (conn != null && !invalided) {
                if (!conn.isClosed() && soTimeout > 0) {
                    conn.setSoTimeout(oldTimeout);
                }
                bioConnPool.returnObject(conn);
            }

        }
    }
}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

/**
 * @param itemLabels//  w  w  w.  j  a  v a2 s  .c o m
 * @param tblInfo
 */
private void buildFieldInfoList(Vector<FVOFieldInfo> itemLabels, final DBTableInfo tblInfo) {
    // This next section loops through all the UI components in the form that has an ID
    // It checks to make sure that it is a candidate for CF
    Vector<String> ids = new Vector<String>();
    getFieldIds(ids, true); // true means return all the UI components with ids not just the fields
    for (String id : ids) {
        FVOFieldInfo fieldInfo = getFieldInfoForId(id);
        String fieldName = fieldInfo.getFormCell().getName();
        DBFieldInfo fi = tblInfo != null ? tblInfo.getFieldByName(fieldName) : null;

        fieldInfo.setFieldInfo(fi);

        log.debug("-------------------------------");
        log.debug(fieldName);

        // Start by assuming it is OK to be added
        boolean isOK = true;
        if (fieldInfo.getFormCell() instanceof FormCellFieldIFace) {
            // Only the ones that are editable.
            FormCellFieldIFace fcf = (FormCellFieldIFace) fieldInfo.getFormCell();
            if (fcf.isReadOnly()) {
                isOK = false;
            } else {
                DBInfoBase infoBase = fieldInfo.getFieldInfo();
                if (infoBase instanceof DBFieldInfo) {
                    if (fi.isUnique() || !fi.isUpdatable()) {
                        isOK = false;

                    } else if (fi.getFormatter() != null && fi.getFormatter().isIncrementer()) {
                        isOK = false;
                    }
                } else {
                    log.debug("Skipping " + infoBase);
                }
            }
        } else {
            log.debug("Skipping " + fieldInfo.getFormCell());
        }

        // At this point we have weeded out any readonly/autoinc "fields" and we need to get a label for the field
        // And weed out any SubViews.
        if (isOK) {
            // Check to see if the field has a label
            String label = null;
            FVOFieldInfo labelInfo = getLabelInfoFor(id);
            if (labelInfo != null) {
                if (!(fieldInfo.getFormCell() instanceof FormCellLabel)) {
                    label = ((FormCellLabel) labelInfo.getFormCell()).getLabel();
                }
            }

            //log.debug("Field ["+fieldName+"] in ["+(ti != null ? ti.getTitle() : "N/A")+"]");

            // Now we go get the DBFieldInfo and DBRelationshipInfo and check to make
            // that the field or Relationship is still a candidate for CF
            DBInfoBase infoBase = null;
            if (tblInfo != null) {
                if (fi != null) {
                    infoBase = fi;

                    // Skip any fields that are AutoNumbered
                    if (fieldInfo.getComp() instanceof AutoNumberableIFace) {
                        isOK = !((AutoNumberableIFace) fieldInfo.getComp()).isFormatterAutoNumber();
                    } else {
                        isOK = true;
                    }

                } else {
                    DBRelationshipInfo ri = tblInfo.getRelationshipByName(fieldName);
                    if (ri != null) {
                        infoBase = ri;

                        // If the field is a OneToMany then it is a s Set
                        // and we need to make sure the items in the set are clonable
                        // if they are not clonable then we can't include this in 
                        // the Carry Forward list
                        Class<?> dataCls = ri.getDataClass();
                        if (ri.getType() == DBRelationshipInfo.RelationshipType.OneToMany) {
                            try {
                                Method method = dataCls.getMethod("clone", new Class<?>[] {});
                                // Pretty much every Object has a "clone" method but we need 
                                // to check to make sure it is implemented by the same class of 
                                // Object that is in the Set.
                                isOK = method.getDeclaringClass() == dataCls;

                            } catch (Exception ex) {
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormViewObj.class,
                                        ex);
                                isOK = false; // this really shouldn't happen
                            }
                        }

                    } else if (fieldInfo.getUiPlugin() != null) {
                        if (StringUtils.isNotEmpty(label)) {
                            label = fieldInfo.getUiPlugin().getTitle();
                        }
                        isOK = fieldInfo.getUiPlugin().canCarryForward();
                    } else {
                        log.error("Couldn't find field [" + fieldName + "] in [" + tblInfo.getTitle() + "]");
                        isOK = false;
                    }
                }

                if (isOK) {
                    if (infoBase != null && StringUtils.isEmpty(label)) {
                        label = infoBase.getTitle();
                    }
                    fieldInfo.setLabel(label);
                    itemLabels.add(fieldInfo);
                    fieldInfo.setFieldInfo(infoBase);
                } else {
                    log.error("Field NOT OK [" + fieldName + "] in [" + tblInfo.getTitle() + "]");
                }
            }
        }
    }

    Collections.sort(itemLabels, new Comparator<FVOFieldInfo>() {
        @Override
        public int compare(FVOFieldInfo o1, FVOFieldInfo o2) {
            if (o1.getLabel() == null || o2.getLabel() == null) {
                return 1;
            }
            return o1.getLabel().compareTo(o2.getLabel());
        }
    });

}

From source file:com.clark.func.Functions.java

/**
 * <p>/* ww w.  j  av a 2s .co m*/
 * Returns the desired Method much like <code>Class.getMethod</code>,
 * however it ensures that the returned Method is from a public class or
 * interface and not from an anonymous inner class. This means that the
 * Method is invokable and doesn't fall foul of Java bug <a
 * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957"
 * >4071957</a>).
 * 
 * <code><pre>Set set = Collections.unmodifiableSet(...);
 *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
 *  Object result = method.invoke(set, new Object[]);</pre></code>
 * </p>
 * 
 * @param cls
 *            the class to check, not null
 * @param methodName
 *            the name of the method
 * @param parameterTypes
 *            the list of parameters
 * @return the method
 * @throws NullPointerException
 *             if the class is null
 * @throws SecurityException
 *             if a a security violation occured
 * @throws NoSuchMethodException
 *             if the method is not found in the given class or if the
 *             metothod doen't conform with the requirements
 */
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?> parameterTypes[])
        throws SecurityException, NoSuchMethodException {

    Method declaredMethod = cls.getMethod(methodName, parameterTypes);
    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
        return declaredMethod;
    }

    List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
    candidateClasses.addAll(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Class<?> candidateClass : candidateClasses) {
        if (!Modifier.isPublic(candidateClass.getModifiers())) {
            continue;
        }
        Method candidateMethod;
        try {
            candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ex) {
            continue;
        }
        if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
            return candidateMethod;
        }
    }

    throw new NoSuchMethodException("Can't find a public method for " + methodName);
}

From source file:com.clark.func.Functions.java

/**
 * <p>/*from  w  w  w .  ja  v a 2 s.  c o m*/
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method. If no such method can
 * be found, return <code>null</code>.
 * </p>
 * 
 * @param method
 *            The method that we wish to call
 * @return The accessible method
 */
public static Method getAccessibleMethod(Method method) {
    if (!isAccessible(method)) {
        return null;
    }
    // If the declaring class is public, we are done
    Class<?> cls = method.getDeclaringClass();
    if (Modifier.isPublic(cls.getModifiers())) {
        return method;
    }
    String methodName = method.getName();
    Class<?>[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(cls, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(cls, methodName, parameterTypes);
    }
    return method;
}