Example usage for java.lang Class getDeclaredConstructor

List of usage examples for java.lang Class getDeclaredConstructor

Introduction

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

Prototype

@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

Usage

From source file:org.jbpm.instantiation.XmlInstantiator.java

public Object instantiate(Class clazz, String configuration) {
    Object newInstance = null;//  w  w  w .ja v  a2  s.  co m
    try {
        // parse the bean configuration
        Element configurationElement = parseConfiguration(configuration);

        Constructor constructor = clazz.getDeclaredConstructor(parameterTypes);
        constructor.setAccessible(true);
        newInstance = constructor.newInstance(new Object[] { configurationElement });
    } catch (Exception e) {
        log.error("couldn't instantiate '" + clazz.getName() + "'", e);
        throw new JbpmException(e);
    }
    return newInstance;
}

From source file:com.cloudera.sqoop.manager.DefaultManagerFactory.java

public ConnManager accept(JobData data) {
    SqoopOptions options = data.getSqoopOptions();
    String manualDriver = options.getDriverClassName();
    if (manualDriver != null) {
        // User has manually specified JDBC implementation with --driver.
        // Just use GenericJdbcManager.
        return new GenericJdbcManager(manualDriver, options);
    }/*from w w w .j  av a  2s.co m*/

    if (null != options.getConnManagerClassName()) {
        String className = options.getConnManagerClassName();
        ConnManager connManager = null;
        try {
            Class<ConnManager> cls = (Class<ConnManager>) Class.forName(className);
            Constructor<ConnManager> constructor = cls.getDeclaredConstructor(SqoopOptions.class);
            connManager = constructor.newInstance(options);
        } catch (Exception e) {
            System.err.println("problem finding the connection manager for class name :" + className);
            // Log the stack trace for this exception
            LOG.debug(e.getMessage(), e);
            // Print exception message.
            System.err.println(e.getMessage());
        }
        return connManager;
    }

    String connectStr = options.getConnectString();

    // java.net.URL follows RFC-2396 literally, which does not allow a ':'
    // character in the scheme component (section 3.1). JDBC connect strings,
    // however, commonly have a multi-scheme addressing system. e.g.,
    // jdbc:mysql://...; so we cannot parse the scheme component via URL
    // objects. Instead, attempt to pull out the scheme as best as we can.

    // First, see if this is of the form [scheme://hostname-and-etc..]
    int schemeStopIdx = connectStr.indexOf("//");
    if (-1 == schemeStopIdx) {
        // If no hostname start marker ("//"), then look for the right-most ':'
        // character.
        schemeStopIdx = connectStr.lastIndexOf(':');
        if (-1 == schemeStopIdx) {
            // Warn that this is nonstandard. But we should be as permissive
            // as possible here and let the ConnectionManagers themselves throw
            // out the connect string if it doesn't make sense to them.
            LOG.warn("Could not determine scheme component of connect string");

            // Use the whole string.
            schemeStopIdx = connectStr.length();
        }
    }

    String scheme = connectStr.substring(0, schemeStopIdx);

    if (null == scheme) {
        // We don't know if this is a mysql://, hsql://, etc.
        // Can't do anything with this.
        LOG.warn("Null scheme associated with connect string.");
        return null;
    }

    LOG.debug("Trying with scheme: " + scheme);

    if (scheme.equals("jdbc:mysql:")) {
        if (options.isDirect()) {
            return new DirectMySQLManager(options);
        } else {
            return new MySQLManager(options);
        }
    } else if (scheme.equals("jdbc:postgresql:")) {
        if (options.isDirect()) {
            return new DirectPostgresqlManager(options);
        } else {
            return new PostgresqlManager(options);
        }
    } else if (scheme.startsWith("jdbc:hsqldb:")) {
        return new HsqldbManager(options);
    } else if (scheme.startsWith("jdbc:oracle:")) {
        return new OracleManager(options);
    } else {
        return null;
    }
}

From source file:com.liferay.faces.bridge.renderkit.primefaces.FileUploadRendererPrimeFacesImpl.java

/**
 * This method overrides the {@link #decode(FacesContext, UIComponent)} method so that it can avoid a Servlet-API
 * dependency in the PrimeFaces FileUploadRenderer. Note that p:fileUpload will do an Ajax postback and invoke the
 * JSF lifecycle for each individual file.
 *//*from ww  w . j a v  a  2  s  . c  o  m*/
@Override
public void decode(FacesContext facesContext, UIComponent uiComponent) {

    try {
        String clientId = uiComponent.getClientId(facesContext);
        ExternalContext externalContext = facesContext.getExternalContext();
        Map<String, String> requestParameterMap = externalContext.getRequestParameterMap();
        String submittedValue = requestParameterMap.get(clientId);

        if (submittedValue != null) {

            // Get the UploadedFile from the request attribute map.
            ContextMapFactory contextMapFactory = (ContextMapFactory) FactoryExtensionFinder
                    .getFactory(ContextMapFactory.class);
            BridgeContext bridgeContext = BridgeContext.getCurrentInstance();
            Map<String, Collection<UploadedFile>> uploadedFileMap = contextMapFactory
                    .getUploadedFileMap(bridgeContext);

            Collection<UploadedFile> uploadedFiles = uploadedFileMap.get(clientId);

            if (uploadedFiles != null) {

                for (UploadedFile uploadedFile : uploadedFiles) {

                    // Convert the UploadedFile to a Commons-FileUpload FileItem.
                    FileItem fileItem = new PrimeFacesFileItem(clientId, uploadedFile);

                    // Reflectively create an instance of the PrimeFaces DefaultUploadedFile class.
                    Class<?> defaultUploadedFileClass = Class.forName(FQCN_DEFAULT_UPLOADED_FILE);
                    Constructor<?> constructor = defaultUploadedFileClass
                            .getDeclaredConstructor(FileItem.class);
                    Object defaultUploadedFile = constructor.newInstance(fileItem);

                    // If the PrimeFaces FileUpload component is in "simple" mode, then simply set the submitted
                    // value of the component to the DefaultUploadedFile instance.
                    PrimeFacesFileUpload primeFacesFileUpload = new PrimeFacesFileUpload((UIInput) uiComponent);

                    if (primeFacesFileUpload.getMode().equals(PrimeFacesFileUpload.MODE_SIMPLE)) {
                        logger.debug("Setting submittedValue=[{0}]", submittedValue);
                        primeFacesFileUpload.setSubmittedValue(defaultUploadedFile);
                    }

                    // Otherwise,
                    else {
                        logger.debug("Queuing FileUploadEvent for submittedValue=[{0}]", submittedValue);

                        // Reflectively create an instance of the PrimeFaces FileUploadEvent class.
                        Class<?> uploadedFileClass = Class.forName(FQCN_UPLOADED_FILE);
                        Class<?> fileUploadEventClass = Class.forName(FQCN_FILE_UPLOAD_EVENT);
                        constructor = fileUploadEventClass.getConstructor(UIComponent.class, uploadedFileClass);

                        FacesEvent fileUploadEvent = (FacesEvent) constructor.newInstance(uiComponent,
                                defaultUploadedFile);

                        // Queue the event.
                        primeFacesFileUpload.queueEvent(fileUploadEvent);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:com.liferay.faces.bridge.renderkit.primefaces.internal.FileUploadRendererPrimeFacesImpl.java

/**
 * This method overrides the {@link #decode(FacesContext, UIComponent)} method so that it can avoid a Servlet-API
 * dependency in the PrimeFaces FileUploadRenderer. Note that p:fileUpload will do an Ajax postback and invoke the
 * JSF lifecycle for each individual file.
 *//*from   w  w  w. j av a 2  s .c  o m*/
@Override
public void decode(FacesContext facesContext, UIComponent uiComponent) {

    try {
        String clientId = uiComponent.getClientId(facesContext);
        ExternalContext externalContext = facesContext.getExternalContext();
        Map<String, String> requestParameterMap = externalContext.getRequestParameterMap();
        String submittedValue = requestParameterMap.get(clientId);

        if (submittedValue != null) {

            // Get the UploadedFile from the request attribute map.
            ContextMapFactory contextMapFactory = (ContextMapFactory) BridgeFactoryFinder
                    .getFactory(ContextMapFactory.class);
            BridgeContext bridgeContext = BridgeContext.getCurrentInstance();
            Map<String, List<UploadedFile>> uploadedFileMap = contextMapFactory
                    .getUploadedFileMap(bridgeContext);

            List<UploadedFile> uploadedFiles = uploadedFileMap.get(clientId);

            if (uploadedFiles != null) {

                for (UploadedFile uploadedFile : uploadedFiles) {

                    // Convert the UploadedFile to a Commons-FileUpload FileItem.
                    FileItem fileItem = new PrimeFacesFileItem(clientId, uploadedFile);

                    // Reflectively create an instance of the PrimeFaces DefaultUploadedFile class.
                    Class<?> defaultUploadedFileClass = Class.forName(FQCN_DEFAULT_UPLOADED_FILE);
                    Constructor<?> constructor = defaultUploadedFileClass
                            .getDeclaredConstructor(FileItem.class);
                    Object defaultUploadedFile = constructor.newInstance(fileItem);

                    // If the PrimeFaces FileUpload component is in "simple" mode, then simply set the submitted
                    // value of the component to the DefaultUploadedFile instance.
                    PrimeFacesFileUpload primeFacesFileUpload = new PrimeFacesFileUpload((UIInput) uiComponent);

                    if (primeFacesFileUpload.getMode().equals(PrimeFacesFileUpload.MODE_SIMPLE)) {
                        logger.debug("Setting submittedValue=[{0}]", submittedValue);
                        primeFacesFileUpload.setSubmittedValue(defaultUploadedFile);
                    }

                    // Otherwise,
                    else {
                        logger.debug("Queuing FileUploadEvent for submittedValue=[{0}]", submittedValue);

                        // Reflectively create an instance of the PrimeFaces FileUploadEvent class.
                        Class<?> uploadedFileClass = Class.forName(FQCN_UPLOADED_FILE);
                        Class<?> fileUploadEventClass = Class.forName(FQCN_FILE_UPLOAD_EVENT);
                        constructor = fileUploadEventClass.getConstructor(UIComponent.class, uploadedFileClass);

                        FacesEvent fileUploadEvent = (FacesEvent) constructor.newInstance(uiComponent,
                                defaultUploadedFile);

                        // Queue the event.
                        primeFacesFileUpload.queueEvent(fileUploadEvent);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:ch.ksfx.web.pages.publishing.ManagePublishingConfiguration.java

public void onValidateFromPublishingConfigurationForm() {
    PublishingConfiguration publishingConfigurationOld = null;

    if (publishingConfiguration.getId() != null) {
        publishingConfigurationOld = publishingConfigurationDAO
                .getPublishingConfigurationForId(publishingConfiguration.getId());
    }//from   ww  w .  j  ava 2  s .com

    if (publishingConfigurationOld != null && publishingConfigurationOld.getLockedForEditing() == true
            && publishingConfiguration.getLockedForEditing() == true) {
        publishingConfigurationForm
                .recordError("This publishing configuration is locked, please unlock it first!");
    }

    try {
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
        Class clazz = groovyClassLoader.parseClass(publishingConfiguration.getPublishingStrategy());

        Constructor cons = clazz.getDeclaredConstructor(ObjectLocator.class);
    } catch (Exception e) {
        publishingConfigurationForm.recordError(StacktraceUtil.getStackTrace(e));
    }
}

From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandlersManager.java

/**
 * Retrieve the appropriate SecurityHandler for a the given filter name.
 * The filter name is an entry of the encryption dictionary of an encrypted document.
 *
 * @param filterName The filter name./*from w  ww  .ja  v  a 2  s .  co  m*/
 *
 * @return The appropriate SecurityHandler if it exists.
 *
 * @throws BadSecurityHandlerException If the security handler does not exist.
 */
public SecurityHandler getSecurityHandler(String filterName) throws BadSecurityHandlerException {
    Object found = handlerNames.get(filterName);
    if (found == null) {
        throw new BadSecurityHandlerException("Cannot find an appropriate security handler for " + filterName);
    }
    Class handlerclass = (Class) found;
    Class[] argsClasses = {};
    Object[] args = {};
    try {
        Constructor c = handlerclass.getDeclaredConstructor(argsClasses);
        SecurityHandler handler = (SecurityHandler) c.newInstance(args);
        return handler;
    } catch (Exception e) {
        LOG.error(e, e);
        throw new BadSecurityHandlerException("problem while trying to instanciate the security handler "
                + handlerclass.getName() + ": " + e.getMessage());
    }
}

From source file:cn.vlabs.duckling.vwb.service.auth.policy.AuthorizationFileParser.java

private Permission parsePermission() throws AuthorizationSyntaxParseException, IOException {
    String perm = ats.nextUsefulToken();
    if (perm == null) {
        throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", permission syntax error");
    } else if (!perm.toLowerCase().equals("permission")) {
        String rightBracket = perm;
        if (rightBracket == null || !rightBracket.contains("}")) {
            throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", no right bracket");
        } else if (!rightBracket.contains(";")) {
            throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", no \";\" sign finded");
        }//from  www .j a  v  a 2 s  . c om
        return null;
    }
    String className = ats.nextUsefulToken();
    String isEnd = ats.nextUsefulToken();
    if (className == null) {
        throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", className is null");
    }
    if (isEnd == null) {
        throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", no operate object defined");
    } else {
        try {
            if (!isEnd.contains(";")) {
                String oper = isEnd;
                oper = oper.replace("\"", "");
                oper = oper.replace(",", "");
                isEnd = ats.nextUsefulToken();
                if (isEnd != null && isEnd.contains(";")) {
                    String actions = isEnd.replace(";", "");
                    actions = actions.replace("\"", "");
                    Class<?> clazz = Class.forName(className, false, VWBPermission.class.getClassLoader());
                    return ((Permission) clazz
                            .getDeclaredConstructor(new Class[] { String.class, String.class })
                            .newInstance(oper, actions));
                } else {
                    throw new AuthorizationSyntaxParseException(
                            "Line " + ats.getLineNum() + ", no \";\" sign finded");
                }
            } else {
                String oper = isEnd.replace(";", "");
                oper = oper.replace("\"", "");
                Class<?> clazz = Class.forName(className);
                return ((Permission) clazz.getDeclaredConstructor(String.class).newInstance(oper));
            }
        } catch (ClassNotFoundException e) {
            throw new AuthorizationSyntaxParseException(
                    "Line " + ats.getLineNum() + ", ClassNotFoundException, " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthorizationSyntaxParseException(
                    "Line " + ats.getLineNum() + ", Exception happens, " + e.getMessage());
        }
    }
}

From source file:at.bitfire.davdroid.DateUtils.java

/**
 * Takes a formatted string as provided by the Android calendar provider and returns a DateListProperty
 * constructed from these values./*from ww w  . j a  va2  s  .  c  om*/
 * @param dbStr     formatted string from Android calendar provider (RDATE/EXDATE field)
 *                  expected format: "[TZID;]date1,date2,date3" where date is "yyyymmddThhmmss[Z]"
 * @param type      subclass of DateListProperty, e.g. RDate or ExDate
 * @param allDay    true: list will contain DATE values; false: list will contain DATE_TIME values
 * @return          instance of "type" containing the parsed dates/times from the string
 */
public static DateListProperty androidStringToRecurrenceSet(String dbStr,
        Class<? extends DateListProperty> type, boolean allDay) throws ParseException {
    // 1. split string into time zone and actual dates
    TimeZone timeZone;
    String datesStr;
    final int limiter = dbStr.indexOf(';');
    if (limiter != -1) { // TZID given
        timeZone = DateUtils.tzRegistry.getTimeZone(dbStr.substring(0, limiter));
        datesStr = dbStr.substring(limiter + 1);
    } else {
        timeZone = null;
        datesStr = dbStr;
    }

    // 2. process date string and generate list of DATEs or DATE-TIMEs
    DateList dateList;
    if (allDay) {
        dateList = new DateList(Value.DATE);
        for (String s : StringUtils.split(datesStr, ','))
            dateList.add(new Date(new DateTime(s)));
    } else {
        dateList = new DateList(datesStr, Value.DATE_TIME, timeZone);
        if (timeZone == null)
            dateList.setUtc(true);
    }

    // 3. generate requested DateListProperty (RDate/ExDate) from list of DATEs or DATE-TIMEs
    DateListProperty list;
    try {
        list = (DateListProperty) type.getDeclaredConstructor(new Class[] { DateList.class })
                .newInstance(dateList);
        if (dateList.getTimeZone() != null)
            list.setTimeZone(dateList.getTimeZone());
    } catch (Exception e) {
        throw new ParseException("Couldn't create date/time list by reflection", -1);
    }

    return list;
}

From source file:com.adaptris.core.fs.AggregatingFsConsumer.java

private FileFilter createFileFilter(String filterExpression) throws Exception {
    Class[] paramTypes = { filterExpression.getClass() };
    Object[] args = { filterExpression };

    Class c = Class.forName(fileFilterImp());
    Constructor cnst = c.getDeclaredConstructor(paramTypes);
    return (FileFilter) cnst.newInstance(args);
}

From source file:ae.config.Project.java

private ActiveEntity loadModelDefinitionAt(final Class<?> aClass) {
    assert aClass != null : "aClass is null";
    final Object declaredModel;
    final Constructor<?> constructor;

    try {//w ww  .  j  av  a  2 s  . com
        constructor = aClass.getDeclaredConstructor(getClass());
    } catch (final SecurityException e) {
        throw new IllegalStateException(e);
    } catch (final NoSuchMethodException e) {
        throw new IllegalStateException(e);
    }
    constructor.setAccessible(true);
    try {
        declaredModel = constructor.newInstance(this);
    } catch (final InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (final InvocationTargetException e) {
        throw new IllegalStateException(e);
    }
    return (ActiveEntity) declaredModel;
}