Example usage for java.lang Thread setContextClassLoader

List of usage examples for java.lang Thread setContextClassLoader

Introduction

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

Prototype

public void setContextClassLoader(ClassLoader cl) 

Source Link

Document

Sets the context ClassLoader for this Thread.

Usage

From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java

public boolean shutdown() throws AxisFault {
    //        checkStandaloneMode();
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {/*from   w  w  w.jav a2 s .  c om*/
        thread.setContextClassLoader(dataHolder.getRestartThreadContextClassloader());
        ConfigurationContext configurationContext = getConfigContext();
        final Controllable controllable = (Controllable) configurationContext
                .getProperty(ServerConstants.CARBON_INSTANCE);
        Thread th = new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    controllable.shutdown();
                } catch (Exception e) {
                    String msg = "Cannot shutdown server";
                    log.error(msg, e);
                    throw new RuntimeException(msg, e);
                }
            }
        };
        th.start();
        invalidateSession();
    } finally {
        thread.setContextClassLoader(originalClassloader);
    }
    return true;
}

From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java

public boolean shutdownGracefully() throws AxisFault {
    //        checkStandaloneMode();
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {/*from w w w.  j  a v  a 2  s . c o m*/
        thread.setContextClassLoader(dataHolder.getRestartThreadContextClassloader());
        ConfigurationContext configurationContext = getConfigContext();
        final Controllable controllable = (Controllable) configurationContext
                .getProperty(ServerConstants.CARBON_INSTANCE);
        Thread th = new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    controllable.shutdownGracefully();
                } catch (Exception e) {
                    String msg = "Cannot gracefully shutdown server";
                    log.error(msg, e);
                    throw new RuntimeException(msg, e);
                }
            }
        };
        th.start();
        invalidateSession();
    } finally {
        thread.setContextClassLoader(originalClassloader);
    }
    return true;
}

From source file:org.springframework.boot.context.embedded.tomcat.TomcatWebServer.java

private void startDaemonAwaitThread() {
    Thread awaitThread = new Thread("container-" + (containerCounter.get())) {

        @Override//from  w  w w .ja v  a 2 s.  c  o m
        public void run() {
            TomcatWebServer.this.tomcat.getServer().await();
        }

    };
    awaitThread.setContextClassLoader(getClass().getClassLoader());
    awaitThread.setDaemon(false);
    awaitThread.start();
}

From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java

@Override
public String mapInternalIdentifier(String externalId, String providerKey, String providerId)
        throws RepositoryException {
    UuidMapping uuidMapping = new UuidMapping();
    uuidMapping.setExternalId(externalId);
    uuidMapping.setProviderKey(providerKey);
    uuidMapping/*w w w  . ja v a 2s  .  c o m*/
            .setInternalUuid(providerId + "-" + StringUtils.substringAfter(UUID.randomUUID().toString(), "-"));
    org.hibernate.Session session = null;
    Thread currentThread = Thread.currentThread();
    ClassLoader previousClassLoader = currentThread.getContextClassLoader();
    currentThread.setContextClassLoader(this.getClass().getClassLoader());
    try {
        session = getHibernateSessionFactory().openSession();
        session.beginTransaction();
        session.save(uuidMapping);
        session.getTransaction().commit();

        // cache it
        getIdentifierCache().put(new Element(getCacheKey(externalId.hashCode(), providerKey),
                uuidMapping.getInternalUuid(), true));
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(
                "Error storing mapping for external node " + externalId + " [provider: " + providerKey + "]",
                e);
    } finally {
        if (session != null) {
            session.close();
        }
        currentThread.setContextClassLoader(previousClassLoader);
    }

    return uuidMapping.getInternalUuid();
}

From source file:org.codehaus.mojo.hibernate3.HibernateExporterMojo.java

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 *///from   w ww  .  j a  v a  2  s .  co  m
public void execute() throws MojoExecutionException, MojoFailureException {
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();

    try {
        currentThread.setContextClassLoader(getClassLoader());
        if (getComponentProperty("skip", false)) {
            getLog().info("skipping hibernate3 execution");
        } else {
            doExecute();
        }
    } finally {
        currentThread.setContextClassLoader(oldClassLoader);
    }
}

From source file:com.thinkbiganalytics.spark.repl.SparkScriptEngine.java

/**
 * Executes the specified callable after replacing the current context class loader.
 *
 * <p>This is a work-around to avoid {@link ClassCastException} issues caused by conflicts between Hadoop and Kylo Spark Shell. Spark uses the context class loader when loading Hadoop components
 * for running Spark on YARN. When both Hadoop and Kylo Spark Shell provide the same class then both classes are loaded when creating a {@link SparkContext}. The fix is to set the context class
 * loader to the same class loader that was used to load the {@link SparkContext} class.</p>
 *
 * @param callable the function to be executed
 * @param <T>      the return type
 * @return the return value/*from  w w w.  ja  v  a 2  s  . c o  m*/
 */
private <T> T executeWithSparkClassLoader(@Nonnull final Callable<T> callable) {
    // Set context class loader
    final Thread currentThread = Thread.currentThread();
    final ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    final ClassLoader sparkClassLoader = new ForwardingClassLoader(SparkContext.class.getClassLoader(),
            contextClassLoader);
    currentThread.setContextClassLoader(sparkClassLoader);

    // Execute callable
    try {
        return callable.call();
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    } finally {
        // Reset context class loader
        currentThread.setContextClassLoader(contextClassLoader);
    }
}

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

@Override
public void init() throws IdentityOAuth2Exception {

    super.init();

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

    try {/*from w  w  w . ja v  a 2 s .  co m*/
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        log.error("Error in bootstrapping the OpenSAML2 library", e);
        throw new IdentityOAuth2Exception("Error in bootstrapping the OpenSAML2 library");
    } finally {
        thread.setContextClassLoader(loader);
    }

    profileValidator = new SAMLSignatureProfileValidator();
}

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

/**
 * {@inheritDoc}/*from   ww w.  j a v a 2 s .com*/
 * 
 * @see org.opencastproject.security.api.SecurityService#setAccessControl(org.opencastproject.mediapackage.MediaPackage,
 *      java.util.Set)
 */
@Override
public MediaPackage setAccessControl(MediaPackage mediapackage, AccessControlList acl)
        throws MediaPackageException {
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(XACMLAuthorizationService.class.getClassLoader());
        if (acl == null) {
            logger.debug("No ACL specified: no XACML attachment will be added to mediapackage '{}'",
                    mediapackage);
            return mediapackage;
        }
        // Get XACML representation of these role + action tuples
        String xacmlContent = null;
        try {
            xacmlContent = XACMLUtils.getXacml(mediapackage, acl);
        } catch (JAXBException e) {
            throw new MediaPackageException(
                    "Unable to generate xacml for mediapackage " + mediapackage.getIdentifier());
        }

        // Remove the old xacml file(s)
        Attachment attachment = null;
        for (Attachment a : mediapackage.getAttachments(XACML_POLICY)) {
            attachment = (Attachment) a.clone();
            try {
                workspace.delete(a.getURI());
            } catch (Exception e) {
                logger.warn("Unable to delete previous xacml file: {}", e);
            }
            mediapackage.remove(a);
        }

        // add attachment
        URI uri = workspace.getURI(mediapackage.getIdentifier().toString(), XACML_ELEMENT_ID, XACML_FILENAME);
        if (attachment == null) {
            attachment = (Attachment) MediaPackageElementBuilderFactory.newInstance().newElementBuilder()
                    .elementFromURI(uri, Attachment.TYPE, XACML_POLICY);
        }
        attachment.setIdentifier(XACML_ELEMENT_ID);
        mediapackage.add(attachment);

        try {
            workspace.put(mediapackage.getIdentifier().toString(), attachment.getIdentifier(), XACML_FILENAME,
                    IOUtils.toInputStream(xacmlContent));
        } catch (IOException e) {
            throw new MediaPackageException(
                    "Can not store xacml for mediapackage " + mediapackage.getIdentifier());
        }
        attachment.setURI(uri);

        // return augmented mediapackage
        return mediapackage;
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
}

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

/**
 * {@inheritDoc}/* ww w. j  a va2s.c  om*/
 * 
 * @see org.opencastproject.security.api.AuthorizationService#hasPermission(org.opencastproject.mediapackage.MediaPackage,
 *      java.lang.String)
 */
@Override
public boolean hasPermission(MediaPackage mediapackage, String action) {
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(XACMLAuthorizationService.class.getClassLoader());
        Attachment[] xacmlAttachments = mediapackage.getAttachments(MediaPackageElements.XACML_POLICY);
        if (xacmlAttachments.length == 0) {
            logger.info("No XACML attachment found in {}", mediapackage);
            return true;
        } else if (xacmlAttachments.length > 1) {
            logger.warn("More than one XACML policy is attached to {}", mediapackage);
            return false;
        }
        File xacmlPolicyFile = null;
        try {
            xacmlPolicyFile = workspace.get(xacmlAttachments[0].getURI());
        } catch (NotFoundException e) {
            logger.warn("XACML policy file not found", e);
        } catch (IOException e) {
            logger.warn("Unable to access XACML policy file {}", xacmlPolicyFile, e);
        }

        RequestContext requestCtx = RequestResponseContextFactory.createRequestCtx();

        User user = securityService.getUser();

        // Create a subject type
        SubjectType subject = new SubjectType();
        subject.getAttribute().add(RequestAttributeFactory.createStringAttributeType(
                XACMLUtils.SUBJECT_IDENTIFIER, XACMLUtils.ISSUER, user.getUserName()));
        for (String role : user.getRoles()) {
            AttributeType attSubjectID = RequestAttributeFactory
                    .createStringAttributeType(XACMLUtils.SUBJECT_ROLE_IDENTIFIER, XACMLUtils.ISSUER, role);
            subject.getAttribute().add(attSubjectID);
        }

        // Create a resource type
        URI uri = null;
        try {
            uri = new URI(mediapackage.getIdentifier().toString());
        } catch (URISyntaxException e) {
            logger.warn("Unable to represent mediapackage identifier '{}' as a URI",
                    mediapackage.getIdentifier().toString());
        }
        org.jboss.security.xacml.core.model.context.ResourceType resourceType = new org.jboss.security.xacml.core.model.context.ResourceType();
        resourceType.getAttribute().add(RequestAttributeFactory
                .createAnyURIAttributeType(XACMLUtils.RESOURCE_IDENTIFIER, XACMLUtils.ISSUER, uri));

        // Create an action type
        org.jboss.security.xacml.core.model.context.ActionType actionType = new org.jboss.security.xacml.core.model.context.ActionType();
        actionType.getAttribute().add(RequestAttributeFactory
                .createStringAttributeType(XACMLUtils.ACTION_IDENTIFIER, XACMLUtils.ISSUER, action));

        // Create a Request Type
        RequestType requestType = new RequestType();
        requestType.getSubject().add(subject);
        requestType.getResource().add(resourceType);
        requestType.setAction(actionType);
        try {
            requestCtx.setRequest(requestType);
        } catch (IOException e) {
            logger.warn("Unable to set the xacml request type", e);
            return false;
        }

        PolicyDecisionPoint pdp = getPolicyDecisionPoint(xacmlPolicyFile);

        return pdp.evaluate(requestCtx).getDecision() == XACMLConstants.DECISION_PERMIT;
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
}