Example usage for java.net URL getProtocol

List of usage examples for java.net URL getProtocol

Introduction

In this page you can find the example usage for java.net URL getProtocol.

Prototype

public String getProtocol() 

Source Link

Document

Gets the protocol name of this URL .

Usage

From source file:com.quartercode.jtimber.rh.agent.util.ResourceLister.java

/**
 * Creates a new resource lister that lists all occurrences of the given classpath resource on the classpath as {@link Path}s.
 * It is possible that multiple paths are listed if multiple classpath entries (e.g. jars) contain the resource.
 * For example, if two jars contain the directory {@code /test1/test2}, this class lists both both.<br>
 * <br>//from  w ww  . j a v a2s  .  c  o  m
 * Note that this class uses a workaround to create path objects for files which are located inside a jar.
 * Because of that, each instance of this class should be closed after the paths have been used.
 * However, the paths might no longer be accessible after the lister has been closed.
 * 
 * @param resourcePath The path that defines the classpath resource whose occurrences should be listed.
 * @param throwAll Whether {@link IOException}s, which are thrown during the retrieval of one specific resource and would therefore also interrupt
 *        the retrieval of other resources, should be thrown.
 *        If this is {@code false}, the regarding exceptions are logged as errors.
 * @throws IOException Something goes wrong while retrieving the resource occurrences.
 *         If {@code throwAll} is {@code true} and an occurrence is located inside a jar, a jar reading exception is also possible.
 * @throws IllegalArgumentException The resource path doesn't start with "/" (this method cannot list relative resources).
 * @see #getResourcePaths()
 */
public ResourceLister(String resourcePath, boolean throwAll) throws IOException {

    Validate.isTrue(resourcePath.startsWith("/"),
            "Cannot retrieve relative resources, make sure your path starts with '/'");

    // Retrieve all occurrences of the given path in the classpath
    Enumeration<URL> locations = ResourceLister.class.getClassLoader()
            .getResources(StringUtils.stripStart(resourcePath, "/"));

    // Iterate over those occurrences
    while (locations.hasMoreElements()) {
        URL location = locations.nextElement();

        // Check whether the found location is inside a jar file
        if (location.getProtocol().equals("jar")) {
            try {
                // Resolve the path of the jar file and load the resources from there
                Path jarFile = Paths.get(toURI(((JarURLConnection) location.openConnection()).getJarFileURL()));

                // Load the resources from the jar file
                FileSystem jarFS = FileSystems.newFileSystem(jarFile, null);
                resourcePaths.add(jarFS.getPath(resourcePath));
                jarFileSystems.add(jarFS);
            } catch (IOException e) {
                if (throwAll) {
                    throw e;
                } else {
                    LOGGER.error("Cannot read resource '{}' from jar file '{}'", resourcePath, location, e);
                }
            }
        } else {
            // Directly load the resources from the main file system
            resourcePaths.add(Paths.get(toURI(location)));
        }
    }
}

From source file:org.pentaho.reporting.platform.plugin.PentahoReportEnvironment.java

private String getBaseServerURL(final String fullyQualifiedServerUrl) {
    try {/*from  w w  w .j a  v  a 2  s .co m*/
        final URL url = new URL(fullyQualifiedServerUrl);
        return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        // ignore
        logger.warn(Messages.getInstance().getString("ReportPlugin.warnNoBaseServerURL"), e);
    }
    return null;
}

From source file:com.hazelcast.config.XmlConfigSchemaLocationTest.java

@Test
public void testSchemaLocationsExist() throws Exception {
    assumeTls12Available();/*  www  . j a va2  s.c o m*/

    ResourcesScanner scanner = new ResourcesScanner();
    Reflections reflections = new Reflections(scanner);
    Set<String> resources = reflections.getResources(Pattern.compile(".*\\.xml"));
    ClassLoader classLoader = getClass().getClassLoader();
    for (String resource : resources) {
        URL resourceUrl = classLoader.getResource(resource);
        String protocol = resourceUrl.getProtocol();

        // do not validate schemas from JARs (libraries). we are interested in local project files only.
        if (protocol.startsWith("jar")) {
            continue;
        }

        InputStream stream = null;
        try {
            stream = classLoader.getResourceAsStream(resource);
            validateSchemaLocationUrl(stream, resource);
        } finally {
            IOUtil.closeResource(stream);
        }
    }
}

From source file:uk.ac.ox.oucs.vle.XcriPopulatorInput.java

public InputStream getInput(PopulatorContext context) throws PopulatorException {

    InputStream input = null;/*from  www  .j  a  v  a  2 s . com*/
    HttpEntity entity = null;

    try {
        URL xcri = new URL(context.getURI());

        HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

        HttpGet httpget = new HttpGet(xcri.toURI());
        HttpResponse response = httpClient.execute(targetHost, httpget);
        entity = response.getEntity();

        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            throw new PopulatorException("Invalid Response [" + response.getStatusLine().getStatusCode() + "]");
        }

        input = entity.getContent();

    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } finally {
        if (null == input && null != entity) {
            try {
                entity.getContent().close();
            } catch (IOException e) {
                log.error("IOException [" + e + "]");
            }
        }
    }
    return input;
}

From source file:org.bytesoft.bytetcc.supports.zk.TransactionCuratorClient.java

public void initZookeeperAddressIfNecessary(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] beanNameArray = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        if (com.alibaba.dubbo.config.RegistryConfig.class.getName().equals(beanDef.getBeanClassName())) {
            MutablePropertyValues mpv = beanDef.getPropertyValues();
            PropertyValue protpv = mpv.getPropertyValue(KEY_DUBBO_REGISTRY_PROTOCOL);
            PropertyValue addrpv = mpv.getPropertyValue(KEY_DUBBO_REGISTRY_ADDRESS);

            String protocol = null;
            String address = null;
            if (addrpv == null) {
                throw new FatalBeanException("zookeeper address cannot be null!"); // should never happen
            } else if (protpv == null) {
                String value = String.valueOf(addrpv.getValue());
                try {
                    URL url = new URL(null, value, this);
                    protocol = url.getProtocol();
                    address = url.getAuthority();
                } catch (Exception ex) {
                    throw new FatalBeanException("Unsupported format!");
                }//from  ww  w .  j  a va2 s . c  om
            } else {
                protocol = String.valueOf(protpv.getValue());
                String value = StringUtils.trimToEmpty(String.valueOf(addrpv.getValue()));
                int index = value.indexOf(protocol);
                if (index == -1) {
                    address = value;
                } else if (index == 0) {
                    String str = StringUtils.trimToEmpty(value.substring(protocol.length()));
                    if (str.startsWith("://")) {
                        address = StringUtils.trimToEmpty(str.substring(3));
                    } else {
                        throw new FatalBeanException("Unsupported format!");
                    }
                } else {
                    throw new FatalBeanException("Unsupported format!");
                }
            }

            if (KEY_DUBBO_REGISTRY_ZOOKEEPER.equalsIgnoreCase(protocol) == false) {
                throw new FatalBeanException("Unsupported protocol!");
            }

            String addrKey = "zookeeperAddr";
            String[] watcherBeanArray = beanFactory
                    .getBeanNamesForType(org.bytesoft.bytetcc.supports.zk.TransactionCuratorClient.class);
            BeanDefinition watcherBeanDef = beanFactory.getBeanDefinition(watcherBeanArray[0]);
            MutablePropertyValues warcherMpv = watcherBeanDef.getPropertyValues();
            PropertyValue warcherPv = warcherMpv.getPropertyValue(addrKey);
            if (warcherPv == null) {
                warcherMpv.addPropertyValue(new PropertyValue(addrKey, address));
            } else {
                warcherMpv.removePropertyValue(addrKey);
                warcherMpv.addPropertyValue(new PropertyValue(addrKey, address));
            }

        }
    }
}

From source file:lux.solr.AppServerComponent.java

@Override
public void prepare(ResponseBuilder rb) throws IOException {
    SolrQueryRequest req = rb.req;//from  w ww .j ava2  s  . c o  m
    SolrParams params = req.getParams();
    if (rb.getQueryString() == null) {
        queryPath = rb.req.getParams().get(LUX_XQUERY);
        if (!StringUtils.isBlank(queryPath)) {
            String baseUri;
            String contextBase = (String) params.get("lux.serverBaseUri");
            if (params.get("lux.baseUri") != null) {
                baseUri = (String) params.get("lux.baseUri");
            } else if (params.get("lux.serverBaseUri") != null) {
                baseUri = contextBase;
            } else {
                baseUri = "";
            }
            if (File.separatorChar == '\\') {
                baseUri = baseUri.replace('\\', '/');
            }
            if (!baseUri.endsWith("/")) {
                // add trailing slash
                baseUri = baseUri + '/';
            }
            if (baseUri.startsWith("/") || (File.separatorChar == '\\' && baseUri.matches("^[A-Za-z]:/.*$"))) {
                baseUri = "file://" + baseUri;
            }
            //System.out.println ("BASE URI = " + baseUri);
            String resourceBase = null;
            if (baseUri.startsWith(RESOURCE_SCHEME)) {
                resourceBase = baseUri.substring(RESOURCE_SCHEME.length());
            } else if (baseUri.startsWith(CONTEXT_SCHEME)) {
                baseUri = contextBase + baseUri.substring(CONTEXT_SCHEME.length());
            }
            String contents = null;
            if (resourceBase != null) {
                InputStream in = AppServerComponent.class.getResourceAsStream(resourceBase + queryPath);
                queryPath = baseUri + queryPath;
                if (in == null) {
                    throw new SolrException(ErrorCode.NOT_FOUND, queryPath + " not found");
                } else {
                    try {
                        contents = IOUtils.toString(in);
                    } catch (IOException e) {
                        LoggerFactory.getLogger(AppServerComponent.class)
                                .error("An error occurred while reading " + queryPath, e);
                    }
                    IOUtils.closeQuietly(in);
                }
            } else {
                // url provided with scheme
                queryPath = baseUri + queryPath;
                URL url = new URL(queryPath);
                String scheme = url.getProtocol();
                if (scheme.equals("lux")) {
                    // TODO implement lux: uri resolution
                    throw new SolrException(ErrorCode.NOT_FOUND,
                            queryPath + " not found (actually lux: scheme is not implemented)");
                } else {
                    InputStream in = null;
                    try {
                        if (url.getProtocol().equals("file")) {
                            File f = new File(url.getPath());
                            if (!f.exists()) {
                                throw new SolrException(ErrorCode.NOT_FOUND, f + " not found");
                            }
                            if (f.isDirectory() || !f.canRead()) {
                                throw new SolrException(ErrorCode.FORBIDDEN,
                                        "access to " + f + " denied by rule");
                            }
                            in = new FileInputStream(f);
                        } else {
                            // in = url.openStream();
                            LoggerFactory.getLogger(AppServerComponent.class)
                                    .error("URL scheme not supported: " + url.getProtocol());
                        }
                        contents = IOUtils.toString(in);
                    } catch (IOException e) {
                        LoggerFactory.getLogger(AppServerComponent.class)
                                .error("An error occurred while reading " + url, e);
                    }
                    if (in != null) {
                        IOUtils.closeQuietly(in);
                    }
                }
            }
            rb.setQueryString(contents);
        }
    }
    super.prepare(rb);
}

From source file:org.teavm.libgdx.plugin.AssetsCopier.java

private void copyClasspathAssets(File dir) throws IOException {
    Enumeration<URL> resources = context.getClassLoader()
            .getResources("META-INF/teavm-libgdx/classpath-assets");
    Set<String> resourcesToCopy = new HashSet<>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        InputStream input = resource.openStream();
        if (input == null) {
            continue;
        }/*from  w  w w.  ja  v  a 2 s.co  m*/
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"))) {
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                resourcesToCopy.add(line);
            }
        }
    }

    for (String resourceToCopy : resourcesToCopy) {
        File resource = new File(dir, resourceToCopy);
        if (resource.exists()) {
            URL url = context.getClassLoader().getResource(resourceToCopy);
            if (url != null && url.getProtocol().equals("file")) {
                try {
                    File sourceFile = new File(url.toURI());
                    if (sourceFile.exists() && sourceFile.length() == resource.length()
                            && sourceFile.lastModified() == resource.lastModified()) {
                        continue;
                    }
                } catch (URISyntaxException e) {
                    // fall back to usual resource copying
                }
            }
        }
        InputStream input = context.getClassLoader().getResourceAsStream(resourceToCopy);
        if (input == null) {
            continue;
        }
        resource.getParentFile().mkdirs();
        IOUtils.copy(input, new FileOutputStream(resource));
    }
}

From source file:com.collabnet.tracker.common.httpClient.TrackerHttpSender.java

@Override
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL url) {
    String httpUser = null;//w w  w . java2s.co m
    String httpPassword = null;
    String serverUrl = url.getProtocol() + "://" + url.getHost();
    PTrackerWebServicesClient webServicesClient = TrackerClientManager.getInstance().getClient(serverUrl);

    Proxy proxy = Activator.getPlatformProxy(url.toString());
    if (proxy != null) {
        proxy.setProxy(client);
    }

    httpUser = webServicesClient.getHttpUser();
    httpPassword = webServicesClient.getHttpPassword();

    setupHttpClient(client, url.toString(), httpUser, httpPassword);
    return client.getHostConfiguration();
}

From source file:org.eclipse.skalli.core.destination.DestinationComponent.java

/**
 * Returns <code>true</code>, if the given URL starts with a known
 * protocol specifier, i.e. <tt>http://</tt> or <tt>https://</tt>.
 *
 * @param url  the URL to check./*from ww  w .j  a  v a2 s. c om*/
 */
@Override
public boolean isSupportedProtocol(URL url) {
    String protocol = url.getProtocol();
    return protocol.equals(HTTP) || protocol.equals(HTTPS);
}

From source file:org.dataconservancy.access.connector.HttpDcsSearchIteratorTest.java

@Override
protected DcsConnectorConfig getConnectorConfig() {
    DcsConnectorConfig config = new DcsConnectorConfig();
    try {/*w  ww  .  j a  v  a2 s. c om*/
        URL u = new URL(
                String.format(accessServiceUrl, testServer.getServiceHostName(), testServer.getServicePort()));
        config.setScheme(u.getProtocol());
        config.setHost(u.getHost());
        config.setPort(u.getPort());
        config.setContextPath(u.getPath());
        config.setMaxOpenConn(1);
    } catch (MalformedURLException e) {
        fail("Unable to construct connector configuration: " + e.getMessage());
    }

    return config;
}