Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

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

Prototype

PrivilegedAction

Source Link

Usage

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.event.EventAdminDispatcher.java

public void afterClose(final BlueprintEvent event) {
    if (dispatcher != null) {
        try {//from w ww .ja va2s .c  o m
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        dispatcher.afterClose(event);
                        return null;
                    }
                });
            } else {
                dispatcher.afterClose(event);
            }
        } catch (Throwable th) {
            log.warn("Cannot dispatch event " + event, th);
        }
    }
}

From source file:org.apache.ranger.admin.client.RangerAdminRESTClient.java

@Override
public ServicePolicies getServicePoliciesIfUpdated(final long lastKnownVersion,
        final long lastActivationTimeInMillis) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", "
                + lastActivationTimeInMillis + ")");
    }//  w  ww .  j  a v a2 s  .  c o m

    ServicePolicies ret = null;
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();

    ClientResponse response = null;
    if (isSecureMode) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking Service policy if updated as user : " + user);
        }
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {
            public ClientResponse run() {
                WebResource secureWebResource = createWebResource(
                        RangerRESTUtils.REST_URL_POLICY_GET_FOR_SECURE_SERVICE_IF_UPDATED + serviceName)
                                .queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION,
                                        Long.toString(lastKnownVersion))
                                .queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME,
                                        Long.toString(lastActivationTimeInMillis))
                                .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
                return secureWebResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
            };
        };
        response = user.doAs(action);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking Service policy if updated with old api call");
        }
        WebResource webResource = createWebResource(
                RangerRESTUtils.REST_URL_POLICY_GET_FOR_SERVICE_IF_UPDATED + serviceName)
                        .queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION,
                                Long.toString(lastKnownVersion))
                        .queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME,
                                Long.toString(lastActivationTimeInMillis))
                        .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
        response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
    }

    if (response != null && response.getStatus() == 200) {
        ret = response.getEntity(ServicePolicies.class);
    } else if (!(response != null && response.getStatus() == 304)) {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.error("Error getting policies. secureMode=" + isSecureMode + ", user=" + user + ", response="
                + resp.toString() + ", serviceName=" + serviceName);

        throw new Exception(resp.getMessage());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", "
                + lastActivationTimeInMillis + "): " + ret);
    }

    return ret;
}

From source file:org.apache.ranger.audit.provider.kafka.KafkaAuditProvider.java

@Override
public boolean log(AuditEventBase event) {
    if (event instanceof AuthzAuditEvent) {
        AuthzAuditEvent authzEvent = (AuthzAuditEvent) event;

        if (authzEvent.getAgentHostname() == null) {
            authzEvent.setAgentHostname(MiscUtil.getHostname());
        }//from   w w  w .j  a  v a 2 s .  c  o  m

        if (authzEvent.getLogType() == null) {
            authzEvent.setLogType("RangerAudit");
        }

        if (authzEvent.getEventId() == null) {
            authzEvent.setEventId(MiscUtil.generateUniqueId());
        }
    }

    String message = MiscUtil.stringify(event);
    try {

        if (producer != null) {
            // TODO: Add partition key
            final ProducerRecord<String, String> keyedMessage = new ProducerRecord<String, String>(topic,
                    message);

            MiscUtil.executePrivilegedAction(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    producer.send(keyedMessage);
                    return null;
                };
            });

        } else {
            LOG.info("AUDIT LOG (Kafka Down):" + message);
        }
    } catch (Throwable t) {
        LOG.error("Error sending message to Kafka topic. topic=" + topic + ", message=" + message, t);
        return false;
    }
    return true;
}

From source file:org.apache.axis2.util.Utils.java

private static ClassLoader getContextClassLoader_DoPriv() {
    return (ClassLoader) org.apache.axis2.java.security.AccessController
            .doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }/*from w w w . ja v  a  2s .c  o  m*/
            });
}

From source file:org.apache.axis2.datasource.jaxb.JAXBAttachmentMarshaller.java

public String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String namespace,
        String localPart) {/*from  w  w  w.j a v  a 2s.  c  o  m*/

    if (offset != 0 || length != data.length) {
        int len = length - offset;
        byte[] newData = new byte[len];
        System.arraycopy(data, offset, newData, 0, len);
        data = newData;
    }

    if (mimeType == null || mimeType.length() == 0) {
        mimeType = APPLICATION_OCTET;
    }

    if (log.isDebugEnabled()) {
        log.debug("Adding MTOM/XOP byte array attachment for element: " + "{" + namespace + "}" + localPart);
    }

    String cid = null;

    try {
        // Create MIME Body Part
        final InternetHeaders ih = new InternetHeaders();
        final byte[] dataArray = data;
        ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeType);
        final MimeBodyPart mbp = (MimeBodyPart) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    return new MimeBodyPart(ih, dataArray);
                } catch (MessagingException e) {
                    throw new OMException(e);
                }
            }
        });

        //Create a data source for the MIME Body Part
        MimePartDataSource mpds = (MimePartDataSource) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new MimePartDataSource(mbp);
            }
        });
        long dataLength = data.length;
        Integer value = null;
        if (msgContext != null) {
            value = (Integer) msgContext.getProperty(Constants.Configuration.MTOM_THRESHOLD);
        } else if (log.isDebugEnabled()) {
            log.debug(
                    "The msgContext is null so the MTOM threshold value can not be determined; it will default to 0.");
        }

        int optimizedThreshold = (value != null) ? value.intValue() : 0;

        if (optimizedThreshold == 0 || dataLength > optimizedThreshold) {
            DataHandler dataHandler = new DataHandler(mpds);
            cid = addDataHandler(dataHandler, false);
        }

        // Add the content id to the mime body part
        mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
    } catch (MessagingException e) {
        throw new OMException(e);
    }

    return cid == null ? null : "cid:" + cid;
}

From source file:org.mobicents.slee.runtime.sbb.SbbObjectPoolFactory.java

/**
 * Create a new instance of this object and set the SbbContext This places
 * it into the object pool./*www  . j av  a2 s. c  om*/
 */
public Object makeObject() {

    SbbObject retval;
    if (doTraceLogs) {
        logger.trace("makeObject() for " + serviceID + " and " + sbbComponent);
    }

    final ClassLoader oldClassLoader = SleeContainerUtils.getCurrentThreadClassLoader();

    try {
        final ClassLoader cl = sbbComponent.getClassLoader();
        if (System.getSecurityManager() != null)
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(cl);
                    return null;

                }
            });
        else
            Thread.currentThread().setContextClassLoader(cl);

        retval = new SbbObjectImpl(serviceID, sbbComponent);

    } finally {
        if (System.getSecurityManager() != null)
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                    return null;
                }
            });
        else
            Thread.currentThread().setContextClassLoader(oldClassLoader);
    }

    retval.setState(SbbObjectState.POOLED);

    return retval;
}

From source file:org.apache.hadoop.hdfs.server.namenode.ha.BootstrapStandby.java

@Override
public int run(String[] args) throws Exception {
    parseArgs(args);//ww w . ja  v a 2s  .  co  m
    parseConfAndFindOtherNN();
    NameNode.checkAllowFormat(conf);

    InetSocketAddress myAddr = NameNode.getAddress(conf);
    SecurityUtil.login(conf, DFS_NAMENODE_KEYTAB_FILE_KEY, DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY,
            myAddr.getHostName());

    return SecurityUtil.doAsLoginUserOrFatal(new PrivilegedAction<Integer>() {
        @Override
        public Integer run() {
            try {
                return doRun();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:org.pentaho.di.trans.ael.websocket.SessionConfigurator.java

private Header getAuthenticationHeader(URI uri) throws RuntimeException {
    try {//  w  w w. j a  v  a2s  .  com
        ClientLoginConfig loginConfig = new ClientLoginConfig(this.keytab, this.principal);

        Subject serviceSubject = getServiceSubject(loginConfig);
        return Subject.doAs(serviceSubject, new PrivilegedAction<Header>() {
            public Header run() {
                // First try without stripping the port
                RuntimeException saveFirstException;
                try {
                    return spnegoAuthenticate(false, uri);
                } catch (Exception e) {
                    saveFirstException = new RuntimeException(e);
                }
                // if fails let's try stripping the port
                try {
                    return spnegoAuthenticate(true, uri);
                } catch (Exception e) {
                    //let's send the first exception
                    throw saveFirstException;
                }
            }
        });
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(ERROR_MSG, e);
    }
}

From source file:org.rhq.enterprise.client.LocalClient.java

@Override
public AlertDefinitionManagerRemote getAlertDefinitionManager() {
    return AccessController.doPrivileged(new PrivilegedAction<AlertDefinitionManagerRemote>() {
        @Override/*from  w  w w  .j a v a 2  s .c o m*/
        public AlertDefinitionManagerRemote run() {
            return getProxy(LookupUtil.getAlertDefinitionManager(), AlertDefinitionManagerRemote.class);
        }
    });
}

From source file:org.eclipse.gemini.blueprint.config.internal.adapter.OsgiServiceLifecycleListenerAdapter.java

/**
 * Initialise adapter. Determine custom methods and do validation.
 *//*from  ww  w  . java  2  s.c  o  m*/
private void initialize() {

    Class<?> clazz = (target == null ? beanFactory.getType(targetBeanName) : target.getClass());

    Assert.notNull(clazz, "listener " + targetBeanName + " class type cannot be determined");

    isLifecycleListener = OsgiServiceLifecycleListener.class.isAssignableFrom(clazz);
    if (isLifecycleListener)
        if (log.isDebugEnabled())
            log.debug(clazz.getName() + " is a lifecycle listener");

    bindMethods = CustomListenerAdapterUtils.determineCustomMethods(clazz, bindMethod, isBlueprintCompliant);

    boolean isSecurityEnabled = System.getSecurityManager() != null;
    final Class<?> clz = clazz;

    // determine methods using ServiceReference signature
    if (StringUtils.hasText(bindMethod)) {
        if (isSecurityEnabled) {
            bindReference = AccessController.doPrivileged(new PrivilegedAction<Method>() {
                public Method run() {
                    return findServiceReferenceMethod(clz, bindMethod);
                }
            });
        } else {
            bindReference = findServiceReferenceMethod(clz, bindMethod);
        }

        if (bindMethods.isEmpty()) {
            String beanName = (target == null ? "" : " bean [" + targetBeanName + "] ;");
            throw new IllegalArgumentException(
                    "Custom bind method [" + bindMethod + "] not found on " + beanName + "class " + clazz);
        }
    }

    unbindMethods = CustomListenerAdapterUtils.determineCustomMethods(clazz, unbindMethod,
            isBlueprintCompliant);

    if (StringUtils.hasText(unbindMethod)) {
        if (isSecurityEnabled) {
            unbindReference = AccessController.doPrivileged(new PrivilegedAction<Method>() {
                public Method run() {
                    return findServiceReferenceMethod(clz, unbindMethod);
                }
            });
        } else {
            unbindReference = findServiceReferenceMethod(clz, unbindMethod);
        }

        if (unbindMethods.isEmpty()) {
            String beanName = (target == null ? "" : " bean [" + targetBeanName + "] ;");
            throw new IllegalArgumentException(
                    "Custom unbind method [" + unbindMethod + "] not found on " + beanName + "class " + clazz);
        }
    }

    if (!isLifecycleListener && (bindMethods.isEmpty() && unbindMethods.isEmpty() && bindReference == null
            && unbindReference == null))
        throw new IllegalArgumentException(
                "target object needs to implement " + OsgiServiceLifecycleListener.class.getName()
                        + " or custom bind/unbind methods have to be specified");

    if (log.isTraceEnabled()) {
        StringBuilder builder = new StringBuilder();
        builder.append("Discovered bind methods=");
        builder.append(bindMethods.values());
        builder.append(", bind ServiceReference=");
        builder.append(bindReference);
        builder.append("\nunbind methods=");
        builder.append(unbindMethods.values());
        builder.append(", unbind ServiceReference=");
        builder.append(unbindReference);
        log.trace(builder.toString());
    }
}