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.apache.sqoop.ConnFactory.java

/**
 * Factory method to get a ConnManager./*w w w .j  ava2s.c o  m*/
 *
 * Connection Manager is created directly if user specifies it on the command
 * line or the execution is passed to various configured connection factories
 * in case that user is not requesting one specific manager.
 *
 * @param data the connection and other configuration arguments.
 * @return a ConnManager instance for the appropriate database.
 * @throws IOException if it cannot find a ConnManager for this schema.
 */
public ConnManager getManager(JobData data) throws IOException {
    com.cloudera.sqoop.SqoopOptions options = data.getSqoopOptions();
    String manualDriver = options.getDriverClassName();
    String managerClassName = options.getConnManagerClassName();

    // User has specified --driver argument, but he did not specified
    // manager to use. We will use GenericJdbcManager as this was
    // the way sqoop was working originally. However we will inform
    // user that specifying connection manager explicitly is more cleaner
    // solution for this case.
    if (manualDriver != null && managerClassName == null) {
        LOG.warn("Parameter --driver is set to an explicit driver however"
                + " appropriate connection manager is not being set (via"
                + " --connection-manager). Sqoop is going to fall back to "
                + GenericJdbcManager.class.getCanonicalName() + ". Please specify"
                + " explicitly which connection manager should be used next time.");
        return new GenericJdbcManager(manualDriver, options);
    }

    // If user specified explicit connection manager, let's use it
    if (managerClassName != null) {
        ConnManager connManager = null;

        try {
            Class<ConnManager> cls = (Class<ConnManager>) Class.forName(managerClassName);

            // We have two constructor options, one is with or without explicit
            // constructor. In most cases --driver argument won't be allowed as the
            // connectors are forcing to use their building class names.
            if (manualDriver == null) {
                Constructor<ConnManager> constructor = cls
                        .getDeclaredConstructor(com.cloudera.sqoop.SqoopOptions.class);
                connManager = constructor.newInstance(options);
            } else {
                Constructor<ConnManager> constructor = cls.getDeclaredConstructor(String.class,
                        com.cloudera.sqoop.SqoopOptions.class);
                connManager = constructor.newInstance(manualDriver, options);
            }
        } catch (ClassNotFoundException e) {
            LOG.error("Sqoop could not found specified connection manager class " + managerClassName
                    + ". Please check that you've specified the " + "class correctly.");
            throw new IOException(e);
        } catch (NoSuchMethodException e) {
            LOG.error("Sqoop wasn't able to create connnection manager properly. "
                    + "Some of the connectors supports explicit --driver and some "
                    + "do not. Please try to either specify --driver or leave it out.");
            throw new IOException(e);
        } catch (Exception e) {
            LOG.error("Problem with bootstrapping connector manager:" + managerClassName);
            LOG.error(e);
            throw new IOException(e);
        }
        return connManager;
    }

    // Try all the available manager factories.
    for (ManagerFactory factory : factories) {
        LOG.debug("Trying ManagerFactory: " + factory.getClass().getName());
        ConnManager mgr = factory.accept(data);
        if (null != mgr) {
            LOG.debug("Instantiated ConnManager " + mgr.toString());
            return mgr;
        }
    }

    throw new IOException("No manager for connect string: " + data.getSqoopOptions().getConnectString());
}

From source file:org.apache.phoenix.queryserver.server.QueryServer.java

@Override
public int run(String[] args) throws Exception {
    logProcessInfo(getConf());/* w w  w  .j av  a  2s .  c  o m*/
    try {
        final boolean isKerberos = "kerberos"
                .equalsIgnoreCase(getConf().get(QueryServices.QUERY_SERVER_HBASE_SECURITY_CONF_ATTRIB));
        final boolean disableSpnego = getConf().getBoolean(
                QueryServices.QUERY_SERVER_SPNEGO_AUTH_DISABLED_ATTRIB,
                QueryServicesOptions.DEFAULT_QUERY_SERVER_SPNEGO_AUTH_DISABLED);

        // handle secure cluster credentials
        if (isKerberos && !disableSpnego) {
            String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
                    getConf().get(QueryServices.QUERY_SERVER_DNS_INTERFACE_ATTRIB, "default"),
                    getConf().get(QueryServices.QUERY_SERVER_DNS_NAMESERVER_ATTRIB, "default")));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Login to " + hostname + " using "
                        + getConf().get(QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB) + " and principal "
                        + getConf().get(QueryServices.QUERY_SERVER_KERBEROS_PRINCIPAL_ATTRIB) + ".");
            }
            SecurityUtil.login(getConf(), QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB,
                    QueryServices.QUERY_SERVER_KERBEROS_PRINCIPAL_ATTRIB, hostname);
            LOG.info("Login successful.");
        }

        Class<? extends PhoenixMetaFactory> factoryClass = getConf().getClass(
                QueryServices.QUERY_SERVER_META_FACTORY_ATTRIB, PhoenixMetaFactoryImpl.class,
                PhoenixMetaFactory.class);
        int port = getConf().getInt(QueryServices.QUERY_SERVER_HTTP_PORT_ATTRIB,
                QueryServicesOptions.DEFAULT_QUERY_SERVER_HTTP_PORT);
        LOG.debug("Listening on port " + port);
        PhoenixMetaFactory factory = factoryClass.getDeclaredConstructor(Configuration.class)
                .newInstance(getConf());
        Meta meta = factory.create(Arrays.asList(args));
        Service service = new LocalService(meta);

        // Start building the Avatica HttpServer
        final HttpServer.Builder builder = new HttpServer.Builder().withPort(port).withHandler(service,
                getSerialization(getConf()));

        // Enable SPNEGO and Impersonation when using Kerberos
        if (isKerberos) {
            UserGroupInformation ugi = UserGroupInformation.getLoginUser();

            // Make sure the proxyuser configuration is up to date
            ProxyUsers.refreshSuperUserGroupsConfiguration(getConf());

            String keytabPath = getConf().get(QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB);
            File keytab = new File(keytabPath);

            String realmsString = getConf().get(QueryServices.QUERY_SERVER_KERBEROS_ALLOWED_REALMS, null);
            String[] additionalAllowedRealms = null;
            if (null != realmsString) {
                additionalAllowedRealms = StringUtils.split(realmsString, ',');
            }

            // Enable SPNEGO and impersonation (through standard Hadoop configuration means)
            builder.withSpnego(ugi.getUserName(), additionalAllowedRealms).withAutomaticLogin(keytab)
                    .withImpersonation(new PhoenixDoAsCallback(ugi, getConf()));
        }

        // Build and start the HttpServer
        server = builder.build();
        server.start();
        runningLatch.countDown();
        server.join();
        return 0;
    } catch (Throwable t) {
        LOG.fatal("Unrecoverable service error. Shutting down.", t);
        this.t = t;
        return -1;
    }
}

From source file:org.commoncrawl.service.queryserver.index.PositionBasedSequenceFileIndex.java

public PositionBasedSequenceFileIndex(FileSystem fileSystem, Path indexFilePath, Class<KeyType> keyClass,
        Class<ValueType> valueClass) throws IOException {

    _fileSystem = fileSystem;//from www. j  ava2s . com
    _indexFileName = indexFilePath;

    if (!_fileSystem.exists(_indexFileName) || _fileSystem.getFileStatus(_indexFileName).isDir()) {
        throw new IOException("Index Path:" + indexFilePath + " Points to Invalid File");
    } else {

        try {
            this.keyConstructor = keyClass.getDeclaredConstructor(emptyArray);
            this.keyConstructor.setAccessible(true);
            this.valConstructor = valueClass.getDeclaredConstructor(emptyArray);
            this.valConstructor.setAccessible(true);
        } catch (SecurityException e) {
            LOG.error(CCStringUtils.stringifyException(e));
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            LOG.error(CCStringUtils.stringifyException(e));
            throw new RuntimeException(e);
        }

        _indexData = loadStreamIntoMemory(indexFilePath);
        _inputStream = new DataInputStream(newInputStream(_indexData));
        _header.readHeader(_inputStream);
        _headerOffset = _indexData.position();
        // calculate index item count based on file size 
        _indexItemCount = (int) (_indexData.remaining() / INDEX_RECORD_SIZE);
    }
}

From source file:de.fraunhofer.sciencedataamanager.business.SearchExecutionManager.java

/**
 * Executes the search definition.//from   www.j a  v  a 2s . c  o  m
 *
 * @param searchDefinitionID the search definition to be executed.
 * @throws Exception
 */
public void executeOnlyInformations(int searchDefinitionID) throws Exception {
    this.applicationConfiguration.getLoggingManager().log(
            "Entering methode (public void execute(int searchDefinitionID) throws Exception)", LogLevel.DEBUG);

    //get groovy code and compile it

    LinkedList<SearchDefinitonExecution> searchDefinitonExecutionList = new LinkedList<SearchDefinitonExecution>();
    SearchDefinitionDataManager searchDefinitionDataProvider = new SearchDefinitionDataManager(
            applicationConfiguration);
    SearchDefinition searchDefinition = searchDefinitionDataProvider
            .getSearchDefinitionByID(searchDefinitionID);

    SearchExecutionDataManager searchExecutionDataProvider = new SearchExecutionDataManager(
            applicationConfiguration);
    SearchExecution searchExecution = searchExecutionDataProvider
            .getSystemInstanceBySearchDefinition(searchDefinition);

    //construct search definition execution run object and set current timestamp

    SearchDefinitionExecutionRun searchDefinitionExecutionRun = new SearchDefinitionExecutionRun();
    searchDefinitionExecutionRun
            .setDescription(searchDefinition.getName() + " - " + Calendar.getInstance().getTime().toString());
    searchDefinitionExecutionRun
            .setStartExecutionTimestamp(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
    searchDefinitionExecutionRun.setSearchExecution(searchExecution);
    searchDefinitionExecutionRun.setSearchDefinitionExecutionList(searchDefinitonExecutionList);

    SearchDefinitonExecutionRunDataManager searchDefinitonExecutionRunDataManager = new SearchDefinitonExecutionRunDataManager(
            applicationConfiguration);
    searchDefinitionExecutionRun = searchDefinitonExecutionRunDataManager
            .insertSearchDefinitionExecutionRunLastID(searchDefinitionExecutionRun);

    //loop through each system instance and compile connector code. 

    for (SystemInstance connectorLoop : searchExecution.getSystemInstances()) {
        SearchDefinitonExecution searchDefinitonExecution = null;
        try {
            //get groovy code and compile it

            GroovyClassLoader gcl = new GroovyClassLoader();
            Class parsedGroocyClass = gcl
                    .parseClass(StringEscapeUtils.unescapeJava(connectorLoop.getGroovyCode()));
            Class[] constructorParameterConnector = new Class[1];
            constructorParameterConnector[0] = this.applicationConfiguration.getClass();
            //Object groovyClassInstance = parsedGroocyClass.newInstance(constructorParameterConnector);
            Object groovyClassInstance = null;
            Constructor connectorConstructor = parsedGroocyClass
                    .getDeclaredConstructor(constructorParameterConnector);
            if (connectorConstructor != null) {
                groovyClassInstance = connectorConstructor.newInstance(this.applicationConfiguration);
            } else {
                groovyClassInstance = parsedGroocyClass.newInstance();
            }
            currentExecutedConnector = (ICloudPaperConnector) groovyClassInstance;
            //currentExecutedConnector = new ElsevierScienceDirectConnectorBufferAbstract(this.applicationConfiguration); 
            //currentExecutedConnector = new WebOfScienceLightConnector(this.applicationConfiguration); 
            searchExecution.getSearchDefiniton().setSystemInstance(connectorLoop);

            //set to 0 because no data should be downloaded

            searchExecution.getSearchDefiniton().setItemTreshhold(0);
            //execute search method and wait for return

            searchDefinitonExecution = currentExecutedConnector
                    .getCloudPapers(searchExecution.getSearchDefiniton());
            searchDefinitonExecution.setSearchState("Success");
            //set result
            searchDefinitonExecution.setSearch_Definiton_ID(searchDefinitionID);
            searchDefinitonExecution.setSystemInstance(connectorLoop);
            searchDefinitionExecutionRun.getSearchDefinitionExecutionList().add(searchDefinitonExecution);

        } catch (Exception ex) {
            searchDefinitonExecution = new SearchDefinitonExecution();
            searchDefinitonExecution.setSearch_Definiton_ID(searchDefinitionID);
            searchDefinitonExecution.setSystemInstance(connectorLoop);
            searchDefinitonExecution.setSearchState("Failure");
            searchDefinitonExecution.setMessage(ex.toString());
            searchDefinitonExecution.setFinishedExecutionTimestamp(
                    new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
            searchDefinitionExecutionRun.getSearchDefinitionExecutionList().add(searchDefinitonExecution);
            this.applicationConfiguration.getLoggingManager().logException(ex);
            continue;
        }
    }
    //write data to db

    searchDefinitionExecutionRun
            .setFinishedExecutionTimestamp(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
    searchDefinitonExecutionRunDataManager.updateSearchDefinitionExecutionRun(searchDefinitionExecutionRun);

    for (SearchDefinitonExecution searchDefinitonExecution : searchDefinitionExecutionRun
            .getSearchDefinitionExecutionList()) {
        for (ScientificPaperMetaInformationParseException scientificPaperMetaInformationParseException : searchDefinitonExecution
                .getScientificPaperMetaInformationParseException()) {
            this.applicationConfiguration.getLoggingManager()
                    .logException(scientificPaperMetaInformationParseException.getParseException());
        }
    }

}

From source file:de.fraunhofer.sciencedataamanager.business.SearchExecutionManager.java

/**
 * Executes the search definition./*  w  ww  .j av  a  2 s  .  com*/
 *
 * @param searchDefinitionID the search definition to be executed.
 * @throws Exception
 */
public void execute(int searchDefinitionID) throws Exception {

    //get all search definitions and loop through each of them. 
    this.applicationConfiguration.getLoggingManager()
            .log("Prepare execution by getting all required data from database.", LogLevel.DEBUG);

    LinkedList<SearchDefinitonExecution> searchDefinitonExecutionList = new LinkedList<SearchDefinitonExecution>();
    SearchDefinitionDataManager searchDefinitionDataProvider = new SearchDefinitionDataManager(
            applicationConfiguration);
    SearchDefinition searchDefinition = searchDefinitionDataProvider
            .getSearchDefinitionByID(searchDefinitionID);

    SearchExecutionDataManager searchExecutionDataProvider = new SearchExecutionDataManager(
            applicationConfiguration);
    SearchExecution searchExecution = searchExecutionDataProvider
            .getSystemInstanceBySearchDefinition(searchDefinition);

    //construct search definition execution run object and set current timestamp
    SearchDefinitionExecutionRun searchDefinitionExecutionRun = new SearchDefinitionExecutionRun();
    searchDefinitionExecutionRun
            .setDescription(searchDefinition.getName() + " - " + Calendar.getInstance().getTime().toString());
    searchDefinitionExecutionRun
            .setStartExecutionTimestamp(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
    searchDefinitionExecutionRun.setSearchExecution(searchExecution);
    searchDefinitionExecutionRun.setSearchDefinitionExecutionList(searchDefinitonExecutionList);

    SearchDefinitonExecutionRunDataManager searchDefinitonExecutionRunDataManager = new SearchDefinitonExecutionRunDataManager(
            applicationConfiguration);
    searchDefinitionExecutionRun = searchDefinitonExecutionRunDataManager
            .insertSearchDefinitionExecutionRunLastID(searchDefinitionExecutionRun);
    this.applicationConfiguration.getLoggingManager()
            .log("System is now accessing each data source through connector.", LogLevel.DEBUG);

    //loop through each system instance and compile connector code. 
    for (SystemInstance connectorLoop : searchExecution.getSystemInstances()) {
        this.applicationConfiguration.getLoggingManager()
                .log("Preparing connector " + connectorLoop.getName() + "for execution!", LogLevel.DEBUG);

        SearchDefinitonExecution searchDefinitonExecution = null;
        try {

            //get groovy code and compile it
            GroovyClassLoader gcl = new GroovyClassLoader();
            Class parsedGroocyClass = gcl
                    .parseClass(StringEscapeUtils.unescapeJava(connectorLoop.getGroovyCode()));
            Class[] constructorParameterConnector = new Class[1];
            constructorParameterConnector[0] = this.applicationConfiguration.getClass();
            //Object groovyClassInstance = parsedGroocyClass.newInstance(constructorParameterConnector);
            Object groovyClassInstance = null;
            Constructor connectorConstructor = parsedGroocyClass
                    .getDeclaredConstructor(constructorParameterConnector);
            if (connectorConstructor != null) {
                groovyClassInstance = connectorConstructor.newInstance(this.applicationConfiguration);
            } else {
                groovyClassInstance = parsedGroocyClass.newInstance();
            }
            currentExecutedConnector = (ICloudPaperConnector) groovyClassInstance;
            //currentExecutedConnector = new ElsevierScienceDirectConnectorBufferAbstract(this.applicationConfiguration); 
            //currentExecutedConnector = new WebOfScienceLightConnector(this.applicationConfiguration); 
            searchExecution.getSearchDefiniton().setSystemInstance(connectorLoop);
            this.applicationConfiguration.getLoggingManager()
                    .log("Crawling started for connector: " + connectorLoop.getName(), LogLevel.DEBUG);

            //execute search method and wait for return
            searchDefinitonExecution = currentExecutedConnector
                    .getCloudPapers(searchExecution.getSearchDefiniton());
            this.applicationConfiguration.getLoggingManager()
                    .log("Crawling stopped for connector: " + connectorLoop.getName(), LogLevel.DEBUG);

            //set search result
            searchDefinitonExecution.setSearchState("Success");
            searchDefinitonExecution.setSearch_Definiton_ID(searchDefinitionID);
            searchDefinitonExecution.setSystemInstance(connectorLoop);
            searchDefinitionExecutionRun.getSearchDefinitionExecutionList().add(searchDefinitonExecution);
            this.applicationConfiguration.getLoggingManager().log(
                    "Connector search finished. Deconstruct connector: " + connectorLoop.getName(),
                    LogLevel.DEBUG);

        } catch (Exception ex) {
            searchDefinitonExecution = new SearchDefinitonExecution();
            searchDefinitonExecution.setSearch_Definiton_ID(searchDefinitionID);
            searchDefinitonExecution.setSystemInstance(connectorLoop);
            searchDefinitonExecution.setSearchState("Failure");
            searchDefinitonExecution.setMessage(ex.toString());
            searchDefinitonExecution.setFinishedExecutionTimestamp(
                    new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
            searchDefinitionExecutionRun.getSearchDefinitionExecutionList().add(searchDefinitonExecution);
            this.applicationConfiguration.getLoggingManager().logException(ex);
            continue;
        }
    }

    //write crawled data to the db
    this.applicationConfiguration.getLoggingManager().log("Start writing data to local database.",
            LogLevel.DEBUG);

    searchDefinitionExecutionRun
            .setFinishedExecutionTimestamp(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
    searchDefinitonExecutionRunDataManager.updateSearchDefinitionExecutionRun(searchDefinitionExecutionRun);

    for (SearchDefinitonExecution searchDefinitonExecution : searchDefinitionExecutionRun
            .getSearchDefinitionExecutionList()) {
        for (ScientificPaperMetaInformationParseException scientificPaperMetaInformationParseException : searchDefinitonExecution
                .getScientificPaperMetaInformationParseException()) {
            this.applicationConfiguration.getLoggingManager()
                    .logException(scientificPaperMetaInformationParseException.getParseException());
        }
    }
    this.applicationConfiguration.getLoggingManager().log("Stopped writing data to local database.",
            LogLevel.DEBUG);

}

From source file:ezbake.security.impl.cache.MemoryCache.java

@Override
public Value get(Key key, Class<?> clazz) {
    CacheValue<Value> value = lruCache.get(key);
    Value retval = null;//www .java 2 s.c o m

    // check value expiration
    if (value != null && !expired(value.timestamp)) {
        log.info("Value for key: {} was not expired - returning the value", key);
        retval = (value.value != null) ? value.value : null;
    } else if (value != null) {
        log.info("Value for key: {} expired at {} - removing from cache and returning null", key,
                value.timestamp);
        lruCache.remove(key);
    }

    // try to call the copy constructor so the user can't alter values in the cache
    if (retval != null) {
        try {
            Value copied = (Value) clazz.getDeclaredConstructor(clazz).newInstance(retval);
            retval = copied;
        } catch (NoSuchMethodException e) {
            log.warn(
                    "Cache value class doesn't support the copy constructor. Just returning the original object");
        } catch (InvocationTargetException e) {
            log.warn("Unexpected exception copying the cache value into a new object. returning null");
            retval = null;
        } catch (InstantiationException e) {
            log.warn("Unexpected exception instantiating the cache value into a new object. returning null");
            retval = null;
        } catch (IllegalAccessException e) {
            log.warn("Couldn't call the copy constructor of the cache value class. Just returning the original "
                    + "object");
        }
    }
    return retval;
}

From source file:org.opendope.webapp.SubmitBoth.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/html" })
public Response processForm(
        //         @Context ServletContext servletContext, 
        //         @Context  HttpServletRequest servletRequest,
        @FormDataParam("xmlfile") InputStream xis,
        @FormDataParam("xmlfile") FormDataContentDisposition xmlFileDetail,
        @FormDataParam("docx") InputStream docxInputStream,
        @FormDataParam("docx") FormDataContentDisposition docxFileDetail,
        @FormDataParam("format") String format, @FormDataParam("processTocField") boolean processTocField,
        @FormDataParam("TocPageNumbers") boolean tocPageNumbers) throws Docx4JException, IOException {

    //      log.info("servletRequest.getCharacterEncoding(): " + servletRequest.getCharacterEncoding());
    //      //from   w  ww . ja  va2 s  .c o m
    //      log.warn("platformt: " + getDefaultEncoding() );
    //      
    //      log.info("requested format: " + format);
    //      
    //      byte[] bytes = IOUtils.toByteArray(xis);
    //      File f = new File( System.getProperty("java.io.tmpdir") + "/xml.xml");
    //      FileUtils.writeByteArrayToFile(f, bytes); 
    //      log.info("Saved: " + f.getAbsolutePath());

    //      log.info("gip" + servletContext.getInitParameter("HtmlImageTargetUri") );
    //      java.util.Enumeration penum = servletContext.getInitParameterNames();
    //      for ( ; penum.hasMoreElements() ;) {
    //         String name = (String)penum.nextElement();
    //         log.info( name + "=" +  servletContext.getInitParameter(name) );
    //      }

    // For XHTML Import, only honour CSS on the white list
    initWhitelist();

    // XHTML Import: no need to add a mapping, if docx defaults are to be used,
    // for fonts in docx4j's MicrosoftFonts.xml.
    // Helvetica is not there.
    XHTMLImporterImpl.addFontMapping("helvetica", "Helvetica");

    final WordprocessingMLPackage wordMLPackage;

    String dataname = getFileName(xmlFileDetail.getFileName());

    WordprocessingMLPackage tmpPkg = null;

    String docxname = getFileName(docxFileDetail.getFileName());

    LoadFromZipNG loader = new LoadFromZipNG();
    try {
        tmpPkg = (WordprocessingMLPackage) loader.get(docxInputStream);
    } catch (Exception e) {
        throw new WebApplicationException(
                new Docx4JException("Error reading docx file (is this a valid docx?)"), Status.BAD_REQUEST);
    }

    // Now we should have both our docx and xml
    if (tmpPkg == null) {
        throw new WebApplicationException(new Docx4JException("No docx file provided"), Status.BAD_REQUEST);
    }
    if (xis == null) {
        throw new WebApplicationException(new Docx4JException("No xml data file provided"), Status.BAD_REQUEST);
    }
    wordMLPackage = tmpPkg;
    String filePrefix = docxname + "_" + dataname + "_" + now("yyyyMMddHHmmss"); // add ss or ssSSSS if you wish

    // Find custom xml item id and inject data_file.xml      
    CustomXmlDataStoragePart customXmlDataStoragePart = CustomXmlDataStoragePartSelector
            .getCustomXmlDataStoragePart(wordMLPackage);
    if (customXmlDataStoragePart == null) {
        throw new WebApplicationException(new Docx4JException("Couldn't find CustomXmlDataStoragePart"),
                Status.UNSUPPORTED_MEDIA_TYPE);
    }
    customXmlDataStoragePart.getData().setDocument(xis);

    //      customXmlDataStoragePart.getData().setDocument(new ByteArrayInputStream(bytes));

    //      java.lang.NullPointerException
    //      org.docx4j.openpackaging.parts.XmlPart.setDocument(XmlPart.java:129)

    final SaveToZipFile saver = new SaveToZipFile(wordMLPackage);

    // Process conditionals and repeats
    OpenDoPEHandler odh = new OpenDoPEHandler(wordMLPackage);
    odh.preprocess();

    OpenDoPEIntegrity odi = new OpenDoPEIntegrity();
    odi.process(wordMLPackage);

    if (log.isDebugEnabled()) {
        try {
            File save_preprocessed = new File(
                    System.getProperty("java.io.tmpdir") + "/" + filePrefix + "_INT.docx");
            saver.save(save_preprocessed);
            log.debug("Saved: " + save_preprocessed);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    // Apply the bindings
    // Convert hyperlinks, using this style
    BindingHandler.setHyperlinkStyle(hyperlinkStyleId);

    AtomicInteger bookmarkId = odh.getNextBookmarkId();
    BindingHandler bh = new BindingHandler(wordMLPackage);
    bh.setStartingIdForNewBookmarks(bookmarkId);
    bh.applyBindings();

    if (log.isDebugEnabled()) {
        try {
            File save_bound = new File(System.getProperty("java.io.tmpdir") + "/" + filePrefix + "_BOUND.docx");
            saver.save(save_bound);
            log.debug("Saved: " + save_bound);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        //         System.out.println(
        //         XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
        //         );         
    }

    // Update TOC .. before RemovalHandler!
    if (processTocField) {

        log.debug("toc processing requested");

        // Use reflection, so this WAR can be built
        // by users who don't have the Enterprise jar
        try {
            Class<?> tocGenerator = Class.forName("com.plutext.docx.toc.TocGenerator");

            Constructor ctor = tocGenerator.getDeclaredConstructor(WordprocessingMLPackage.class);
            Object tocGeneratorObj = ctor.newInstance(wordMLPackage);

            //Method method = documentBuilder.getMethod("merge", wmlPkgList.getClass());         
            Method[] methods = tocGenerator.getMethods();
            Method method = null;
            for (int j = 0; j < methods.length; j++) {
                System.out.println(methods[j].getName());
                if (methods[j].getName().equals("updateToc") && methods[j].getParameterTypes().length == 1) {
                    method = methods[j];
                    break;
                }
            }
            if (method == null) {
                log.error("toc processing requested, but Enterprise jar not available");
            } else {

                Document contentBackup = XmlUtils
                        .deepCopy(wordMLPackage.getMainDocumentPart().getJaxbElement());
                try {
                    //                  TocGenerator.updateToc(wordMLPackage, tocPageNumbers);
                    method.invoke(tocGeneratorObj, !tocPageNumbers);
                } catch (Exception e1) {
                    log.error(e1.getMessage(), e1);
                    log.error("Omitting TOC; generate that in Word");
                    wordMLPackage.getMainDocumentPart().setJaxbElement(contentBackup);
                    //                  TocGenerator.updateToc(wordMLPackage, true);
                }
            }

        } catch (Exception e) {
            log.error("toc processing requested, but Enterprise jar not available");
            log.error(e.getMessage(), e);
        }
    }

    // Strip content controls: you MUST do this 
    // if you are processing hyperlinks
    RemovalHandler rh = new RemovalHandler();
    rh.removeSDTs(wordMLPackage, Quantifier.ALL);
    if (log.isDebugEnabled()) {
        try {
            File save = new File(System.getProperty("java.io.tmpdir") + "/" + filePrefix + "_STRIPPED.docx");
            saver.save(save);
            log.debug("Saved: " + save);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    if (format != null) {

        if (format.equals("html")) {

            // Return html
            final AbstractHtmlExporter exporter = new HtmlExporterNG2();
            final HtmlSettings htmlSettings = new HtmlSettings();
            htmlSettings.setImageDirPath(htmlImageDirPath);
            htmlSettings.setImageTargetUri(htmlImageTargetUri);

            ResponseBuilder builder = Response.ok(

                    new StreamingOutput() {

                        public void write(OutputStream output) throws IOException, WebApplicationException {

                            javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(
                                    output);

                            try {
                                exporter.html(wordMLPackage, result, htmlSettings);
                            } catch (Exception e) {
                                throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
                            }

                        }
                    });
            builder.type("text/html");
            return builder.build();

        } else if (format.equals("pdf")) {

            final org.docx4j.convert.out.pdf.PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
                    wordMLPackage);

            ResponseBuilder builder = Response.ok(

                    new StreamingOutput() {
                        public void write(OutputStream output) throws IOException, WebApplicationException {
                            try {
                                c.output(output, new PdfSettings());
                            } catch (Docx4JException e) {
                                throw new WebApplicationException(e);
                            }
                        }
                    });
            //                  builder.header("Content-Disposition", "attachment; filename=output.pdf");
            builder.type("application/pdf");

            return builder.build();

        } else if (format.equals("docx")) {

            // fall through to the below

        } else {
            log.error("Unkown format: " + format);
            return Response.ok("<p>Unknown format " + format + " </p>", MediaType.APPLICATION_XHTML_XML_TYPE)
                    .build();

        }
    }

    // return a docx
    ResponseBuilder builder = Response.ok(

            new StreamingOutput() {
                public void write(OutputStream output) throws IOException, WebApplicationException {
                    try {
                        saver.save(output);
                    } catch (Docx4JException e) {
                        throw new WebApplicationException(e);
                    }
                }
            });
    builder.header("Content-Disposition", "attachment; filename=" + filePrefix + ".docx");
    builder.type("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    return builder.build();

}

From source file:org.leo.benchmark.Benchmark.java

/**
 * @param collectionClass/* w  w w  . j  a v  a 2  s.  c  om*/
 * @throws NoSuchMethodException
 * @throws SecurityException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void runMemoryBench(List<Class<? extends Collection>> collectionClasses) {
    for (Class<? extends Collection> clazz : collectionClasses) {
        try {
            // run some gc
            heavyGc();
            long usedMemory = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
            Constructor<? extends Collection> constructor = clazz.getDeclaredConstructor((Class<?>[]) null);
            constructor.setAccessible(true);
            // do the test on 100 objects, to be more accurate
            for (int i = 0; i < 100; i++) {
                this.collection = (Collection<String>) constructor.newInstance();
                // polulate
                collection.addAll(defaultCtx);
                warmUp();
            }
            // measure size
            long objectSize = (long) ((ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()
                    - usedMemory) / 100f);
            System.out.println(clazz.getCanonicalName() + " Object size : " + objectSize + " bytes");
            memoryResults.put((Class<? extends Collection<?>>) clazz, objectSize);
            collection.clear();
            collection = null;
        } catch (Exception e) {
            System.err.println("Failed running benchmark on class " + clazz.getCanonicalName());
            e.printStackTrace();
        }
    }
}

From source file:org.apache.openjpa.enhance.PCSubclassValidator.java

public void assertCanSubclass() {
    Class superclass = meta.getDescribedType();
    String name = superclass.getName();
    if (superclass.isInterface())
        addError(loc.get("subclasser-no-ifaces", name), meta);
    if (Modifier.isFinal(superclass.getModifiers()))
        addError(loc.get("subclasser-no-final-classes", name), meta);
    if (Modifier.isPrivate(superclass.getModifiers()))
        addError(loc.get("subclasser-no-private-classes", name), meta);
    if (PersistenceCapable.class.isAssignableFrom(superclass))
        addError(loc.get("subclasser-super-already-pc", name), meta);

    try {//w ww  .  j  a va 2 s  .  com
        Constructor c = superclass.getDeclaredConstructor(new Class[0]);
        if (!(Modifier.isProtected(c.getModifiers()) || Modifier.isPublic(c.getModifiers())))
            addError(loc.get("subclasser-private-ctor", name), meta);
    } catch (NoSuchMethodException e) {
        addError(loc.get("subclasser-no-void-ctor", name), meta);
    }

    // if the BCClass we loaded is already pc and the superclass is not,
    // then we should never get here, so let's make sure that the
    // calling context is caching correctly by throwing an exception.
    if (pc.isInstanceOf(PersistenceCapable.class) && !PersistenceCapable.class.isAssignableFrom(superclass))
        throw new InternalException(loc.get("subclasser-class-already-pc", name));

    if (AccessCode.isProperty(meta.getAccessType()))
        checkPropertiesAreInterceptable();

    if (errors != null && !errors.isEmpty())
        throw new UserException(errors.toString());
    else if (contractViolations != null && !contractViolations.isEmpty() && log.isWarnEnabled())
        log.warn(contractViolations.toString());
}

From source file:com.adf.bean.AbsBean.java

/**
 * IMPORT/*from   w  w w  . ja  v  a2 s  .  c  om*/
 * */
private void setArrayColumn(String col, JSONArray arr)
        throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
    Field f;
    f = getClass().getDeclaredField(col);
    f.setAccessible(true);
    Class<?> arrCls = f.getType();
    Class<?> objCls = getArrayObjectClass(arrCls);
    if (objCls != null) {
        Object array = Array.newInstance(objCls, arr.length());
        for (int i = 0; i < arr.length(); i++) {
            Object oi = arr.opt(i);
            if (oi.getClass() == objCls) {
                Array.set(array, i, arr.opt(i));
            } else {
                Constructor<?> cons;
                try {
                    cons = objCls.getDeclaredConstructor(String.class);
                    cons.setAccessible(true);
                    Object obj = cons.newInstance(oi.toString());
                    Array.set(array, i, obj);
                } catch (NoSuchMethodException e) {
                    LogUtil.err("setArrayColumn NoSuchMethodException, col " + col + " :" + e.getMessage());
                } catch (InstantiationException e) {
                    LogUtil.err("setArrayColumn InstantiationException, col " + col + " :" + e.getMessage());
                } catch (InvocationTargetException e) {
                    LogUtil.err("setArrayColumn InvocationTargetException, col " + col + " :" + e.getMessage());
                }
            }
        }
        f.set(this, array);
    } else {
        throw new IllegalArgumentException("Can not get Array Column Object class");
    }
}