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.constellio.app.modules.es.connectors.http.fetcher.config.BasicUrlNormalizer.java

@Override
public String normalize(String url) throws MalformedURLException, URISyntaxException {
    String trimmedUrl = StringUtils.trim(url);
    String noFragmentUrl = StringUtils.substringBefore(trimmedUrl, "#");
    if (StringUtils.isEmpty(new URL(noFragmentUrl).getFile())) {
        noFragmentUrl = noFragmentUrl + "/";
    }/*from   w ww  .jav a 2  s. c  o m*/
    URL normalizedUrl = new URL(noFragmentUrl);
    String lowerCaseHost = StringUtils.lowerCase(normalizedUrl.getHost());
    normalizedUrl = new URL(normalizedUrl.getProtocol(), lowerCaseHost, normalizedUrl.getPort(),
            normalizedUrl.getFile());
    return normalizedUrl.toURI().normalize().toString();
}

From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.CRLDistributionPointRevocationChecker.java

private void addURL(final List<URL> list, final String uriString) {
    try {/* ww  w  .j av  a  2s.co  m*/
        // Build URI by components to facilitate proper encoding of querystring
        // e.g. http://example.com:8085/ca?action=crl&issuer=CN=CAS Test User CA
        final URL url = new URL(uriString);
        final URI uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
        list.add(uri.toURL());
    } catch (final Exception e) {
        log.warn(uriString + " is not a valid distribution point URI.");
    }
}

From source file:crawlercommons.fetcher.file.SimpleFileFetcher.java

@Override
public FetchedResult get(String url, Payload payload) throws BaseFetchException {
    String path = null;/* w  ww. j  a  va2 s.co m*/

    try {
        URL realUrl = new URL(url);
        if (!realUrl.getProtocol().equals("file")) {
            throw new BadProtocolFetchException(url);
        }

        path = realUrl.getPath();
        if (path.length() == 0) {
            path = "/";
        }
    } catch (MalformedURLException e) {
        throw new UrlFetchException(url, e.getMessage());
    }

    File f = new File(path);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        long startTime = System.currentTimeMillis();

        // TODO - limit to be no more than maxContentSize. We should read in
        // up to 16K,
        // then call Tika to detect the content type and use that to do
        // mime-type based
        // max size.

        // TODO - see Nutch's File protocol for doing a better job of
        // mapping file
        // errors (e.g. file not found) to HttpBaseException such as 404.

        // TODO - see Nutch's File protocol for handling directories -
        // return as HTML with links

        // TODO - see Nutch's File protocol for handling symlinks as
        // redirects. We'd want
        // to then enforce max redirects, which means moving the redirect
        // support back into
        // the BaseFetcher class.

        byte[] content = IOUtils.toByteArray(fis);
        long stopTime = System.currentTimeMillis();
        long totalReadTime = Math.max(1, stopTime - startTime);
        long responseRate = (content.length * 1000L) / totalReadTime;
        String contentType = "application/octet-stream";
        return new FetchedResult(url, url, System.currentTimeMillis(), new Metadata(), content, contentType,
                (int) responseRate, payload, url, 0, "localhost", HttpStatus.SC_OK, null);
    } catch (FileNotFoundException e) {
        throw new HttpFetchException(url, "Error fetching " + url, HttpStatus.SC_NOT_FOUND, new Metadata());
    } catch (IOException e) {
        throw new IOFetchException(url, e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.wavemaker.tools.ws.WebServiceToolsManager.java

/**
 * Given the systemId which could be of format like "http://www.abc.com/test.xsd" or "file:/C:/temp/test.xsd". If
 * the systemId represents a local XSD file (e.g. file:C:/temp/test.xsd) then returns it; otherwise returns null.
 * /*w  w  w.  j av a  2s.c  o  m*/
 * @param systemId
 * @return An XSD file.
 */
private static java.io.File getLocalXsdFileFromSystemId(String systemId) {
    if (!systemId.endsWith(Constants.XSD_EXT)) {
        return null;
    }
    URL url = null;
    try {
        url = new URL(systemId);
    } catch (MalformedURLException e) {
        return null;
    }
    if (url.getProtocol().equals("file") && url.getFile() != null) {
        return new java.io.File(url.getFile());
    } else {
        return null;
    }
}

From source file:com.brightcove.com.zartan.verifier.video.StreamingFLVURLVerifier.java

@ZartanCheck(value = "Primary Rendition is delivered over rtmp")
public ResultEnum assertPrimaryRenditionProtocolCorrect(UploadData upData) throws Throwable {
    URL u = getPrimaryRenditionUrl(upData);
    assertEquals("Protocol should be rtmp", "rtmp", u.getProtocol());
    return ResultEnum.PASS;
}

From source file:org.jboss.ejb3.packagemanager.retriever.impl.HttpPackageRetriever.java

/**
 * @see org.jboss.ejb3.packagemanager.retriever.PackageRetriever#retrievePackage(PackageManagerContext, URL)
 *///from w w  w  .  j a v  a  2 s. co m
@Override
public File retrievePackage(PackageManagerContext pkgMgrCtx, URL packagePath) throws PackageRetrievalException {
    if (!packagePath.getProtocol().equals("http")) {
        throw new PackageRetrievalException("Cannot handle " + packagePath);
    }
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(packagePath.toExternalForm());
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);
    } catch (Exception e) {
        throw new PackageRetrievalException("Exception while retrieving package " + packagePath, e);
    }
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new PackageRetrievalException("Http retrieval wasn't successful, returned status code  "
                + httpResponse.getStatusLine().getStatusCode());
    }
    HttpEntity httpEntity = httpResponse.getEntity();

    try {
        // TODO: should this tmp be deleted on exit?
        File tmpPkgFile = File.createTempFile("tmp", ".jar",
                pkgMgrCtx.getPackageManagerEnvironment().getPackageManagerTmpDir());
        FileOutputStream fos = new FileOutputStream(tmpPkgFile);
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(fos);
            InputStream is = httpEntity.getContent();
            bis = new BufferedInputStream(is);
            byte[] content = new byte[4096];
            int length;
            while ((length = bis.read(content)) != -1) {
                bos.write(content, 0, length);
            }
            bos.flush();
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bis != null) {
                bis.close();
            }
        }
        return tmpPkgFile;

    } catch (IOException ioe) {
        throw new PackageRetrievalException("Could not process the retrieved package", ioe);
    }
    // TODO: I need to read the HttpClient 4.x javadocs to figure out the API for closing the
    // Http connection

}

From source file:com.braindrainpain.docker.DockerRegistry.java

/**
 * Validate the URL./*from  ww  w.  ja v a2 s  . c o  m*/
 *
 * @param validationResult The list with invalid fields.
 */
public void validate(final ValidationResult validationResult) {
    try {
        if (StringUtils.isBlank(url)) {
            validationResult.addError(new ValidationError(Constants.REGISTRY, "URL is empty"));
            return;
        }
        URL validatedUrl = new URL(this.url);
        if (!protocols.contains(validatedUrl.getProtocol())) {
            validationResult.addError(new ValidationError(Constants.REGISTRY,
                    "Invalid URL: Only 'http' and 'https' protocols are supported."));
        }

        if (StringUtils.isNotBlank(validatedUrl.getUserInfo())) {
            validationResult.addError(new ValidationError(Constants.REGISTRY,
                    "User info should not be provided as part of the URL. Please provide credentials using USERNAME and PASSWORD configuration keys."));
        }
    } catch (MalformedURLException e) {
        validationResult.addError(new ValidationError(Constants.REGISTRY, "Invalid URL : " + url));
    }
}

From source file:atg.tools.dynunit.nucleus.NucleusUtils.java

/**
 * A crazily ugly and elaborate method where we try to discover
 * DYNAMO_ROOT by various means. This is mostly made complicated
 * by the ROAD DUST environment being so different from devtools.
 *//*from  w w w  .  java 2  s  .  co m*/
private static String findDynamoRoot() {
    // now let's try to find dynamo home...
    String dynamoRootStr = DynamoEnv.getProperty("atg.dynamo.root");

    if (dynamoRootStr == null) {
        // let's try to look at an environment variable, just to
        // see....
        dynamoRootStr = CommandProcessor.getProcEnvironmentVar("DYNAMO_ROOT");
    }

    if (dynamoRootStr == null) {
        // try dynamo home
        String dynamoHomeStr = DynamoEnv.getProperty("atg.dynamo.home");
        if (StringUtils.isEmpty(dynamoHomeStr)) {
            dynamoHomeStr = null;
        }

        if (dynamoHomeStr == null) {
            dynamoHomeStr = CommandProcessor.getProcEnvironmentVar("DYNAMO_HOME");

            if (StringUtils.isEmpty(dynamoHomeStr)) {
                dynamoHomeStr = null;
            }

            if (dynamoHomeStr != null) {
                // make sure home is set as a property
                DynamoEnv.setProperty("atg.dynamo.home", dynamoHomeStr);
            }
        }

        if (dynamoHomeStr != null) {
            dynamoRootStr = dynamoHomeStr.trim() + File.separator + "..";
        }
    }

    if (dynamoRootStr == null) {
        // okay, start searching upwards for something that looks like
        // a dynamo directory, which should be the case for devtools
        File currentDir = new File(new File(".").getAbsolutePath());
        String strDynamoHomeLocalConfig = "Dynamo" + File.separator + "home" + File.separator + "localconfig";

        while (currentDir != null) {
            File filePotentialHomeLocalconfigDir = new File(currentDir, strDynamoHomeLocalConfig);
            if (filePotentialHomeLocalconfigDir.exists()) {
                dynamoRootStr = new File(currentDir, "Dynamo").getAbsolutePath();
                logger.debug("Found dynamo root via parent directory: " + dynamoRootStr);
                break;
            }
            currentDir = currentDir.getParentFile();
        }
    }

    if (dynamoRootStr == null) {
        // okay, we are not devtools-ish, so let's try using our ClassLoader
        // to figure things out.

        URL urlClass = NucleusUtils.class.getClassLoader().getResource("atg/nucleus/Nucleus.class");

        // okay... this should be jar URL...
        if ((urlClass != null) && "jar".equals(urlClass.getProtocol())) {
            String strFile = urlClass.getFile();
            int separator = strFile.indexOf('!');
            strFile = strFile.substring(0, separator);

            File fileCur = null;
            try {
                fileCur = urlToFile(new URL(strFile));
            } catch (MalformedURLException e) {
                // ignore
            }

            if (fileCur != null) {
                String strSubPath = "DAS/taglib/dspjspTaglib/1.0".replace('/', File.separatorChar);
                while ((fileCur != null) && fileCur.exists()) {
                    if (new File(fileCur, strSubPath).exists()) {
                        dynamoRootStr = fileCur.getAbsolutePath();
                        logger.debug("Found dynamo root by Nucleus.class location: " + dynamoRootStr);

                        break;
                    }
                    fileCur = fileCur.getParentFile();
                }
            }
        }
    }

    return dynamoRootStr;
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static void copyResourcesRecursively(String sourceDirectory, String writeDirectory) throws IOException {
    final URL dirURL = ePADD.class.getClassLoader().getResource(sourceDirectory);
    //final String path = sourceDirectory.substring( 1 );

    if ((dirURL != null) && dirURL.getProtocol().equals("jar")) {
        final JarURLConnection jarConnection = (JarURLConnection) dirURL.openConnection();
        //System.out.println( "jarConnection is " + jarConnection );

        final ZipFile jar = jarConnection.getJarFile();

        final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            // System.out.println( name );
            if (!name.startsWith(sourceDirectory)) {
                // entry in wrong subdir -- don't copy
                continue;
            }/*from   w  w w.  ja  v a2s .c om*/
            final String entryTail = name.substring(sourceDirectory.length());

            final File f = new File(writeDirectory + File.separator + entryTail);
            if (entry.isDirectory()) {
                // if its a directory, create it
                final boolean bMade = f.mkdir();
                System.out.println((bMade ? "  creating " : "  unable to create ") + name);
            } else {
                System.out.println("  writing  " + name);
                final InputStream is = jar.getInputStream(entry);
                final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
                final byte buffer[] = new byte[4096];
                int readCount;
                // write contents of 'is' to 'os'
                while ((readCount = is.read(buffer)) > 0) {
                    os.write(buffer, 0, readCount);
                }
                os.close();
                is.close();
            }
        }

    } else if (dirURL == null) {
        throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath");
    } else {
        // not a "jar" protocol URL
        throw new IllegalStateException("don't know how to handle extracting from " + dirURL);
    }
}

From source file:org.jasig.portal.security.provider.saml.Resource.java

/**
 * Sets up the SSL parameters of a connection to the WSP, including the
 * client certificate and server certificate trust.  The program that set up
 * the SAMLSession object is responsible for providing these optional SSL
 * parameters.//from  w  ww .  j  a  v  a 2s  .  com
 *  
 * @param samlSession SAMLSession that already must contain a valid HttpClient for the WSP
 * @param resource Resource wrapper class that contains a resource URL
 * @throws MalformedURLException 
 */
public void setupWSPClientConnection(SAMLSession samlSession) throws MalformedURLException {
    URL url = new URL(resourceUrl);
    String protocol = url.getProtocol();
    int port = url.getPort();

    // Unless we are using SSL/TLS, there is no need to do the socket factory

    if (protocol.equalsIgnoreCase("https")) {
        SSLSocketFactory socketFactory = getWSPSocketFactory();

        if (port == -1)
            port = 443;

        Scheme sch = new Scheme(protocol, socketFactory, port);
        samlSession.getHttpClient().getConnectionManager().getSchemeRegistry().unregister(protocol);
        samlSession.getHttpClient().getConnectionManager().getSchemeRegistry().register(sch);
    }
}