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:io.fabric8.apiman.ApimanStarter.java

public static void setFabric8Props(URL elasticEndpoint) throws IOException {

    log.info("** Setting API Manager Configuration Properties **");

    setConfigProp("apiman.plugins.repositories", "http://repository.jboss.org/nexus/content/groups/public/");

    setConfigProp("apiman.es.protocol", elasticEndpoint.getProtocol());
    setConfigProp("apiman.es.host", elasticEndpoint.getHost());
    setConfigProp("apiman.es.port", String.valueOf(elasticEndpoint.getPort()));

    String esIndexPrefix = getSystemPropertyOrEnvVar("apiman.es.index.prefix", ".apiman_");
    if (esIndexPrefix != null) {
        setConfigProp(ApiManagerConfig.APIMAN_MANAGER_STORAGE_ES_INDEX_NAME, esIndexPrefix + "manager");
    }//w w  w.  j  a  v  a2s  .c o m
    setConfigProp(ApiManagerConfig.APIMAN_MANAGER_STORAGE_ES_CLIENT_FACTORY,
            Fabric8EsClientFactory.class.getName());

    setConfigProp(ApiManagerConfig.APIMAN_MANAGER_STORAGE_TYPE, "es");
    setConfigProp("apiman-manager.storage.es.protocol",
            Systems.getEnvVarOrSystemProperty("apiman.es.protocol"));
    setConfigProp("apiman-manager.storage.es.host", Systems.getEnvVarOrSystemProperty("apiman.es.host"));
    setConfigProp("apiman-manager.storage.es.port", Systems.getEnvVarOrSystemProperty("apiman.es.port"));
    setConfigProp("apiman-manager.storage.es.username",
            Systems.getEnvVarOrSystemProperty("apiman.es.username"));
    setConfigProp("apiman-manager.storage.es.password",
            Systems.getEnvVarOrSystemProperty("apiman.es.password"));
    setConfigProp(ApiManagerConfig.APIMAN_MANAGER_STORAGE_ES_INITIALIZE, "true");

    setConfigProp(ApiManagerConfig.APIMAN_MANAGER_METRICS_TYPE, "es");
    setConfigProp("apiman-manager.metrics.es.protocol",
            Systems.getEnvVarOrSystemProperty("apiman.es.protocol"));
    setConfigProp("apiman-manager.metrics.es.host", Systems.getEnvVarOrSystemProperty("apiman.es.host"));
    setConfigProp("apiman-manager.metrics.es.port", Systems.getEnvVarOrSystemProperty("apiman.es.port"));
    setConfigProp("apiman-manager.metrics.es.username",
            Systems.getEnvVarOrSystemProperty("apiman.es.username"));
    setConfigProp("apiman-manager.metrics.es.password",
            Systems.getEnvVarOrSystemProperty("apiman.es.password"));

    setConfigProp(ApiManagerConfig.APIMAN_MANAGER_API_CATALOG_TYPE, KubernetesServiceCatalog.class.getName());

    File gatewayUserFile = new File(ApimanStarter.APIMAN_GATEWAY_USER_PATH);
    if (gatewayUserFile.exists()) {
        String[] user = IOUtils.toString(gatewayUserFile.toURI()).split(",");
        setConfigProp(ApimanStarter.APIMAN_GATEWAY_USERNAME, user[0]);
        setConfigProp(ApimanStarter.APIMAN_GATEWAY_PASSWORD, user[1]);
    }

    log.info("** ******************************************** **");
}

From source file:com.k42b3.aletheia.protocol.http.Util.java

/**
 * This method takes an base url and resolves the href to an url
 * // w  w  w .ja  v a  2s. c  o m
 * @param baseUrl
 * @param href
 * @return string
 * @throws MalformedURLException
 */
public static String resolveHref(String baseUrl, String href) throws MalformedURLException {
    URL currentUrl = new URL(baseUrl);

    if (href.startsWith("http://") || href.startsWith("https://")) {
        // we have an absolute url
        return href;
    } else if (href.startsWith("//")) {
        return currentUrl.getProtocol() + ":" + href;
    } else if (href.startsWith("?")) {
        return currentUrl.getProtocol() + "://" + currentUrl.getHost() + currentUrl.getPath() + href;
    } else {
        // we have an path wich must be resolved to the base url
        String completePath;

        if (href.startsWith("/")) {
            completePath = href;
        } else {
            int pos = currentUrl.getPath().lastIndexOf('/');
            String path;

            if (pos != -1) {
                path = currentUrl.getPath().substring(0, pos);
            } else {
                path = currentUrl.getPath();
            }

            completePath = path + "/" + href;
        }

        // remove dot segments from path
        String path = removeDotSegments(completePath);

        // build url
        String url = currentUrl.getProtocol() + "://" + currentUrl.getHost() + path;

        // add query params
        int sPos, ePos;
        sPos = href.indexOf('?');

        if (sPos != -1) {
            String query;
            ePos = href.indexOf('#');

            if (ePos == -1) {
                query = href.substring(sPos + 1);
            } else {
                query = href.substring(sPos + 1, ePos);
            }

            if (!query.isEmpty()) {
                url += "?" + query;
            }
        }

        // add fragment
        sPos = href.indexOf('#');

        if (sPos != -1) {
            String fragment = href.substring(sPos + 1);

            if (!fragment.isEmpty()) {
                url += "#" + fragment;
            }
        }

        return url;
    }
}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * URL may contain spaces and other nasties that will cause a failure.
 *
 * @param existing the existing URL to transform
 * @return the new URL, or old one if there was a failure
 *//*from w  w w  .  j  a v  a  2  s. c om*/
private static URL reformat(URL existing) {
    try {
        URL url = new URL(existing.toString());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        url = uri.toURL();
        return url;
    } catch (MalformedURLException e) {
        return existing;
    } catch (URISyntaxException e) {
        return existing;
    }
}

From source file:edu.kit.dama.util.release.GenerateSourceRelease.java

public static void updatePom(File destination, ReleaseConfiguration config)
        throws IOException, XmlPullParserException {
    File pomfile = new File(destination, "pom.xml");

    FileUtils.copyFile(pomfile, new File(destination, "pom.original.xml"));
    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
    FileReader reader = new FileReader(pomfile);
    Model model = mavenreader.read(reader);
    model.setPomFile(pomfile);//  w  w  w .  ja v a 2  s  .c  o m

    if (config.isRemoveDevelopers()) {
        model.setDevelopers(new ArrayList<Developer>());
    }

    if (config.isRemoveDistributionManagement()) {
        model.setDistributionManagement(null);
    }

    if (config.isRemoveCiManagement()) {
        model.setCiManagement(null);
    }

    if (config.getScmConnection() != null || config.getScmUrl() != null) {
        Scm scm = new Scm();
        scm.setConnection(config.getScmConnection());
        scm.setUrl(config.getScmUrl());
        model.setScm(scm);
    }

    for (final String profile : config.getProfilesToRemove()) {

        Profile toRemove = (Profile) org.apache.commons.collections.CollectionUtils.find(model.getProfiles(),
                new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return profile.equals(((Profile) o).getId());
                    }
                });

        if (toRemove != null) {
            model.getProfiles().remove(toRemove);
        }
    }

    for (final String plugin : config.getPluginsToRemove()) {

        Plugin toRemove = (Plugin) org.apache.commons.collections.CollectionUtils
                .find(model.getBuild().getPlugins(), new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return plugin.equals(((Plugin) o).getArtifactId());
                    }
                });

        if (toRemove != null) {
            model.getBuild().getPlugins().remove(toRemove);
        }
    }

    for (final String module : config.getModulesToRemove()) {

        String toRemove = (String) org.apache.commons.collections.CollectionUtils.find(model.getModules(),
                new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return module.equals((String) o);
                    }
                });

        if (toRemove != null) {
            model.getModules().remove(toRemove);
        }
    }

    for (String property : config.getPropertiesToRemove()) {
        model.getProperties().remove(property);
    }

    Set<Entry<String, String>> entries = config.getPropertiesToSet().entrySet();

    for (Entry<String, String> entry : entries) {
        model.getProperties().put(entry.getKey(), entry.getValue());
    }

    if (config.getLocalDependencies().length != 0) {
        //add local dependencies
        for (Dependency dependency : config.getLocalDependencies()) {
            String groupId = dependency.getGroupId();
            String artifactId = dependency.getArtifactId();
            String version = dependency.getVersion();
            String dependencyPath = groupId.replaceAll("\\.", File.separator) + File.separator + artifactId
                    + File.separator + version;
            String mavenRepoPath = MAVEN_REPOSITORY + File.separator + dependencyPath;
            String localRepoPath = config.getDestinationDirectory() + File.separator + "srcRelease"
                    + File.separator + "libs" + File.separator + dependencyPath;
            if (!new File(localRepoPath).mkdirs() && !new File(localRepoPath).exists()) {
                throw new IOException("Failed to create local repository path at " + localRepoPath);
            }
            String artifactFileName = artifactId + "-" + version + ".jar";
            String pomFileName = artifactId + "-" + version + ".pom";

            File artifact = new File(mavenRepoPath, artifactFileName);
            File pom = new File(mavenRepoPath, pomFileName);
            if (artifact.exists() && pom.exists()) {
                FileUtils.copyFile(artifact, new File(localRepoPath, artifactFileName));
                FileUtils.copyFile(pom, new File(localRepoPath, pomFileName));
            } else {
                throw new IOException("Dependency " + groupId + ":" + artifactId + ":" + version
                        + " not found at " + mavenRepoPath);
            }
        }

        //check local repo                
        boolean haveLocalRepo = false;
        for (Repository repository : model.getRepositories()) {
            String repoUrl = repository.getUrl();
            URL u = new URL(repoUrl);
            if ("file".equals(u.getProtocol())) {
                haveLocalRepo = true;
                break;
                /**
                 * <repository>
                 * <id>localRepository</id>
                 * <url>file://${basedir}/${root.relative.path}/libs</url>
                 * </repository>
                 */
            }
        }

        if (!haveLocalRepo) {
            //add local repo
            Repository localRepository = new Repository();
            localRepository.setId("localRepository");
            localRepository.setUrl("file://${basedir}/lib/");
            localRepository.setName("Local file repository");
            model.getRepositories().add(0, localRepository);
        }
    }

    // MavenProject project = new MavenProject(model);
    //check parent (fail if exists)
    //
    MavenXpp3Writer mavenwriter = new MavenXpp3Writer();
    mavenwriter.write(new FileOutputStream(new File(destination, "pom.xml")), model);
}

From source file:org.wso2.carbon.appfactory.apiManager.integration.utils.Utils.java

public static HttpPost createHttpPostRequest(URL url, List<NameValuePair> params, String path)
        throws AppFactoryException {

    URI uri;//from www.j  a  va 2 s .c om
    try {
        uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), path,
                URLEncodedUtils.format(params, "UTF-8"), null);
    } catch (URISyntaxException e) {
        String msg = "Invalid URL syntax";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }

    return new HttpPost(uri);
}

From source file:com.fujitsu.dc.test.utils.Http.java

static Socket createSocket(URL url) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException {
    String host = url.getHost();/*w ww.j  a v a  2  s .  c om*/
    int port = url.getPort();
    String proto = url.getProtocol();
    if (port < 0) {
        if ("https".equals(proto)) {
            port = PORT_HTTPS;
        }
        if ("http".equals(proto)) {
            port = PORT_HTTP;
        }
    }
    log.debug("sock: " + host + ":" + port);
    log.debug("proto: " + proto);
    // HTTPS?????????????SSLSocket???
    if ("https".equals(proto)) {
        KeyManager[] km = null;
        TrustManager[] tm = { new javax.net.ssl.X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkClientTrusted");
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkServerTrusted");
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(km, tm, new SecureRandom());
        SocketFactory sf = sslContext.getSocketFactory();
        return (SSLSocket) sf.createSocket(host, port);
    }
    // HTTPS????????
    return new Socket(host, port);
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();//from   w ww  .j a  va 2s . c  om

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:io.seldon.importer.articles.FileItemAttributesImporter.java

public static String getUrlEncodedString(String input) {
    URL url = null;
    try {/*from  w ww . ja v  a 2s.  c o  m*/
        url = new URL(input);

        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);

        String encoded = uri.toASCIIString();

        return encoded;

    } catch (MalformedURLException mue) {
        logger.error("Malformed url " + input);
        return null;
    } catch (URISyntaxException e) {
        logger.error("Failed to tranform url into uri ", e);
        return null;
    }
}

From source file:com.vmware.vchs.publicapi.samples.HttpUtils.java

/**
 * This method will parse the passed in String which is presumably a complete URL and return the
 * base URL e.g. https://vchs.vmware.api/ from the component parts of the passed in URL.
 * //  w  ww  .j a v  a 2 s  .c o  m
 * @param vDCUrl
 *            the VDC Href to parse
 * @return the base url of the vCloud
 */
public static String getHostname(String completeUrl) {
    URL baseUrl = null;

    try {
        // First create a URL object
        baseUrl = new URL(completeUrl);
        // Now use the URL implementation to provide the component parts, leaving out
        // some parts so that we can build just the base URL without the path and query string
        return new URL(baseUrl.getProtocol(), baseUrl.getHost(), baseUrl.getPort(), "").toString();
    } catch (MalformedURLException e) {
        throw new RuntimeException("Invalid URL: " + completeUrl);
    }
}

From source file:io.hummer.util.ws.AbstractNode.java

public static AbstractNode getDeployedNodeForResourceUri(UriInfo info) throws Exception {
    String absolute = info.getAbsolutePath().toString();
    URL u = new URL(absolute);
    absolute = absolute.replace("/rest/", "/");
    String path = u.getProtocol() + "://";
    absolute = absolute.substring(absolute.indexOf("://") + "://".length());
    path += absolute.substring(0, absolute.indexOf("/") + 1);
    absolute = absolute.substring(absolute.indexOf("/") + 1);
    path += absolute.substring(0, absolute.indexOf("/"));
    if (path.endsWith("REST")) {
        path = path.substring(0, path.length() - "REST".length());
    }/* w ww.jav  a  2s  . c  om*/
    AbstractNode n = deployedNodes.get(path);
    if (n == null) {
        n = deployedNodes.get(path + "?wsdl");
    }
    if (n == null) {
        if (logger.isDebugEnabled())
            logger.debug(path + " not contained in node list " + deployedNodes);
        if (deployedNodes.size() == 1) {
            n = deployedNodes.values().iterator().next();
        }
    }
    return n;
}