Example usage for java.lang Thread getContextClassLoader

List of usage examples for java.lang Thread getContextClassLoader

Introduction

In this page you can find the example usage for java.lang Thread getContextClassLoader.

Prototype

@CallerSensitive
public ClassLoader getContextClassLoader() 

Source Link

Document

Returns the context ClassLoader for this thread.

Usage

From source file:com.liferay.portal.search.elasticsearch.internal.connection.EmbeddedElasticsearchConnection.java

protected Node createNode(Settings settings) {
    Thread thread = Thread.currentThread();

    ClassLoader contextClassLoader = thread.getContextClassLoader();

    Class<?> clazz = getClass();

    thread.setContextClassLoader(clazz.getClassLoader());

    String jnaTmpDir = System.getProperty("jna.tmpdir");

    System.setProperty("jna.tmpdir", _jnaTmpDirName);

    try {/* w  ww . j a v a  2s .  c  om*/
        NodeBuilder nodeBuilder = new NodeBuilder();

        nodeBuilder.settings(settings);

        nodeBuilder.local(true);

        Node node = nodeBuilder.build();

        if (elasticsearchConfiguration.syncSearch()) {
            Injector injector = node.injector();

            _replaceTransportRequestHandler(injector.getInstance(TransportService.class),
                    injector.getInstance(SearchService.class));
        }

        return node;
    } finally {
        thread.setContextClassLoader(contextClassLoader);

        if (jnaTmpDir == null) {
            System.clearProperty("jna.tmpdir");
        } else {
            System.setProperty("jna.tmpdir", jnaTmpDir);
        }
    }
}

From source file:org.apache.myfaces.trinidadbuild.plugin.faces.AbstractFacesMojo.java

private ClassLoader createCompileClassLoader(MavenProject project) throws MojoExecutionException {
    Thread current = Thread.currentThread();
    ClassLoader cl = current.getContextClassLoader();

    try {/*  ww  w .jav a2s . c  o m*/
        List classpathElements = project.getCompileClasspathElements();
        if (!classpathElements.isEmpty()) {
            String[] entries = (String[]) classpathElements.toArray(new String[0]);
            URL[] urls = new URL[entries.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(entries[i]).toURL();
            }
            cl = new URLClassLoader(urls, cl);
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error calculating scope classpath", e);
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Error calculating scope classpath", e);
    }

    return cl;
}

From source file:org.opencastproject.authorization.xacml.XACMLAuthorizationService.java

/**
 * {@inheritDoc}/*from   w w w  .  ja  va2  s.  c  om*/
 * 
 * @see org.opencastproject.security.api.AuthorizationService#getAccessControlList(org.opencastproject.mediapackage.MediaPackage)
 */
@SuppressWarnings("unchecked")
@Override
public AccessControlList getAccessControlList(MediaPackage mediapackage) {
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(XACMLAuthorizationService.class.getClassLoader());
        Attachment[] xacmlAttachments = mediapackage.getAttachments(MediaPackageElements.XACML_POLICY);
        URI xacmlUri = null;
        if (xacmlAttachments.length == 0) {
            logger.debug("No XACML attachment found in {}", mediapackage);
            return getFallbackAcl(mediapackage);
        } else if (xacmlAttachments.length > 1) {
            // try to find the source policy. Some may be copies sent to distribution channels.
            for (Attachment a : xacmlAttachments) {
                if (a.getReference() == null) {
                    if (xacmlUri == null) {
                        xacmlUri = a.getURI();
                    } else {
                        logger.warn("More than one non-referenced XACML policy is attached to {}.",
                                mediapackage);
                        return getFallbackAcl(mediapackage);
                    }
                }
            }
            if (xacmlUri == null) {
                logger.warn("Multiple XACML policies are attached to {}, and none seem to be authoritative.",
                        mediapackage);
                return getFallbackAcl(mediapackage);
            }
        } else {
            xacmlUri = xacmlAttachments[0].getURI();
        }
        File xacmlPolicyFile = null;
        try {
            xacmlPolicyFile = workspace.get(xacmlUri);
        } catch (NotFoundException e) {
            logger.warn("XACML policy file not found '{}'.", xacmlUri);
            return getFallbackAcl(mediapackage);
        } catch (IOException e) {
            logger.error("Unable to access XACML policy file. {}", xacmlPolicyFile, e);
            return getFallbackAcl(mediapackage);
        }

        FileInputStream in;
        try {
            in = new FileInputStream(xacmlPolicyFile);
        } catch (FileNotFoundException e) {
            throw new IllegalStateException("Unable to find file in the workspace: " + xacmlPolicyFile);
        }

        PolicyType policy = null;
        try {
            policy = ((JAXBElement<PolicyType>) XACMLUtils.jBossXacmlJaxbContext.createUnmarshaller()
                    .unmarshal(in)).getValue();
        } catch (JAXBException e) {
            throw new IllegalStateException("Unable to unmarshall xacml document" + xacmlPolicyFile);
        } finally {
            IoSupport.closeQuietly(in);
        }
        AccessControlList accessControlList = new AccessControlList();
        List<AccessControlEntry> acl = accessControlList.getEntries();
        for (Object object : policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
            if (object instanceof RuleType) {
                RuleType rule = (RuleType) object;
                if (rule.getTarget() == null) {
                    continue;
                }
                ActionType action = rule.getTarget().getActions().getAction().get(0);
                String actionForAce = (String) action.getActionMatch().get(0).getAttributeValue().getContent()
                        .get(0);
                String role = null;
                JAXBElement<ApplyType> apply = (JAXBElement<ApplyType>) rule.getCondition().getExpression();
                for (JAXBElement<?> element : apply.getValue().getExpression()) {
                    if (element.getValue() instanceof AttributeValueType) {
                        role = (String) ((AttributeValueType) element.getValue()).getContent().get(0);
                        break;
                    }
                }
                if (role == null) {
                    logger.warn("Unable to find a role in rule {}", rule);
                    continue;
                }
                AccessControlEntry ace = new AccessControlEntry(role, actionForAce,
                        rule.getEffect().equals(EffectType.PERMIT));
                acl.add(ace);
            } else {
                logger.debug("Skipping {}", object);
            }
        }
        return accessControlList;
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
}

From source file:org.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.java

/**
 * Overrides the default behaviour to including binding of Grails domain classes.
 *//*  w w w .ja  v  a2 s .  c om*/
@Override
protected void secondPassCompile() throws MappingException {
    final Thread currentThread = Thread.currentThread();
    final ClassLoader originalContextLoader = currentThread.getContextClassLoader();
    if (!configLocked) {
        if (LOG.isDebugEnabled())
            LOG.debug("[GrailsAnnotationConfiguration] [" + domainClasses.size()
                    + "] Grails domain classes to bind to persistence runtime");

        // do Grails class configuration
        DefaultGrailsDomainConfiguration.configureDomainBinder(grailsApplication, domainClasses);

        for (GrailsDomainClass domainClass : domainClasses) {

            final String fullClassName = domainClass.getFullName();

            String hibernateConfig = fullClassName.replace('.', '/') + ".hbm.xml";
            final ClassLoader loader = originalContextLoader;
            // don't configure Hibernate mapped classes
            if (loader.getResource(hibernateConfig) != null)
                continue;

            final Mappings mappings = super.createMappings();
            if (!GrailsHibernateUtil.usesDatasource(domainClass, dataSourceName)) {
                continue;
            }

            LOG.debug("[GrailsAnnotationConfiguration] Binding persistent class [" + fullClassName + "]");

            Mapping m = binder.getMapping(domainClass);
            mappings.setAutoImport(m == null || m.getAutoImport());
            binder.bindClass(domainClass, mappings, sessionFactoryBeanName);
        }
    }

    try {
        currentThread.setContextClassLoader(grailsApplication.getClassLoader());
        super.secondPassCompile();
        createSubclassForeignKeys();
    } finally {
        currentThread.setContextClassLoader(originalContextLoader);
    }

    configLocked = true;
}

From source file:org.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.java

@Override
public SessionFactory buildSessionFactory() throws HibernateException {

    // set the class loader to load Groovy classes
    if (grailsApplication != null) {
        LOG.debug("[GrailsAnnotationConfiguration] Setting context class loader to Grails GroovyClassLoader");
        Thread.currentThread().setContextClassLoader(grailsApplication.getClassLoader());
    }/*from   www.  j a  v  a2 s.  co m*/

    // work around for HHH-2624
    Map<String, Type> empty = new HashMap<String, Type>();
    addFilterDefinition(new FilterDefinition("dynamicFilterEnabler", "1=1", empty));

    SessionFactory sessionFactory = null;

    ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER);
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (appClassLoader != null && !appClassLoader.equals(threadContextClassLoader));
    if (overrideClassLoader) {
        currentThread.setContextClassLoader(appClassLoader);
    }

    try {
        ConfigurationHelper.resolvePlaceHolders(getProperties());

        EventListenerIntegrator eventListenerIntegrator = new EventListenerIntegrator(hibernateEventListeners,
                eventListeners);
        BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder()
                .with(eventListenerIntegrator).build();

        setSessionFactoryObserver(new SessionFactoryObserver() {
            private static final long serialVersionUID = 1;

            public void sessionFactoryCreated(SessionFactory factory) {
            }

            public void sessionFactoryClosed(SessionFactory factory) {
                ((ServiceRegistryImplementor) serviceRegistry).destroy();
            }
        });

        StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder(
                bootstrapServiceRegistry).applySettings(getProperties());
        sessionFactory = super.buildSessionFactory(standardServiceRegistryBuilder.build());
        serviceRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry();
    } finally {
        if (overrideClassLoader) {
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
    }

    if (grailsApplication != null) {
        GrailsHibernateUtil.configureHibernateDomainClasses(sessionFactory, sessionFactoryBeanName,
                grailsApplication);
    }

    return sessionFactory;
}

From source file:org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML1BearerGrantHandler.java

public void init() throws IdentityOAuth2Exception {

    super.init();

    Thread thread = Thread.currentThread();
    ClassLoader loader = thread.getContextClassLoader();
    thread.setContextClassLoader(this.getClass().getClassLoader());

    try {//www.  j a  v  a 2  s.c  om
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        String errorMessage = "Error in bootstrapping the OpenSAML library";
        log.error(errorMessage, e);
        throw new IdentityOAuth2Exception(errorMessage, e);
    } finally {
        thread.setContextClassLoader(loader);
    }

    profileValidator = new SAMLSignatureProfileValidator();

    Properties grantTypeProperties = new Properties();
    InputStream stream = loader.getResourceAsStream("repository/conf/" + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE);
    if (stream != null) {
        try {
            grantTypeProperties.load(stream);
            audienceRestrictionValidationEnabled = Boolean
                    .parseBoolean(grantTypeProperties.getProperty("audienceRestrictionValidationEnabled"));
            if (log.isDebugEnabled()) {
                log.debug("Audience restriction validation enabled is set to "
                        + audienceRestrictionValidationEnabled);
            }
        } catch (IOException e) {
            log.warn(
                    "Failed to load the SAML-1.0-BearerGrantType.properties stream. The default configurations are "
                            + "used instead of configurations defined in "
                            + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE + " file.");
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                log.warn("Failed to close the input stream of " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE, e);
            }
        }

    }
}

From source file:org.apache.hadoop.hbase.coprocessor.CoprocessorHost.java

/**
 * Load a coprocessor implementation into the host
 * @param path path to implementation jar
 * @param className the main class name/*from   w  ww  .j ava2  s  . c  om*/
 * @param priority chaining priority
 * @param conf configuration for coprocessor
 * @throws java.io.IOException Exception
 */
public E load(Path path, String className, int priority, Configuration conf) throws IOException {
    Class<?> implClass = null;
    LOG.debug("Loading coprocessor class " + className + " with path " + path + " and priority " + priority);

    ClassLoader cl = null;
    if (path == null) {
        try {
            implClass = getClass().getClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new IOException("No jar path specified for " + className);
        }
    } else {
        cl = CoprocessorClassLoader.getClassLoader(path, getClass().getClassLoader(), pathPrefix, conf);
        try {
            implClass = cl.loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new IOException("Cannot load external coprocessor class " + className, e);
        }
    }

    //load custom code for coprocessor
    Thread currentThread = Thread.currentThread();
    ClassLoader hostClassLoader = currentThread.getContextClassLoader();
    try {
        // switch temporarily to the thread classloader for custom CP
        currentThread.setContextClassLoader(cl);
        E cpInstance = loadInstance(implClass, priority, conf);
        return cpInstance;
    } finally {
        // restore the fresh (host) classloader
        currentThread.setContextClassLoader(hostClassLoader);
    }
}

From source file:org.apache.solr.handler.clustering.carrot2.CarrotClusteringEngine.java

@Override
public Object cluster(Query query, SolrDocumentList solrDocList, Map<SolrDocument, Integer> docIds,
        SolrQueryRequest sreq) {//from   www .  j  a  v a2 s  . c  om
    try {
        // Prepare attributes for Carrot2 clustering call
        Map<String, Object> attributes = new HashMap<>();
        List<Document> documents = getDocuments(solrDocList, docIds, query, sreq);
        attributes.put(AttributeNames.DOCUMENTS, documents);
        attributes.put(AttributeNames.QUERY, query.toString());

        // Pass the fields on which clustering runs.
        attributes.put("solrFieldNames", getFieldsForClustering(sreq));

        // Pass extra overriding attributes from the request, if any
        extractCarrotAttributes(sreq.getParams(), attributes);

        // Perform clustering and convert to an output structure of clusters.
        //
        // Carrot2 uses current thread's context class loader to get
        // certain classes (e.g. custom tokenizer/stemmer) at runtime.
        // To make sure classes from contrib JARs are available,
        // we swap the context class loader for the time of clustering.
        Thread ct = Thread.currentThread();
        ClassLoader prev = ct.getContextClassLoader();
        try {
            ct.setContextClassLoader(core.getResourceLoader().getClassLoader());
            return clustersToNamedList(controller.process(attributes, clusteringAlgorithmClass).getClusters(),
                    sreq.getParams());
        } finally {
            ct.setContextClassLoader(prev);
        }
    } catch (Exception e) {
        log.error("Carrot2 clustering failed", e);
        throw new SolrException(ErrorCode.SERVER_ERROR, "Carrot2 clustering failed", e);
    }
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

private static LoginContext newLoginContext(String appName, Subject subject,
        javax.security.auth.login.Configuration loginConf) throws LoginException {
    // Temporarily switch the thread's ContextClassLoader to match this
    // class's classloader, so that we can properly load HadoopLoginModule
    // from the JAAS libraries.
    Thread t = Thread.currentThread();
    ClassLoader oldCCL = t.getContextClassLoader();
    t.setContextClassLoader(HadoopLoginModule.class.getClassLoader());
    try {/* w  w w .  java 2 s  .c om*/
        return new LoginContext(appName, subject, null, loginConf);
    } finally {
        t.setContextClassLoader(oldCCL);
    }
}

From source file:org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java

public void afterPropertiesSet() throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader cl = thread.getContextClassLoader();
    try {//  w  w  w  . j  av a2s  . c o m
        thread.setContextClassLoader(classLoader);
        buildSessionFactory();
    } finally {
        thread.setContextClassLoader(cl);
    }
}