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.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Check the http state cookies to see if we have the proper session id cookie
 *
 * @param reqUrl   URL being requested// ww w .  jav  a2  s. c  o m
 * @param state    HTTP state object
 * @param basePath base path of requests
 *
 * @return true if a cookie matching the basePath, server host and port, and request protocol and appropriate
 *         session cookie name is found
 */
public static boolean hasSessionCookie(final URL reqUrl, final HttpState state, final String basePath) {

    final CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    final Cookie[] initcookies = cookiespec.match(reqUrl.getHost(),
            reqUrl.getPort() > 0 ? reqUrl.getPort() : 80, basePath.endsWith("/") ? basePath : basePath + "/",
            HTTP_SECURE_PROTOCOL.equalsIgnoreCase(reqUrl.getProtocol()), state.getCookies());
    boolean hasSession = false;
    if (initcookies.length == 0) {
        hasSession = false;
    } else {
        for (final Cookie cookie : initcookies) {
            if (JAVA_SESSION_COOKIE_NAME.equals(cookie.getName())
                    || JAVA_SESSION_COOKIE_PATTERN.matcher(cookie.getName()).matches()) {
                logger.debug("Saw session cookie: " + cookie.getName());
                hasSession = true;
                break;
            }
        }
    }
    return hasSession;
}

From source file:com.netscape.cmstools.cli.MainCLI.java

public static CAClient createCAClient(PKIClient client) throws Exception {

    ClientConfig config = client.getConfig();
    CAClient caClient = new CAClient(client);

    while (!caClient.exists()) {
        System.err.println("Error: CA subsystem not available");

        URL serverURI = config.getServerURL();
        String uri = serverURI.getProtocol() + "://" + serverURI.getHost() + ":" + serverURI.getPort();

        System.out.print("CA server URL [" + uri + "]: ");
        System.out.flush();/*from w w w.  ja va  2s.  c  o  m*/

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = reader.readLine().trim();
        if (!line.equals("")) {
            uri = line;
        }

        config = new ClientConfig(client.getConfig());
        config.setServerURL(uri);

        client = new PKIClient(config);
        caClient = new CAClient(client);
    }

    return caClient;
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.drilldown.PentahoParameterRefreshHandler.java

private static String getParameterServicePath(final AuthenticationData loginData,
        final PentahoPathModel pathModel) {
    try {//ww  w .j a v a  2 s .  co m
        final FileObject fileSystemRoot = PublishUtil.createVFSConnection(VFS.getManager(), loginData);
        final FileSystem fileSystem = fileSystemRoot.getFileSystem();

        // as of version 3.7 we do not need to check anything other than that the version information is there
        // later we may have to add additional checks in here to filter out known broken versions.

        final String localPath = pathModel.getLocalPath();
        final FileObject object = fileSystemRoot.resolveFile(localPath);
        final FileContent content = object.getContent();
        final String majorVersionText = (String) fileSystem.getAttribute(WebSolutionFileSystem.MAJOR_VERSION);

        if (StringUtils.isEmpty(majorVersionText) == false) {
            final String paramService = (String) content.getAttribute("param-service-url");
            if (StringUtils.isEmpty(paramService)) {
                return null;
            }
            if (paramService.startsWith("http://") || paramService.startsWith("https://")) {
                return paramService;
            }

            try {
                // Encode the URL (must use URI as URL encoding doesn't work on spaces correctly)
                final URL target = new URL(loginData.getUrl());
                final String host;
                if (target.getPort() != -1) {
                    host = target.getHost() + ":" + target.getPort();
                } else {
                    host = target.getHost();
                }

                return target.getProtocol() + "://" + host + paramService;
            } catch (MalformedURLException e) {
                UncaughtExceptionsModel.getInstance().addException(e);
                return null;
            }
        }

        final String extension = IOUtils.getInstance().getFileExtension(localPath);
        if (".prpt".equals(extension)) {
            logger.debug(
                    "Ancient pentaho system detected: parameter service does not deliver valid parameter values");

            final String name = pathModel.getName();
            final String path = pathModel.getPath();
            final String solution = pathModel.getSolution();

            final FastMessageFormat messageFormat = new FastMessageFormat(
                    "/content/reporting/?renderMode=XML&solution={0}&path={1}&name={2}");
            messageFormat.setNullString("");
            return loginData.getUrl() + messageFormat.format(new Object[] { solution, path, name });
        }

        logger.debug("Ancient pentaho system detected: We will not have access to a working parameter service");
        return null;
    } catch (FileSystemException e) {
        UncaughtExceptionsModel.getInstance().addException(e);
        return null;
    }
}

From source file:org.opencastproject.util.IoSupport.java

/**
 * Convenience method to read in a file from either a remote or local source.
 *
 * @param url//from  w w  w .  j a v a2s .c o  m
 *         The {@code URL} to read the source data from.
 * @param trustedClient
 *         The {@code TrustedHttpClient} which should be used to communicate with the remote server. This can be null
 *         for local file reads.
 * @return A String containing the source data or null in the case of an error.
 * @deprecated this method doesn't support UTF8 or handle HTTP response codes
 */
public static String readFileFromURL(URL url, TrustedHttpClient trustedClient) {
    StringBuilder sb = new StringBuilder();
    DataInputStream in = null;
    HttpResponse response = null;
    try {
        // Do different things depending on what we're reading...
        if ("file".equals(url.getProtocol())) {
            in = new DataInputStream(url.openStream());
        } else {
            if (trustedClient == null) {
                logger.error("Unable to read from remote source {} because trusted client is null!",
                        url.getFile());
                return null;
            }
            HttpGet get = new HttpGet(url.toURI());
            try {
                response = trustedClient.execute(get);
            } catch (TrustedHttpClientException e) {
                logger.warn("Unable to fetch file from {}.", url, e);
                trustedClient.close(response);
                return null;
            }
            in = new DataInputStream(response.getEntity().getContent());
        }
        int c = 0;
        while ((c = in.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        logger.warn("IOException attempting to get file from {}.", url);
        return null;
    } catch (URISyntaxException e) {
        logger.warn("URI error attempting to get file from {}.", url);
        return null;
    } catch (NullPointerException e) {
        logger.warn("Nullpointer attempting to get file from {}.", url);
        return null;
    } finally {
        IOUtils.closeQuietly(in);

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

    return sb.toString();
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified port.
 * @param u the URL on which to base the returned URL
 * @param newPort the new port to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified port
 * @throws MalformedURLException if there is a problem creating the new URL
 *///w w w .ja va2s.c  o m
public static URL getUrlWithNewPort(final URL u, final int newPort) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), newPort, u.getPath(), u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified reference.
 * @param u the URL on which to base the returned URL
 * @param newRef the new reference to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified reference
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*from w w  w. ja va  2s  .  co  m*/
public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), u.getPath(), newRef, u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified host.
 * @param u the URL on which to base the returned URL
 * @param newHost the new host to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified host
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from   w  w w  .j  a v a 2  s . c  om
public static URL getUrlWithNewHost(final URL u, final String newHost) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), newHost, u.getPort(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified path.
 * @param u the URL on which to base the returned URL
 * @param newPath the new path to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified path
 * @throws MalformedURLException if there is a problem creating the new URL
 */// w w  w  .j a v a  2  s . co m
public static URL getUrlWithNewPath(final URL u, final String newPath) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), newPath, u.getRef(), u.getQuery());
}

From source file:com.ms.commons.test.classloader.util.AntxconfigUtil.java

@SuppressWarnings("unchecked")
private static void autoconf(File tmp, String autoconfigPath, String autoconfigFile, PrintStream out)
        throws Exception {
    Enumeration<URL> urls = AntxconfigUtil.class.getClassLoader().getResources(autoconfigFile);
    for (; urls.hasMoreElements();) {
        URL url = urls.nextElement();
        // copy xml
        File autoconfFile = new File(tmp, autoconfigFile);
        writeUrlToFile(url, autoconfFile);
        // copy vm
        SAXBuilder b = new SAXBuilder();
        Document document = b.build(autoconfFile);
        List<Element> elements = XPath.selectNodes(document, GEN_PATH);
        for (Element element : elements) {
            String path = url.getPath();
            String vm = element.getAttributeValue("template");
            String vmPath = StringUtils.substringBeforeLast(path, "/") + "/" + vm;
            URL vmUrl = new URL(url.getProtocol(), url.getHost(), vmPath);
            File vmFile = new File(tmp, autoconfigPath + "/" + vm);
            writeUrlToFile(vmUrl, vmFile);
        }/*from  w w  w.  j  a  v  a  2  s  . c o  m*/
        // call antxconfig
        String args = "";
        if (new File(DEFAULT_ANTX_FILE).isFile()) {
            args = " -u " + DEFAULT_ANTX_FILE;
        }

        Process p = Runtime.getRuntime().exec(ANTXCONFIG_CMD + args, null, tmp);
        BufferedInputStream in = new BufferedInputStream(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String s;
        while ((s = br.readLine()) != null) {
            out.println(new String(s.getBytes(), ENDODING));
        }
        FileUtils.deleteDirectory(new File(tmp, autoconfigPath));
    }
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified query string.
 * @param u the URL on which to base the returned URL
 * @param newQuery the new query string to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified query string
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*  ww  w.j  av  a2s  .  c  om*/
public static URL getUrlWithNewQuery(final URL u, final String newQuery) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), u.getPath(), u.getRef(), newQuery);
}