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:org.wso2.carbon.server.admin.service.ServerAdmin.java

public boolean restartGracefully() throws Exception {
    //        checkStandaloneMode();
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {// w w  w  . ja v a  2  s .  com
        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.restartGracefully();
                } catch (Exception e) {
                    String msg = "Cannot restart 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 shutdown() throws AxisFault {
    //        checkStandaloneMode();
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {//from  ww  w. ja  va2  s  . co  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.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 ww  . j  ava 2s  . com
        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:com.liferay.portal.jsonwebservice.JSONWebServiceConfigurator.java

public void configure(ClassLoader classLoader) throws PortalException, SystemException {

    File[] classPathFiles = null;

    if (classLoader != null) {
        URL servicePropertiesURL = classLoader.getResource("service.properties");

        String servicePropertiesPath = null;

        try {/*from   w w  w . ja  v a  2  s .c  o m*/
            servicePropertiesPath = URLDecoder.decode(servicePropertiesURL.getPath(), StringPool.UTF8);
        } catch (UnsupportedEncodingException uee) {
            throw new SystemException(uee);
        }

        File classPathFile = null;

        File libDir = null;

        int pos = servicePropertiesPath.indexOf("_wl_cls_gen.jar!");

        if (pos != -1) {
            String wlClsGenJarPath = servicePropertiesPath.substring(0, pos + 15);

            classPathFile = new File(wlClsGenJarPath);

            libDir = new File(classPathFile.getParent());
        } else {
            File servicePropertiesFile = new File(servicePropertiesPath);

            classPathFile = servicePropertiesFile.getParentFile();

            libDir = new File(classPathFile.getParent(), "lib");
        }

        classPathFiles = new File[2];

        classPathFiles[0] = classPathFile;

        FindFile findFile = new WildcardFindFile("*-portlet-service*.jar");

        findFile.searchPath(libDir);

        classPathFiles[1] = findFile.nextFile();

        if (classPathFiles[1] == null) {
            File classesDir = new File(libDir.getParent(), "classes");

            classPathFiles[1] = classesDir;
        }
    } else {
        Thread currentThread = Thread.currentThread();

        classLoader = currentThread.getContextClassLoader();

        File portalImplJarFile = new File(PortalUtil.getPortalLibDir(), "portal-impl.jar");
        File portalServiceJarFile = new File(PortalUtil.getGlobalLibDir(), "portal-service.jar");

        if (portalImplJarFile.exists() && portalServiceJarFile.exists()) {
            classPathFiles = new File[2];

            classPathFiles[0] = portalImplJarFile;
            classPathFiles[1] = portalServiceJarFile;
        } else {
            classPathFiles = ClassLoaderUtil.getDefaultClasspath(classLoader);
        }
    }

    _classLoader = classLoader;

    _configure(classPathFiles);
}

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

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 *//*from w  w  w  . j  a v a  2 s .c  om*/
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: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//from ww w. ja  v  a  2  s. co  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.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 a2 s  . c o  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 w w w  .j a v  a2s  . c  om*/
 * 
 * @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}//from w  w  w .  j av  a  2s . c  o m
 * 
 * @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);
    }
}