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:org.seedstack.w20.internal.W20BridgeIT.java

@Test
@RunAsClient//from   w ww. j  a v  a  2 s . com
public void paths_are_correctly_built(@ArquillianResource URL baseUrl) {
    String response = given().auth().basic("ThePoltergeist", "bouh").expect().statusCode(200).when()
            .get(baseUrl.toString() + "seed-w20/application/configuration").getBody().asString();
    String prefix = baseUrl.toString().substring(
            (baseUrl.getProtocol() + "://" + baseUrl.getHost() + ":" + baseUrl.getPort()).length(),
            baseUrl.toString().length() - 1);
    assertThat(response).contains("\"components-path\":\"" + prefix + "/bower_components\"");
    assertThat(response).contains("\"components-path-slash\":\"" + prefix + "/bower_components/\"");
    assertThat(response).contains("\"seed-base-path\":\"" + prefix + "\"");
    assertThat(response).contains("\"seed-base-path-slash\":\"" + prefix + "/\"");
    assertThat(response).contains("\"seed-rest-path\":\"" + prefix + "\"");
    assertThat(response).contains("\"seed-rest-path-slash\":\"" + prefix + "/\"");

}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.wiktionary.WiktionaryResource.java

public WiktionaryResource(Language language, String wiktionaryDirectory)
        throws LexicalSemanticResourceException {
    try {/*w  w  w . jav a 2s .  c  o m*/
        // Check if we got an URL (file URL)
        String dir = null;
        try {
            URL url = new URL(wiktionaryDirectory);
            if ("file".equals(url.getProtocol())) {
                dir = new File(url.getPath()).getAbsolutePath();
            } else {
                throw new LexicalSemanticResourceException("Wiktionary resources have to reside on the file "
                        + "system, but are at [" + url + "]");
            }
        } catch (IOException e) {
            // Ignore
        }

        if (dir == null) {
            dir = wiktionaryDirectory;
        }

        wkt = new Wiktionary(dir);

        // use a certain Wiktionary DB
        wkt.setAllowedEntryLanguage(language);
        log.info("Setting PreferedEntryLanguage to " + language.toString());

        // use only words from a certain language
        wkt.setAllowedWordLanguage(language);
        log.info("Setting PreferedWordLanguage to " + language.toString());

        wkt.setIsCaseSensitive(isCaseSensitive);

        wktIterable = new WiktionaryEntityIterable(wkt);

        version = language.toString();

    } catch (DatabaseException e) {
        throw new LexicalSemanticResourceException(e);
    }
}

From source file:de.innovationgate.wgpublisher.WGPRequestPath.java

public static URL determineRedirectionURL(URL currentURL, String redirectProtocol, String redirectHost,
        String redirectPort) throws MalformedURLException {
    // determine current protocol, host and port
    String currentProtocol = currentURL.getProtocol();
    String currentHost = currentURL.getHost();
    String currentPort = null;/*from ww w .  jav a  2 s . c o  m*/
    if (currentURL.getPort() != -1) {
        currentPort = new Integer(currentURL.getPort()).toString();
    } else if ("http".equals(currentProtocol)) {
        currentPort = "80";
    } else if ("https".equals(currentProtocol)) {
        currentPort = "443";
    }

    //build redirectURL
    boolean redirectNecessary = false;
    StringBuffer redirectURLBuffer = new StringBuffer();
    if (redirectProtocol != null) {
        if (!currentProtocol.equalsIgnoreCase(redirectProtocol)) {
            redirectURLBuffer.append(redirectProtocol);
            redirectNecessary = true;
        } else {
            redirectURLBuffer.append(currentProtocol);
        }
    } else {
        redirectURLBuffer.append(currentProtocol);
    }

    redirectURLBuffer.append("://");

    if (redirectHost != null) {
        if (!currentHost.equalsIgnoreCase(redirectHost)) {
            redirectURLBuffer.append(redirectHost);
            redirectNecessary = true;
        } else {
            redirectURLBuffer.append(currentHost);
        }
    } else {
        redirectURLBuffer.append(currentHost);
    }

    if (redirectPort != null && currentPort != null) {
        if (!currentPort.equalsIgnoreCase(redirectPort)) {
            redirectURLBuffer.append(":" + redirectPort);
            redirectNecessary = true;
        } else {
            redirectURLBuffer.append(":" + currentPort);
        }
    } else if (currentPort != null) {
        redirectURLBuffer.append(":" + currentPort);
    }

    redirectURLBuffer.append(currentURL.getPath());

    if (currentURL.getQuery() != null) {
        redirectURLBuffer.append("?").append(currentURL.getQuery());
    }

    if (redirectNecessary) {
        URL redirectURL = new URL(redirectURLBuffer.toString());
        return redirectURL;
    } else {
        return null;
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

private String fetchDataSetId() throws IOException {
    if (dataSetName == null || authorisationHeader == null) {
        return null;
    }//w ww .j  a v  a2  s .c  o  m

    String result = null;

    URI uri = null;
    URL localUrl = new URL(url);
    try {
        uri = new URI(localUrl.getProtocol(), null, localUrl.getHost(), localUrl.getPort(), "/api/datasets",
                "name=" + dataSetName, null);
    } catch (URISyntaxException e) {
        throw new ComponentException(e);
    }

    Request request = Request.Get(uri);
    request.addHeader(authorisationHeader);
    HttpResponse response = request.execute().returnResponse();
    String content = extractResponseInformationAndConsumeResponse(response);

    if (returnStatusCode(response) != HttpServletResponse.SC_OK) {
        throw new IOException(content);
    }

    if (content != null && !"".equals(content)) {
        Object object = JsonReader.jsonToJava(content);
        if (object != null && object instanceof Object[]) {
            Object[] array = (Object[]) object;
            if (array.length > 0) {
                @SuppressWarnings("rawtypes")
                JsonObject jo = (JsonObject) array[0];
                result = (String) jo.get("id");
            }
        }
    }

    return result;
}

From source file:net.sbbi.upnp.devices.UPNPRootDevice.java

/**
 * Parsing an URL from the descriptionXML file
 * @param url the string representation fo the URL
 * @param baseURL the base device URL, needed if the url param is relative
 * @return an URL object defining the url param
 * @throws MalformedURLException if the url param or baseURL.toExternalForm() + url
 *                               cannot be parsed to create an URL object
 *//*from ww  w. ja  v  a2  s .  c om*/
public final static URL getURL(String url, URL baseURL) throws MalformedURLException {
    URL rtrVal;
    if (url == null || url.trim().length() == 0)
        return null;
    try {
        rtrVal = new URL(url);
    } catch (MalformedURLException malEx) {
        // maybe that the url is relative, we add the baseURL and reparse it
        // if relative then we take the device baser url root and add the url
        if (baseURL != null) {
            url = url.replace('\\', '/');
            if (url.charAt(0) != '/') {
                // the path is relative to the device baseURL
                String externalForm = baseURL.toExternalForm();
                if (!externalForm.endsWith("/")) {
                    externalForm += "/";
                }
                rtrVal = new URL(externalForm + url);
            } else {
                // the path is not relative
                String URLRoot = baseURL.getProtocol() + "://" + baseURL.getHost() + ":" + baseURL.getPort();
                rtrVal = new URL(URLRoot + url);
            }
        } else {
            throw malEx;
        }
    }
    return rtrVal;
}

From source file:com.sastix.cms.server.services.content.ResourceServiceTest.java

@Test
public void shouldCreateResourceFromExternalUri() throws Exception {
    URL localFile = getClass().getClassLoader().getResource("./logo.png");
    CreateResourceDTO createResourceDTO = new CreateResourceDTO();
    createResourceDTO.setResourceAuthor("Demo Author");
    createResourceDTO.setResourceExternalURI(localFile.getProtocol() + "://" + localFile.getFile());
    createResourceDTO.setResourceMediaType("image/png");
    createResourceDTO.setResourceName("logo.png");
    createResourceDTO.setResourceTenantId("zaq12345");
    ResourceDTO resourceDTO = resourceService.createResource(createResourceDTO);

    String resourceUri = resourceDTO.getResourceURI();

    //Extract TenantID
    final String tenantID = resourceUri.substring(resourceUri.lastIndexOf('-') + 1, resourceUri.indexOf("/"));

    final Path responseFile = hashedDirectoryService.getDataByURI(resourceUri, tenantID);
    File file = responseFile.toFile();

    byte[] actualBytes = Files.readAllBytes(file.toPath());
    byte[] expectedBytes = Files.readAllBytes(Paths.get(localFile.getPath()));
    Assert.assertArrayEquals(expectedBytes, actualBytes);
}

From source file:de.bahnhoefe.deutschlands.bahnhofsfotos.MyDataActivity.java

private boolean isValidHTTPURL(String urlString) {
    try {/*from www  .j  av  a 2s .c om*/
        URL url = new URL(urlString);
        if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) {
            return false;
        }
    } catch (MalformedURLException e) {
        return false;
    }
    return true;
}

From source file:edu.cornell.med.icb.io.ResourceFinder.java

/**
 * List directory contents for a resource folder. Not recursive, does not return
 * directory entries. Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param pathVal the path to find files for
 * @return Each member item (no path information)
 * @throws URISyntaxException bad URI syntax
 * @throws IOException error reading/*w  w w. jav a2s .c om*/
 */
public String[] getResourceListing(final Class clazz, final String pathVal)
        throws URISyntaxException, IOException {
    // Enforce all paths are separated by "/", they do not start with "/" and
    // the DO end with "/".
    String path = pathVal.replace("\\", "/");
    if (!path.endsWith("/")) {
        path += "/";
    }
    while (path.startsWith("/")) {
        path = path.substring(1);
    }
    URL dirURL = findResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        final String classFilename = clazz.getName().replace(".", "/") + ".class";
        dirURL = findResource(classFilename);
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf('!'));
        if (jarPath.charAt(2) == ':') {
            jarPath = jarPath.substring(1);
        }
        jarPath = URLDecoder.decode(jarPath, "UTF-8");
        final JarFile jar = new JarFile(jarPath);
        final Enumeration<JarEntry> entries = jar.entries();
        final Set<String> result = new HashSet<String>();
        while (entries.hasMoreElements()) {
            final String name = entries.nextElement().getName();
            //filter according to the path
            if (name.startsWith(path)) {
                final String entry = name.substring(path.length());
                if (entry.length() == 0) {
                    // Skip the directory entry for path
                    continue;
                }
                final int checkSubdir = entry.indexOf('/');
                if (checkSubdir >= 0) {
                    // Skip sub dirs
                    continue;
                }
                result.add(entry);
            }
        }
        return result.toArray(new String[result.size()]);
    }
    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:com.yunmall.ymsdk.net.http.AsyncHttpClient.java

/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             String with URL, should be valid URL without params
 * @param params          RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 *//*from   w  w  w.  j a  v a2 s  .c  o  m*/
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null) {
        return null;
    }
    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(),
                    _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            YmLog.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }
    url = url.replaceAll(" ", "%20");

    return url;
}

From source file:net.sourceforge.jwbf.mediawiki.live.LoginTest.java

/**
 * Login on last MW with SSL and htaccess.
 * //from   w w  w .j a v  a 2  s  . c o  m
 * @throws Exception
 *           a
 */
@Test
public final void loginWikiMWLastSSLAndHtaccess() throws Exception {

    AbstractHttpClient httpClient = getSSLFakeHttpClient();
    Version latest = Version.getLatest();

    URL u = new URL(getValue("wiki_url_latest").replace("http", "https"));

    assertEquals("https", u.getProtocol());
    int port = 443;
    {
        // test if authentication required
        HttpHost targetHost = new HttpHost(u.getHost(), port, u.getProtocol());
        HttpGet httpget = new HttpGet(u.getPath());
        HttpResponse resp = httpClient.execute(targetHost, httpget);

        assertEquals(401, resp.getStatusLine().getStatusCode());
        resp.getEntity().consumeContent();
    }

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), port),
            new UsernamePasswordCredentials(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest)));

    HttpActionClient sslFakeClient = new HttpActionClient(httpClient, u);
    bot = new MediaWikiBot(sslFakeClient);

    bot.login(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest));
    assertTrue(bot.isLoggedIn());
}