Example usage for java.security AccessController doPrivileged

List of usage examples for java.security AccessController doPrivileged

Introduction

In this page you can find the example usage for java.security AccessController doPrivileged.

Prototype

@CallerSensitive
public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException 

Source Link

Document

Performs the specified PrivilegedExceptionAction with privileges enabled.

Usage

From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java

private void preloadLibraries() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            Security.addProvider(new BouncyCastleProvider());
            return null;
        }/*  w  w  w . jav a2  s . c  om*/
    });
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

/**
 * Forward this request and response to another resource for processing.
 * Any runtime exception, IOException, or ServletException thrown by the
 * called servlet will be propogated to the caller.
 *
 * @param request The servlet request to be forwarded
 * @param response The servlet response to be forwarded
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *///from   w w  w .  ja  v a 2 s .  c  o  m
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (System.getSecurityManager() != null) {
        try {
            PrivilegedForward dp = new PrivilegedForward(request, response);
            AccessController.doPrivileged(dp);
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();
            if (e instanceof ServletException)
                throw (ServletException) e;
            throw (IOException) e;
        }
    } else {
        doForward(request, response);
    }
}

From source file:org.apache.jk.server.JkCoyoteHandler.java

private void appendHead(org.apache.coyote.Response res) throws IOException {
    if (log.isDebugEnabled())
        log.debug("COMMIT sending headers " + res + " " + res.getMimeHeaders());

    C2BConverter c2b = (C2BConverter) res.getNote(utfC2bNote);
    if (c2b == null) {
        if (System.getSecurityManager() != null) {
            try {
                c2b = (C2BConverter) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws IOException {
                        return new C2BConverter("UTF8");
                    }//from   w  w  w.  j a  v  a  2s.c  o  m
                });
            } catch (PrivilegedActionException pae) {
                Exception ex = pae.getException();
                if (ex instanceof IOException)
                    throw (IOException) ex;
            }
        } else {
            c2b = new C2BConverter("UTF8");
        }
        res.setNote(utfC2bNote, c2b);
    }

    MsgContext ep = (MsgContext) res.getNote(epNote);
    MsgAjp msg = (MsgAjp) ep.getNote(headersMsgNote);
    msg.reset();
    msg.appendByte(HandlerRequest.JK_AJP13_SEND_HEADERS);
    msg.appendInt(res.getStatus());

    MessageBytes mb = (MessageBytes) ep.getNote(tmpMessageBytesNote);
    if (mb == null) {
        mb = new MessageBytes();
        ep.setNote(tmpMessageBytesNote, mb);
    }
    String message = res.getMessage();
    if (message == null) {
        if (System.getSecurityManager() != null) {
            message = (String) AccessController.doPrivileged(new StatusLinePrivilegedAction(res.getStatus()));
        } else {
            message = HttpMessages.getMessage(res.getStatus());
        }
    } else {
        message = message.replace('\n', ' ').replace('\r', ' ');
    }
    mb.setString(message);
    c2b.convert(mb);
    msg.appendBytes(mb);

    // XXX add headers

    MimeHeaders headers = res.getMimeHeaders();
    String contentType = res.getContentType();
    if (contentType != null) {
        headers.setValue("Content-Type").setString(contentType);
    }
    String contentLanguage = res.getContentLanguage();
    if (contentLanguage != null) {
        headers.setValue("Content-Language").setString(contentLanguage);
    }
    int contentLength = res.getContentLength();
    if (contentLength >= 0) {
        headers.setValue("Content-Length").setInt(contentLength);
    }
    int numHeaders = headers.size();
    msg.appendInt(numHeaders);
    for (int i = 0; i < numHeaders; i++) {
        MessageBytes hN = headers.getName(i);
        // no header to sc conversion - there's little benefit
        // on this direction
        c2b.convert(hN);
        msg.appendBytes(hN);

        MessageBytes hV = headers.getValue(i);
        c2b.convert(hV);
        msg.appendBytes(hV);
    }
    ep.setType(JkHandler.HANDLE_SEND_PACKET);
    ep.getSource().invoke(msg, ep);
}

From source file:org.codice.ddf.commands.catalog.ExportCommand.java

private void signJar(File outputFile) {
    SecurityLogger.audit("Signing exported data. file: [{}]", outputFile.getName());
    console.println("Signing zip file...");
    Instant start = Instant.now();

    try (InputStream inputStream = new FileInputStream(outputFile)) {
        String alias = AccessController
                .doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SystemBaseUrl.EXTERNAL_HOST));
        String password = AccessController.doPrivileged(
                (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword"));

        byte[] signature = signer.createDigitalSignature(inputStream, alias, password);

        if (signature != null) {
            String signatureFilepath = Paths.get(System.getProperty("ddf.home"), FILE_NAMER.apply("sig"))
                    .toString();/*  w  w w .  j  a va 2 s. c om*/
            FileUtils.writeByteArrayToFile(new File(signatureFilepath), signature);

            console.println("zip file signed in: " + getFormattedDuration(start));
        } else {
            console.println("An error occurred while signing export");
        }
    } catch (CatalogCommandRuntimeException | IOException e) {
        String message = "Unable to sign export of data";
        LOGGER.debug(message, e);
        console.println(message);
    }
}

From source file:org.apache.cxf.common.logging.LogUtils.java

private static ClassLoader getClassLoader(final Class<?> clazz) {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return clazz.getClassLoader();
            }//w  ww  .  j  a v a  2  s . com
        });
    }
    return clazz.getClassLoader();
}

From source file:org.apache.struts2.jasper.runtime.PageContextImpl.java

public int getAttributesScope(final String name) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//from   w  w  w.  j av  a 2s.c om

    if (SecurityUtil.isPackageProtectionEnabled()) {
        return ((Integer) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new Integer(doGetAttributeScope(name));
            }
        })).intValue();
    } else {
        return doGetAttributeScope(name);
    }
}

From source file:org.apache.jasper.runtime.PageContextImpl.java

public void setAttribute(final String name, final Object o, final int scope) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//from   w w  w. j  ava  2 s.  co  m

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doSetAttribute(name, o, scope);
                return null;
            }
        });
    } else {
        doSetAttribute(name, o, scope);
    }

}

From source file:org.commonjava.sshwrap.config.DefaultSSHConfiguration.java

static String userName() {
    return AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override//from ww  w .j a  va2s  .co m
        public String run() {
            return System.getProperty("user.name");
        }
    });
}

From source file:org.apache.openjpa.persistence.PersistenceProductDerivation.java

/**
 * Looks through the resources at <code>rsrc</code> for a configuration
 * file that matches <code>name</code> (or an unnamed one if
 * <code>name</code> is <code>null</code>), and loads the XML in the
 * resource into a new {@link PersistenceUnitInfo}. Then, applies the
 * overrides in <code>m</code>.
 *
 * @return {@link Boolean#TRUE} if the resource was loaded, null if it
 * does not exist, or {@link Boolean#FALSE} if it is not for OpenJPA
 *//*from   w  w w .j a  v a 2 s  . c om*/
private Boolean load(ConfigurationProviderImpl cp, String rsrc, String name, Map m, ClassLoader loader,
        boolean explicit) throws IOException {
    if (loader == null)
        loader = (ClassLoader) AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());

    List<URL> urls = getResourceURLs(rsrc, loader);
    if (urls == null || urls.size() == 0)
        return null;

    ConfigurationParser parser = new ConfigurationParser(m);
    PersistenceUnitInfoImpl pinfo = parseResources(parser, urls, name, loader);
    if (pinfo == null) {
        if (!explicit)
            return Boolean.FALSE;
        throw new MissingResourceException(
                _loc.get("missing-xml-config", rsrc, String.valueOf(name)).getMessage(), getClass().getName(),
                rsrc);
    } else if (!isOpenJPAPersistenceProvider(pinfo, loader)) {
        if (!explicit) {
            warnUnknownProvider(pinfo);
            return Boolean.FALSE;
        }
        throw new MissingResourceException(
                _loc.get("unknown-provider", rsrc, name, pinfo.getPersistenceProviderClassName()).getMessage(),
                getClass().getName(), rsrc);
    }
    cp.addProperties(pinfo.toOpenJPAProperties());
    cp.setSource(pinfo.getPersistenceXmlFileUrl().toString());
    return Boolean.TRUE;
}

From source file:com.scaleoutsoftware.soss.hserver.hadoop.DistributedCacheManager.java

/**
 * Creates a class loader that includes the designated
 * files and archives.//  ww  w  .jav a 2s .  c  o m
 */
public ClassLoader makeClassLoader(final ClassLoader parent) throws MalformedURLException {
    final URL[] urls = new URL[localClasspaths.size()];
    for (int i = 0; i < localClasspaths.size(); ++i) {
        urls[i] = new File(localClasspaths.get(i)).toURI().toURL();
        LOG.info(urls[i]);
    }
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(urls, parent);
        }
    });
}