Example usage for org.apache.commons.beanutils ConstructorUtils invokeConstructor

List of usage examples for org.apache.commons.beanutils ConstructorUtils invokeConstructor

Introduction

In this page you can find the example usage for org.apache.commons.beanutils ConstructorUtils invokeConstructor.

Prototype

public static Object invokeConstructor(Class klass, Object[] args, Class[] parameterTypes)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
        InstantiationException 

Source Link

Document

Returns new instance of klazz created using constructor with signature parameterTypes and actual arguments args.

The signatures should be assignment compatible.

Usage

From source file:info.magnolia.objectfactory.DefaultClassFactory.java

@Override
public <T> T newInstance(final Class<T> c, final Class<?>[] argTypes, final Object... params) {
    if (argTypes.length != params.length) {
        throw new IllegalStateException("Argument types and values do not match! " + Arrays.asList(argTypes)
                + " / " + Arrays.asList(params));
    }//from www.j a  va  2  s  . co  m

    return newInstance(c, params, new Invoker<T>() {
        @Override
        public T invoke() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException,
                InstantiationException {
            return (T) ConstructorUtils.invokeConstructor(c, params, argTypes);
        }
    });
}

From source file:ar.com.zauber.commons.repository.SpringHibernateRepository.java

/**
 * @see Repository/* ww  w  .j  a  va 2  s .c om*/
 *  #createNew( Reference, java.lang.Object[], java.lang.Class[])
 */
@SuppressWarnings("unchecked")
public final <T extends Persistible> T createNew(final Reference<T> aRef, final Object[] args,
        final Class<?>[] types) {
    T persistible = null;

    try {
        persistible = (T) ConstructorUtils.invokeConstructor(Class.forName(aRef.getClassName()), args, types);
    } catch (final NoSuchMethodException e) {
        logger.error("creating instance of" + aRef.getClass(), e);
    } catch (final IllegalAccessException e) {
        logger.error("creating instance of" + aRef.getClass(), e);
    } catch (final InvocationTargetException e) {
        logger.error("creating instance of" + aRef.getClass(), e);
    } catch (final InstantiationException e) {
        logger.error("creating instance of" + aRef.getClass(), e);
    } catch (final ClassNotFoundException e) {
        logger.error("creating instance of" + aRef.getClass(), e);
    }

    return persistible;
}

From source file:com.googlecode.psiprobe.Tomcat70ContainerAdaptor.java

@Override
protected JspCompilationContext createJspCompilationContext(String name, boolean isErrPage, Options opt,
        ServletContext sctx, JspRuntimeContext jrctx, ClassLoader cl) {
    JspCompilationContext jcctx;/*from ww w .  ja va2  s .  co  m*/
    try {
        jcctx = new JspCompilationContext(name, opt, sctx, null, jrctx);
    } catch (NoSuchMethodError err) {
        /*
         * The above constructor's signature changed in Tomcat 7.0.16:
         * http://svn.apache.org/viewvc?view=revision&revision=1124719
         * 
         * If we reach this point, we are running on a prior version of
         * Tomcat 7 and must use reflection to create this object.
         */
        try {
            jcctx = (JspCompilationContext) ConstructorUtils.invokeConstructor(JspCompilationContext.class,
                    new Object[] { name, false, opt, sctx, null, jrctx },
                    new Class[] { String.class, Boolean.TYPE, Options.class, ServletContext.class,
                            JspServletWrapper.class, JspRuntimeContext.class });
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(ex);
        } catch (InstantiationException ex) {
            throw new RuntimeException(ex);
        }
    }
    if (cl != null) {
        jcctx.setClassLoader(cl);
    }
    return jcctx;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractReportController.java

@SuppressWarnings("rawtypes")
private String getReport(String month, String year, ModelMap modelMap, Class genericReportKlass, Page page,
        Locale locale) {/*from  w  w w  . j a va  2  s .c  om*/
    Report report = null;
    HashMap<String, Object> parameters = new HashMap<String, Object>();
    Calendar cal = Calendar.getInstance();
    if (month == null) {
        month = Integer.toString(cal.get(Calendar.MONTH) + 1);
    }
    if (year == null) {
        year = Integer.toString(cal.get(Calendar.YEAR));
    }

    parameters.put("month", month);
    parameters.put("year", year);
    parameters.put("defaultCurrency",
            messageSource.getMessage(
                    "currency.symbol."
                            + config.getValue(Names.com_citrix_cpbm_portal_settings_default_currency),
                    null, locale));
    Object[] args = new Object[] { parameters, dataSource, config, locale, messageSource };

    Class[] parameterTypes = new Class[] { Map.class, DataSource.class, Configuration.class, Locale.class,
            MessageSource.class };
    GenericReport generic_report;
    try {
        generic_report = (GenericReport) ConstructorUtils.invokeConstructor(genericReportKlass, args,
                parameterTypes);
        report = reportService.generateReport(generic_report);

        setPage(modelMap, page);
        modelMap.addAttribute("report", report);
        modelMap.addAttribute("tenant", getCurrentUser().getTenant());
        addMonthAndYearToMap(modelMap, locale);
    } catch (NoSuchMethodException e) {
        return "failure";
    } catch (IllegalAccessException e) {
        return "failure";
    } catch (InvocationTargetException e) {
        return "failure";
    } catch (InstantiationException e) {
        return "failure";
    }
    return "success";
}

From source file:net.testdriven.psiprobe.Tomcat70ContainerAdaptor.java

@Override
protected JspCompilationContext createJspCompilationContext(String name, boolean isErrPage, Options opt,
        ServletContext sctx, JspRuntimeContext jrctx, ClassLoader cl) {
    JspCompilationContext jcctx;/*w w w  .  jav  a 2s .  c  o  m*/
    try {
        jcctx = new JspCompilationContext(name, opt, sctx, null, jrctx);
    } catch (NoSuchMethodError err) {
        /*
         * The above constructor's signature changed in Tomcat 7.0.16:
         * http://svn.apache.org/viewvc?view=revision&revision=1124719
         * 
         * If we reach this point, we are running on a prior version of
         * Tomcat 7 and must use reflection to create this object.
         */
        try {
            jcctx = (JspCompilationContext) ConstructorUtils.invokeConstructor(JspCompilationContext.class,
                    new Object[] { name, false, opt, sctx, null, jrctx },
                    new Class[] { String.class, Boolean.TYPE, Options.class, ServletContext.class,
                            JspServletWrapper.class, JspRuntimeContext.class });
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException ex) {
            throw new RuntimeException(ex);
        }
    }
    if (cl != null) {
        jcctx.setClassLoader(cl);
    }
    return jcctx;
}

From source file:org.isatools.isatab.mapping.attributes.pipeline.BIIPropValFreeTextMappingHelper.java

/**
 * This default version://from w  w w .ja  v  a  2  s.  c o m
 * <ul>
 * <li> produces a {@link FreeTextTerm} instance
 * <li> checks if there is something in Term Source Name, if yes an {@link OntologyTerm} is attached,
 * using {@link #type}, possibly attaching an accession
 * </ul>
 */
@SuppressWarnings("unchecked")
@Override
public PVT mapProperty(int recordIndex) {
    SectionInstance sectionInstance = getSectionInstance();

    int ifield = this.getFieldIndex();
    if (ifield == -1) {
        log.trace(String.format("WARNING: Field %s not found in section %s", getFieldName(),
                sectionInstance.getSectionId()));
        return null;
    }

    String valueStr = StringUtils.trimToNull(sectionInstance.getString(recordIndex, ifield));

    // null values don't make sense and we can ignore them.
    if (valueStr == null) {
        return null;
    }

    // instantiate a new property value and setup its name
    //

    // Needs to extrapolate the classes from the generic and dynamically instantiate the value.
    PVT value = null;
    try {
        value = (PVT) ConstructorUtils.invokeConstructor(getMappedBIIPropertyValueClass(),
                new Object[] { valueStr, (PT) type },
                new Class[] { String.class, getMappedBIIPropertyClass() });
    } catch (Exception ex) {
        String msg = "Error in creating new property value,\nClass<PV> = "
                + this.getMappedBIIPropertyValueClass().getName() + "\nClass<PVT> = "
                + this.getMappedBIIPropertyClass() + "\nClass(Property)" + this.getMappedPropertyClass()
                + "\n  error: " + ex.getMessage();
        throw new TabInternalErrorException(msg, ex);
    }

    // Handle source and (optional) accession
    //
    String accessionStr = "";
    String sourceStr = StringUtils.trimToEmpty((String) sectionInstance.getString(recordIndex, ifield + 1));

    Field right1Field = getRight1Field();
    boolean hasAccessionHeader = right1Field != null
            && BIIPropertyValueMappingHelper.ACCESSION_HEADER.equals(right1Field.getAttr("id"));
    if (hasAccessionHeader) {
        accessionStr = StringUtils.trimToEmpty((String) sectionInstance.getString(recordIndex, ifield + 2));
    }

    if (sourceStr.length() == 0) {
        // I don't have a source but I have the accession: that's too bad!
        if (hasAccessionHeader && accessionStr.length() != 0) {
            throw new TabMissingValueException(i18n.msg("accession_without_source", accessionStr));
        }

        // Otherwise I fall to consider it free text
        log.debug("WARNING: No ontology source specified for '" + valueStr + "', assuming it is free text");
    } else {
        // I have a source, let's check the accession and eventually set the term
        if (!hasAccessionHeader || accessionStr.length() == 0) {
            String typeName = type == null ? "[?]" : type.getValue();
            log.debug("WARNING: Creating ontology term '" + typeName + "' / '" + valueStr
                    + "' without accession, assuming it's free text");
        }
        OntologyTerm term = (OntologyTerm) mappingUtils.createOntologyEntry(accessionStr, valueStr, sourceStr,
                OntologyTerm.class);
        value.addOntologyTerm(term);
    }

    if (log.isTraceEnabled()) {
        Collection<OntologyTerm> terms = value.getOntologyTerms();
        Iterator<OntologyTerm> titr = terms.iterator();
        OntologyTerm term = titr != null && titr.hasNext() ? titr.next() : null;
        log.trace("Returning mapped ontology term '" + value + "', source: " + term);
    }

    return value;
}

From source file:org.isatools.tablib.mapping.ClassTabMapper.java

/**
 * Creates the mapping helper for mapping the field in fieldIndex.
 * Can be used by {@link #getPropertyHelpers(int, int)}.
 *///  w  ww  .j a v  a 2 s.  c  o  m
@SuppressWarnings("unchecked")
protected PropertyMappingHelper<T, ?> newPropertyHelper(int fieldIndex) {
    SectionInstance sectionInstance = getSectionInstance();
    List<Field> fields = sectionInstance.getFields();
    Field field = fields.get(fieldIndex);

    String fieldName = field.getAttr("id");
    MappingHelperConfig<?> helperConfig = mappingHelpersConfig.get(fieldName);
    if (helperConfig == null) {
        return null;
    }

    PropertyMappingHelper<T, ?> helper;
    helperConfig.getOptions().put("fieldName", fieldName);

    try {
        helper = (PropertyMappingHelper<T, ?>) ConstructorUtils.invokeConstructor(helperConfig.getHelperClass(),
                new Object[] { getStore(), sectionInstance, helperConfig.getOptions(), fieldIndex },
                new Class<?>[] { BIIObjectStore.class, SectionInstance.class, Map.class, Integer.class });
    } catch (Exception ex) {
        throw new TabInternalErrorException("Error while creating the mapper for the property " + fieldName
                + "/" + helperConfig.getOption("propertyName") + ": " + ex.getMessage(), ex);
    }
    return helper;
}

From source file:org.isatools.tablib.mapping.FormatSetTabMapper.java

private FormatTabMapper getFormatMapper(FormatInstance formatInstance) {
    String formatId = formatInstance.getFormat().getId();

    Class<? extends FormatTabMapper> mapperClass = formatMappersConfig.get(formatId);
    if (mapperClass == null) {
        log.trace("WARNING, No mapper defined for format " + formatId + " in "
                + this.getClass().getCanonicalName());
        return null;
    }//from   www.j  ava  2 s  . c  om

    FormatTabMapper mapper;

    try {
        mapper = (FormatTabMapper) ConstructorUtils.invokeConstructor(mapperClass,
                new Object[] { this.getStore(), formatInstance },
                new Class<?>[] { BIIObjectStore.class, FormatInstance.class });
    } catch (Exception ex) {
        throw new TabInternalErrorException("Error with the creation of a mapper for format " + formatId
                + "(class " + mapperClass.getSimpleName() + "): " + ex.getMessage(), ex);
    }

    return mapper;
}

From source file:org.isatools.tablib.mapping.FormatTabMapper.java

private SectionTabMapper getSectionMapper(SectionInstance sectionInstance) {
    String sectionId = sectionInstance.getSection().getId();

    Class<? extends SectionTabMapper> mapperClass = sectionMappersConfig.get(sectionId);
    if (mapperClass == null) {
        log.trace("WARNING: No mapper defined for section " + sectionId + " in "
                + this.getClass().getCanonicalName());
        return null;
    }/*from   w  ww . j a  v a 2 s.  c o  m*/

    SectionTabMapper mapper;

    try {
        mapper = (SectionTabMapper) ConstructorUtils.invokeConstructor(mapperClass,
                new Object[] { this.getStore(), sectionInstance },
                new Class<?>[] { BIIObjectStore.class, SectionInstance.class });
    } catch (Exception ex) {
        throw new TabInternalErrorException(
                "Error with the creation of a mapper for section " + sectionId + ": " + ex.getMessage(), ex);
    }

    return mapper;
}

From source file:org.isatools.tablib.mapping.MappingUtils.java

/**
 * Creates a new ontology entry, from string parameters. Assumes the source for the term was
 * defined in the References spreadsheet.
 *
 * @param acc        The accession for the OE
 * @param labelField The name of the filed where to get the term label
 * @param sourceAcc  The name of term source, as it appears in References/Ontology Source References.
 *                   Does not set the source if this parameter is null.
 * @param oeClass    The OntologyEntry class to be instantiated.
 * @return the new term, with sources attached
 *///from w  w  w. j ava 2s  . c o m
@SuppressWarnings("unchecked")
public <OET extends OntologyEntry> OET createOntologyEntry(String acc, String label, String sourceAcc,
        Class<OET> oeClass) {
    acc = StringUtils.trimToNull(acc);
    label = StringUtils.trimToEmpty(label);
    sourceAcc = StringUtils.trimToNull(sourceAcc);

    if (acc == null && label == null && sourceAcc == null) {
        return null;
    }

    String logpref = String.format("createOntologyEntry( '%s:%s(%s), '%s' ): ", sourceAcc, acc, label,
            oeClass.getSimpleName());

    if (acc == null) {
        acc = "NULL-ACCESSION";
        log.debug("WARNING, No accession provided for the term '" + label + "'/'" + sourceAcc
                + "', using fake accession: " + acc);
    }

    ReferenceSource source = null;
    if (sourceAcc == null) {
        source = new ReferenceSource("Fictitious source for to-be curated terms");
        source.setAcc("BII:NULL-SOURCE");
        log.debug("WARNING, No source specified for the Ontology Term: '" + acc + "'/'" + label
                + "', adding fake source: " + source);
    } else {
        source = (ReferenceSource) store.get(ReferenceSource.class, sourceAcc);
        if (source == null) {
            throw new TabMissingValueException("Cannot find the ontology source '" + sourceAcc + "'");
        }
    }

    OET oe;
    try {
        oe = (OET) ConstructorUtils.invokeConstructor(oeClass, new Object[] { acc, label, source },
                new Class[] { String.class, String.class, ReferenceSource.class });
    } catch (Exception e) {
        throw new TabMissingValueException("Cannot create a new OntologyEntry: " + e.getMessage(), e);
    }

    store.valueOfType(TabMappingContext.class).put("used.oeSource." + sourceAcc, oe);

    if (log.isTraceEnabled()) {
        log.trace(logpref + "Returning new Ontology Entry: " + oe);
    }
    return oe;
}