Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

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

Prototype

public SecurityException() 

Source Link

Document

Constructs a SecurityException with no detail message.

Usage

From source file:it.smartcommunitylab.aac.apikey.APIKeyController.java

/**
 * Delete a specified API key/*from w  w w . j  a va  2  s.  c  om*/
 * @param apiKey
 * @return 
 */
@ApiOperation(value = "Update key")
@PutMapping(value = "/apikey/{apiKey:.*}")
public @ResponseBody APIKey updateKey(HttpServletRequest request, @RequestBody APIKey body,
        @PathVariable String apiKey) throws SecurityException, EntityNotFoundException {
    APIKey key = keyManager.findKey(apiKey);
    if (key != null) {
        String clientId = getClientId(request);
        if (!clientId.equals(key.getClientId())) {
            throw new SecurityException();
        }

        if (body.getValidity() != null && body.getValidity() > 0) {
            keyManager.updateKeyValidity(apiKey, body.getValidity());
        }
        if (body.getAdditionalInformation() != null) {
            keyManager.updateKeyData(apiKey, body.getAdditionalInformation());
        }
        return keyManager.findKey(apiKey);
    }
    throw new EntityNotFoundException();
}

From source file:com.liferay.arquillian.maven.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        @Override//from   ww  w .j  a  v a2 s .c  o m
        public void checkPermission(Permission permission) {
            //It is not needed to check permissions
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

public static String getJSON(String host, String service, String token, Map<String, Object> parameters)
        throws RemoteException {
    final HttpResponse resp;

    try {//  w w w.  ja v  a2  s. com
        String queryString = generateQueryString(parameters);
        final HttpGet get = new HttpGet(normalizeURL(host + service) + queryString);
        get.setHeader(RH_ACCEPT, "application/json");
        get.setHeader(RH_AUTH_TOKEN, bearer(token));

        resp = getHttpClient().execute(get);
        String response = EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response;
        }
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN
                || resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new SecurityException();
        }
        throw new RemoteException("Error validating " + resp.getStatusLine());
    } catch (ClientProtocolException e) {
        throw new RemoteException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new RemoteException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RemoteException(e.getMessage(), e);
    }

}

From source file:com.limegroup.gnutella.util.Launcher.java

/**
 * Launches the file whose abstract path is specified in the <tt>File</tt>
 * parameter. This method will not launch any file with .exe, .vbs, .lnk,
 * .bat, .sys, or .com extensions, diplaying an error if one of the file is
 * of one of these types.//from w ww.  j  a  v  a  2 s .c  o  m
 * 
 * @param path
 *            The path of the file to launch
 * @return an object for accessing the launch process; null, if the process
 *         can be represented (e.g. the file was launched through a native
 *         call)
 * @throws IOException
 *             if the file cannot be launched
 * @throws SecurityException
 *             if the file has an extension that is not allowed
 */
public static LimeProcess launchFile(File file) throws IOException, SecurityException {

    List<String> forbiddenExtensions = Arrays.asList("exe", "vbs", "lnk", "bat", "sys", "com", "js", "scpt");

    if (file.isFile() && forbiddenExtensions.contains(FilenameUtils.getExtension(file.getName()))) {
        throw new SecurityException();
    }

    String path = file.getCanonicalPath();

    if (OSUtils.isWindows()) {
        launchFileWindows(path);
        return null;
    } else if (OSUtils.isMacOSX()) {
        return launchFileMacOSX(path);
    } else {
        // Other OS, use helper apps
        return launchFileOther(path);
    }
}

From source file:org.apache.nutch.indexwriter.elasticrest.ElasticRestIndexWriter.java

@Override
public void open(IndexWriterParams parameters) throws IOException {
    host = parameters.get(ElasticRestConstants.HOST);
    if (StringUtils.isBlank(host)) {
        String message = "Missing host. It should be set in index-writers.xml";
        message += "\n" + describe();
        LOG.error(message);//from  w w  w . j  ava 2 s. c om
        throw new RuntimeException(message);
    }

    port = parameters.getInt(ElasticRestConstants.PORT, 9200);
    user = parameters.get(ElasticRestConstants.USER);
    password = parameters.get(ElasticRestConstants.PASSWORD);
    https = parameters.getBoolean(ElasticRestConstants.HTTPS, false);
    trustAllHostnames = parameters.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);

    languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
    separator = parameters.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
    sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);

    // trust ALL certificates
    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        LOG.error("Failed to instantiate sslcontext object: \n{}", ExceptionUtils.getStackTrace(e));
        throw new SecurityException();
    }

    // skip hostname checks
    HostnameVerifier hostnameVerifier = null;
    if (trustAllHostnames) {
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        hostnameVerifier = new DefaultHostnameVerifier();
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
    SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

    JestClientFactory jestClientFactory = new JestClientFactory();
    URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");

    if (host != null && port > 1) {
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder(urlOfElasticsearchNode.toString())
                .multiThreaded(true).connTimeout(300000).readTimeout(300000);
        if (https) {
            if (user != null && password != null) {
                builder.defaultCredentials(user, password);
            }
            builder.defaultSchemeForDiscoveredNodes("https").sslSocketFactory(sslSocketFactory) // this only affects sync calls
                    .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
        }
        jestClientFactory.setHttpClientConfig(builder.build());
    } else {
        throw new IllegalStateException(
                "No host or port specified. Please set the host and port in nutch-site.xml");
    }

    client = jestClientFactory.getObject();

    defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
    defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");

    maxBulkDocs = parameters.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
    maxBulkLength = parameters.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);

    bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
}

From source file:com.netspective.commons.io.UriAddressableUniqueFileLocator.java

public UriAddressableFile findUriAddressableFile(final String name) throws IOException {
    final boolean logging = log.isDebugEnabled();
    if (logging)//from  w w w.j a  v a  2s .co m
        log.debug("SingleUriAddressableFileLocator searching for " + name);

    if (cacheLocations) {
        UriAddressableFile resource = (UriAddressableFile) cache.get(name);
        if (resource != null) {
            if (logging)
                log.debug("SingleUriAddressableFileLocator cache hit for " + resource);
            return resource;
        }
    }

    try {
        return (UriAddressableFile) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                File source = new File(baseDir, SEP_IS_SLASH ? name : name.replace(File.separatorChar, '/'));
                // Security check for inadvertently returning something outside the
                // resource directory.
                String normalized = source.getCanonicalPath();
                if (!normalized.startsWith(canonicalPath)) {
                    throw new SecurityException();
                }

                if (logging)
                    log.debug("SingleUriAddressableFileLocator looking for '" + name + "' as " + source);
                UriAddressableFile result = source.exists() ? new UriAddressableFile(rootUrl, name, source)
                        : null;
                if (result != null) {
                    if (logging)
                        log.debug("SingleUriAddressableFileLocator found " + result);
                    if (cacheLocations)
                        cache.put(name, result);
                }
                return result;
            }
        });
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
}

From source file:org.droid2droid.ui.connect.AbstractConnectFragment.java

@Override
public Object onTryConnect(String uri, int flags) throws IOException, RemoteException {
    if (getConnectActivity() == null)
        return null;
    if (getConnectActivity().isBroadcast()) {
        AbstractProtoBufRemoteAndroid binder = null;
        try {//  ww  w.ja v  a2 s  .c  o  m
            final Uri uuri = Uri.parse(uri);
            Driver driver = Droid2DroidManagerImpl.sDrivers.get(uuri.getScheme());
            if (driver == null)
                throw new MalformedURLException("Unknown " + uri);
            binder = (AbstractProtoBufRemoteAndroid) driver.factoryBinder(RAApplication.sAppContext,
                    RAApplication.getManager(), uuri);
            if (binder.connect(Type.CONNECT_FOR_BROADCAST, 0, 0, ETHERNET_TRY_TIMEOUT))
                return ProgressJobs.OK; // Hack, simulate normal connection
            else
                throw new IOException("Connection impossible");
        } finally {
            if (binder != null)
                binder.close();
        }
    } else {
        Pair<RemoteAndroidInfoImpl, Long> msg = RAApplication.getManager().askMsgCookie(Uri.parse(uri), flags);
        if (msg == null || msg.second == 0)
            throw new SecurityException();
        RemoteAndroidInfoImpl remoteInfo = msg.first;
        final long cookie = msg.second;
        if (cookie != COOKIE_NO && cookie != COOKIE_EXCEPTION && cookie != COOKIE_SECURITY)
            RAApplication.sDiscover.addCookie(remoteInfo, cookie);
        return msg.first;
    }
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        public void checkPermission(Permission permission) {
        }// ww  w. ja v a  2  s.  c  o m

        public void checkExit(int status) {
            throw new SecurityException();
        }

    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(toolClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (ite.getCause() instanceof SecurityException) {
        } else {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.clearProperty("org.apache.commons.logging.Log");

        System.setSecurityManager(currentSecurityManager);
    }
}