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.apache.axis.configuration.EngineConfigurationFactoryFinder.java

/**
 * Create the default engine configuration and detect whether the user
 * has overridden this with their own.//  www . ja v  a2 s.co m
 *
 * The discovery mechanism will use the following logic:
 *
 * - discover all available EngineConfigurationFactories
 *   - find all META-INF/services/org.apache.axis.EngineConfigurationFactory
 *     files available through class loaders.
 *   - read files (see Discovery) to obtain implementation(s) of that
 *     interface
 * - For each impl, call 'newFactory(Object param)'
 * - Each impl should examine the 'param' and return a new factory ONLY
 *   - if it knows what to do with it
 *     (i.e. it knows what to do with the 'real' type)
 *   - it can find it's configuration information
 * - Return first non-null factory found.
 * - Try EngineConfigurationFactoryServlet.newFactory(obj)
 * - Try EngineConfigurationFactoryDefault.newFactory(obj)
 * - If zero found (all return null), throw exception
 *
 * ***
 * This needs more work: System.properties, etc.
 * Discovery will have more tools to help with that
 * (in the manner of use below) in the near future.
 * ***
 *
 */
public static EngineConfigurationFactory newFactory(final Object obj) {
    /**
     * recreate on each call is critical to gaining
     * the right class loaders.  Do not cache.
     */
    final Object[] params = new Object[] { obj };

    /**
     * Find and examine each service
     */
    return (EngineConfigurationFactory) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ResourceClassIterator services = AxisProperties.getResourceClassIterator(mySpi);

            EngineConfigurationFactory factory = null;

            while (factory == null && services.hasNext()) {
                try {
                    Class service = services.nextResourceClass().loadClass();

                    /* service == null
                     * if class resource wasn't loadable
                     */
                    if (service != null) {
                        factory = newFactory(service, newFactoryParamTypes, params);
                    }
                } catch (Exception e) {
                    // there was an exception creating the factory
                    // the most likely cause was the JDK 1.4 problem
                    // in the discovery code that requires servlet.jar
                    // to be in the client classpath.  For now, fall
                    // through to the next factory
                }
            }

            if (factory != null) {
                if (log.isDebugEnabled()) {
                    log.debug(Messages.getMessage("engineFactory", factory.getClass().getName()));
                }
            } else {
                log.error(Messages.getMessage("engineConfigFactoryMissing"));
                // we should be throwing an exception here,
                //
                // but again, requires more refactoring than we want to swallow
                // at this point in time.  Ifthis DOES occur, it's a coding error:
                // factory should NEVER be null.
                // Testing will find this, as NullPointerExceptions will be generated
                // elsewhere.
            }

            return factory;
        }
    });
}

From source file:com.apress.springosgi.ch9.testsosgi.testivyprovisions.LocalFileSystemIvyRepository.java

/**
 * Initialization method It determines the repository path by checking the
 * existence of <code>localRepository</code> system property and falling
 * back to the default <code>user.home/.ivy2/cache</code>.
 * /*from  w w w.  ja v a2  s  . c  o m*/
 * <p/> This method is used to postpone initialization until an artifact is
 * actually located. As the test class is instantiated on each test run, the
 * init() method prevents repetitive, waste-less initialization.
 * 
 */
private void init() {
    // already discovered a repository home, bailing out
    if (repositoryHome != null)
        return;

    boolean trace = log.isDebugEnabled();

    final String[] sysProperties = new String[2];
    // check system property
    AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            sysProperties[0] = System.getProperty(SYS_PROPERTY);
            sysProperties[1] = System.getProperty(USER_HOME_PROPERTY);
            return null;
        }
    });
    String localRepository = sysProperties[0];
    String userHome = sysProperties[1];

    if (trace)
        log.trace("IVY2 system property [" + SYS_PROPERTY + "] has value=" + localRepository);

    if (localRepository == null) {
        // fall back to the default location
        localRepository = new File(userHome, DEFAULT_DIR).getAbsolutePath();
        if (trace)
            log.trace("No custom setting found; using default M2 local repository=" + localRepository);

    }

    repositoryHome = localRepository;
    log.info("Local Ivy2 repository used: [" + repositoryHome + "]");
}

From source file:org.apache.ranger.hive.client.HiveClient.java

public List<String> getDatabaseList(String databaseMatching) {
    final String dbMatching = databaseMatching;
    List<String> dblist = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
        public List<String> run() {
            return getDBList(dbMatching);
        }/*from w  w w.j  a  va  2  s.  c o  m*/
    });
    return dblist;
}

From source file:org.mule.util.ClassUtils.java

/**
 * Load a given resource. <p/> This method will try to load the resource using
 * the following methods (in order)://from w  w  w .j  av  a  2 s. c o m
 * <ul>
 * <li>From
 * {@link Thread#getContextClassLoader() Thread.currentThread().getContextClassLoader()}
 * <li>From
 * {@link Class#getClassLoader() ClassUtils.class.getClassLoader()}
 * <li>From the {@link Class#getClassLoader() callingClass.getClassLoader() }
 * </ul>
 *
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 *
 * @return A URL pointing to the resource to load or null if the resource is not found
 */
public static URL getResource(final String resourceName, final Class<?> callingClass) {
    URL url = AccessController.doPrivileged(new PrivilegedAction<URL>() {
        public URL run() {
            final ClassLoader cl = Thread.currentThread().getContextClassLoader();
            return cl != null ? cl.getResource(resourceName) : null;
        }
    });

    if (url == null) {
        url = AccessController.doPrivileged(new PrivilegedAction<URL>() {
            public URL run() {
                return ClassUtils.class.getClassLoader().getResource(resourceName);
            }
        });
    }

    if (url == null) {
        url = AccessController.doPrivileged(new PrivilegedAction<URL>() {
            public URL run() {
                return callingClass.getClassLoader().getResource(resourceName);
            }
        });
    }

    return url;
}

From source file:com.wavemaker.commons.classloader.ClassLoaderUtils.java

/**
 * Get a temporary classloader. By default, this will use the parent classloader as a base.
 * // w ww  . java2 s .  c  om
 * @param files
 * @return
 */
public static ClassLoader getTempClassLoaderForResources(Resource... files) {

    final List<Resource> filesList = Arrays.asList(files);

    ClassLoader ret = AccessController.doPrivileged(new PrivilegedAction<ThrowawayFileClassLoader>() {

        @Override
        public ThrowawayFileClassLoader run() {
            return new ThrowawayFileClassLoader(filesList, getClassLoader().getParent());
        }
    });
    return ret;
}

From source file:org.apache.ranger.storm.client.StormClient.java

public List<String> getTopologyList(final String topologyNameMatching) {

    LOG.debug("Getting Storm topology list for topologyNameMatching : " + topologyNameMatching);
    final String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check xa_portal.log for more info.";

    List<String> ret = new ArrayList<String>();

    PrivilegedAction<ArrayList<String>> topologyListGetter = new PrivilegedAction<ArrayList<String>>() {
        @Override/*from  w ww . ja v a2  s .c  o  m*/
        public ArrayList<String> run() {

            ArrayList<String> lret = new ArrayList<String>();

            String url = stormUIUrl + TOPOLOGY_LIST_API_ENDPOINT;

            Client client = null;
            ClientResponse response = null;

            try {
                client = Client.create();

                WebResource webResource = client.resource(url);

                response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);

                LOG.debug("getTopologyList():calling " + url);

                if (response != null) {
                    LOG.debug("getTopologyList():response.getStatus()= " + response.getStatus());
                    if (response.getStatus() == 200) {
                        String jsonString = response.getEntity(String.class);
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();
                        TopologyListResponse topologyListResponse = gson.fromJson(jsonString,
                                TopologyListResponse.class);
                        if (topologyListResponse != null) {
                            if (topologyListResponse.getTopologyList() != null) {
                                for (Topology topology : topologyListResponse.getTopologyList()) {
                                    String toplogyName = topology.getName();
                                    LOG.debug("getTopologyList():Found topology " + toplogyName);
                                    LOG.debug("getTopologyList():topology Name=[" + topology.getName()
                                            + "], topologyNameMatching=[" + topologyNameMatching + "]");
                                    if (toplogyName != null) {
                                        if (topologyNameMatching == null || topologyNameMatching.isEmpty()
                                                || FilenameUtils.wildcardMatch(topology.getName(),
                                                        topologyNameMatching + "*")) {
                                            LOG.debug("getTopologyList():Adding topology " + toplogyName);
                                            lret.add(toplogyName);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        LOG.info("getTopologyList():response.getStatus()= " + response.getStatus() + " for URL "
                                + url + ", so returning null list");
                        String jsonString = response.getEntity(String.class);
                        LOG.info(jsonString);
                        lret = null;
                    }
                } else {
                    String msgDesc = "Unable to get a valid response for " + "expected mime type : ["
                            + EXPECTED_MIME_TYPE + "] URL : " + url + " - got null response.";
                    LOG.error(msgDesc);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    throw hdpException;
                }
            } catch (HadoopException he) {
                throw he;
            } catch (Throwable t) {
                String msgDesc = "Exception while getting Storm TopologyList." + " URL : " + url;
                HadoopException hdpException = new HadoopException(msgDesc, t);
                LOG.error(msgDesc, t);

                hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null,
                        null);
                throw hdpException;

            } finally {
                if (response != null) {
                    response.close();
                }

                if (client != null) {
                    client.destroy();
                }

            }
            return lret;
        }
    };

    try {
        ret = executeUnderKerberos(this.userName, this.password, topologyListGetter);
    } catch (IOException e) {
        LOG.error("Unable to get Topology list from [" + stormUIUrl + "]", e);
    }

    return ret;
}

From source file:org.codehaus.groovy.grails.web.pages.discovery.CachingGrailsConventionGroovyPageLocator.java

@Override
public GroovyPageScriptSource findPage(final String uri) {
    if (uri == null)
        return null;

    PrivilegedAction<GroovyPageScriptSource> updater = new PrivilegedAction<GroovyPageScriptSource>() {
        public GroovyPageScriptSource run() {
            GroovyPageScriptSource scriptSource = CachingGrailsConventionGroovyPageLocator.super.findPage(uri);
            if (scriptSource == null) {
                scriptSource = NULL_SCRIPT;
            }/*from  www  .jav a 2s.  c om*/
            return scriptSource;
        }
    };

    return lookupCache(GroovyPageLocatorCacheKey.build(uri, null, null), updater);
}

From source file:com.agimatec.validation.jsr303.util.SecureActions.java

public static Method getMethod(final Class<?> clazz, final String methodName) {
    return run(new PrivilegedAction<Method>() {
        public Method run() {
            try {
                return clazz.getMethod(methodName);
            } catch (NoSuchMethodException e) {
                return null;
            }/*from  w  w w . j a  v a 2 s . co m*/
        }
    });
}

From source file:gov.nih.nci.cacis.sa.mirthconnect.SemanticAdapter.java

private String getCaCISRequestxml(final CaCISRequest parameter) {

    return AccessController.doPrivileged(new PrivilegedAction<String>() {

        public String run() {
            try {
                final CaCISURLClassLoader cl = new CaCISURLClassLoader(customLibDir,
                        ClassLoader.getSystemClassLoader());
                final Class jmClass = Class.forName("gov.nih.nci.cacis.sa.mirthconnect.JAXBMarshaller", true,
                        cl);/*from   www . j a  va 2  s  .c  o  m*/
                final Method m = jmClass.getMethod("marshal", Object.class);
                return (String) m.invoke(jmClass.newInstance(), parameter);
                // CHECKSTYLE:OFF
            } catch (Exception ex) {
                // CHECKSTYLE:ON
                LOG.error("Error marshalling CaCISRequest!", ex);
                return null;
            }
        }
    });

}

From source file:org.jcodec.player.app.PlayerApplet.java

public void open(final String src) {
    Debug.println("Opening source: " + src);
    try {//from  ww  w .  j  a va  2  s . c  om
        if (player != null) {
            Debug.println("Destroying old player.");
            player.destroy();
            video.close();
            audio.close();
            status2Task.cancel();
            status2Task = null;
        }

        HttpMedia http = AccessController.doPrivileged(new PrivilegedAction<HttpMedia>() {
            public HttpMedia run() {
                try {
                    File cacheWhere = determineCacheLocation();
                    FileUtils.forceMkdir(cacheWhere);
                    return new HttpMedia(new URL(src), cacheWhere);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("Could not open HTTP source: '" + src + "'");
                }
            }
        });
        Debug.println("Initialized packet source");

        Debug.println("Creating player");
        final HttpPacketSource videoTrack = http.getVideoTrack();
        video = new JCodecVideoSource(videoTrack);
        audio = audio(http);
        player = new Player(video, audio, vo, new JSoundAudioOut());

        player.addListener(new Listener() {
            public void timeChanged(RationalLarge pts, int frameNo, TapeTimecode tt) {
                if (onStatus1 == null)
                    return;
                onStatus1
                        .call("call",
                                new Object[] { null, new Status1((double) pts.getNum() / pts.getDen(), frameNo,
                                        tt != null
                                                ? new int[] { tt.getHour(), tt.getMinute(), tt.getSecond(),
                                                        tt.getFrame(), tt.isDropFrame() ? 1 : 0 }
                                                : null) });
            }

            public void statusChanged(Status status) {
                if (onStateChanged != null)
                    onStateChanged.call("call", new Object[] { null, status.toString() });
            }
        });
        status2Task = new TimerTask() {
            public void run() {
                if (onStatus2 == null)
                    return;

                try {
                    VideoInfo videoInfo = player.getVideoSource().getMediaInfo();
                    onStatus2.call("call",
                            new Object[] { null,
                                    new Status2((double) videoInfo.getDuration() / videoInfo.getTimescale(),
                                            (int) videoInfo.getNFrames(), videoTrack.getCached(),
                                            enabledChannels()) });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        timer.scheduleAtFixedRate(status2Task, 0, 1000);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Could not open source", e);
    }
}