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.crazytest.config.TestCase.java

protected void postWithCredential(String endpoint, List<NameValuePair> params)
        throws UnsupportedEncodingException, URISyntaxException, MalformedURLException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(new UrlEncodedFormEntity(params));

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;

    LOGGER.info("request:{}", postRequest.getRequestLine());
    LOGGER.info("request:{}", postRequest.getParams().getParameter("licenseeID"));
}

From source file:com.crazytest.config.TestCase.java

protected void postWithCredential(String endpoint, StringEntity params)
        throws UnsupportedEncodingException, URISyntaxException, MalformedURLException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(params);/*from  w ww  .  j a v  a 2 s  .co  m*/
    LOGGER.info("post request entity={}", postRequest);
    postRequest.setHeader("Content-Type", "application/json");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;

    LOGGER.info("request:{}", postRequest.getRequestLine());
    LOGGER.info("request:{}", postRequest.getParams().getParameter("licenseeID"));
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private HttpHost getHttpHost(URL host) {
    HttpHost httpHost = new HttpHost(host.getHost(), host.getPort(), host.getProtocol());
    return httpHost;
}

From source file:org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTAdapterListener.java

public void startListener() throws MqttException {
    if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null
            && this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) {
        String username = this.mqttBrokerConnectionConfiguration.getBrokerUsername();
        String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl();
        String scopes = this.mqttBrokerConnectionConfiguration.getBrokerScopes();
        //getJWT Client Parameters.
        if (dcrUrlString != null && !dcrUrlString.isEmpty()) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
            try {
                URL dcrUrl = new URL(dcrUrlString);
                HttpClient httpClient = MQTTUtil.getHttpClient(dcrUrl.getProtocol());
                HttpPost postMethod = new HttpPost(dcrUrlString);
                RegistrationProfile registrationProfile = new RegistrationProfile();
                registrationProfile.setCallbackUrl(MQTTEventAdapterConstants.EMPTY_STRING);
                registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE);
                registrationProfile.setOwner(username);
                registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE);
                registrationProfile.setApplicationType(MQTTEventAdapterConstants.APPLICATION_TYPE);
                registrationProfile.setClientName(username + "_" + tenantId);
                String jsonString = registrationProfile.toJSON();
                StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
                postMethod.setEntity(requestEntity);
                HttpResponse httpResponse = httpClient.execute(postMethod);
                if (httpResponse != null) {
                    String response = MQTTUtil.getResponseString(httpResponse);
                    try {
                        if (response != null) {
                            JSONParser jsonParser = new JSONParser();
                            JSONObject jsonPayload = (JSONObject) jsonParser.parse(response);
                            String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID);
                            String clientSecret = (String) jsonPayload
                                    .get(MQTTEventAdapterConstants.CLIENT_SECRET);
                            JWTClientManagerService jwtClientManagerService = MQTTUtil
                                    .getJWTClientManagerService();
                            AccessTokenInfo accessTokenInfo = jwtClientManagerService.getJWTClient()
                                    .getAccessToken(clientId, clientSecret, username, scopes);
                            connectionOptions.setUserName(accessTokenInfo.getAccessToken());
                        }//from w  ww.j a va  2s  . co  m
                    } catch (ParseException e) {
                        String msg = "error occurred while parsing client credential payload";
                        log.error(msg, e);
                    } catch (JWTClientException e) {
                        String msg = "error occurred while parsing the response from JWT Client";
                        log.error(msg, e);
                    }
                }
            } catch (MalformedURLException e) {
                log.error("Invalid dcrUrl : " + dcrUrlString);
            } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) {
                log.error("Failed to create an https connection.", e);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
        }
    }
    mqttClient.connect(connectionOptions);
    mqttClient.subscribe(topic);
}

From source file:com.pocketsoap.salesforce.soap.ChatterClient.java

private String postSuspectsComment(String postId, Map<String, String> suspects, boolean retryOnInvalidSession)
        throws MalformedURLException, IOException, XMLStreamException, FactoryConfigurationError {
    URL instanceUrl = new URL(session.instanceServerUrl);
    URL url = new URL(instanceUrl.getProtocol(), instanceUrl.getHost(), instanceUrl.getPort(),
            "/services/data/v24.0/chatter/feed-items/" + postId + "/comments");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try {/*from w w  w  .j a  v a2s  .  c  o m*/
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "OAuth " + session.sessionId);

        final Comment comment = new Comment();
        final List<MessageSegment> messageSegments = comment.getBody().getMessageSegments();
        messageSegments.add(new TextMessageSegment("Suspects: "));

        Iterator<Entry<String, String>> it = suspects.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> ids = it.next();

            String sfdcId = ids.getValue();
            if (sfdcId != null) {
                //Convert the login to an SFDC ID
                sfdcId = UserService.getUserId(session, sfdcId);
            }

            if (sfdcId == null) { //not mapped
                messageSegments.add(new TextMessageSegment(ids.getKey()));
            } else {
                messageSegments.add(new MentionMessageSegment(sfdcId));
            }

            if (it.hasNext()) {
                messageSegments.add(new TextMessageSegment(", "));
            }
        }

        final OutputStream bodyStream = conn.getOutputStream();
        ObjectMapper mapper = new ObjectMapper();
        MappingJsonFactory jsonFactory = new MappingJsonFactory();
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(bodyStream);
        mapper.writeValue(jsonGenerator, comment);
        bodyStream.close();
        conn.getInputStream().close(); //Don't care about the response
    } catch (IOException e) {
        if (retryOnInvalidSession && conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            SessionCache.get().revoke(credentials);
            return postSuspectsComment(postId, suspects, false);
        }

        BufferedReader r = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String error = "";
        String line;
        while ((line = r.readLine()) != null) {
            error += line + '\n';
        }
        System.out.println(error);
        throw e;
    }
    return null;
}

From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java

/**
 * Returns the plugin path.//from w  ww. j a  va2 s . c  o  m
 * Needs to be invoked from the main thread.
 * @return the path to the plugin JAR file.
 * @throws Exception
 */
private String getPluginPath() throws Exception {
    Enumeration urls = Thread.currentThread().getContextClassLoader().getResources(DIR_TEMPLATES);
    while (urls.hasMoreElements()) {
        URL url = (URL) urls.nextElement();
        url = getJarURLFromURL(url, "");
        if (url.getProtocol().equals("file")) {
            return url.getPath();
        }
    }
    return null;
}

From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private void setupClient(ConfigurationContext context) throws MalformedURLException, InitializationException {
    final String hosts = context.getProperty(HTTP_HOSTS).evaluateAttributeExpressions().getValue();
    String[] hostsSplit = hosts.split(",[\\s]*");
    this.url = hostsSplit[0];
    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue();
    final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();

    final Integer connectTimeout = context.getProperty(CONNECT_TIMEOUT).asInteger();
    final Integer readTimeout = context.getProperty(SOCKET_TIMEOUT).asInteger();
    final Integer retryTimeout = context.getProperty(RETRY_TIMEOUT).asInteger();

    HttpHost[] hh = new HttpHost[hostsSplit.length];
    for (int x = 0; x < hh.length; x++) {
        URL u = new URL(hostsSplit[x]);
        hh[x] = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
    }//from w w w .  ja  v a  2  s . com

    final SSLContext sslContext;
    try {
        sslContext = (sslService != null && sslService.isKeyStoreConfigured()
                && sslService.isTrustStoreConfigured()) ? buildSslContext(sslService) : null;
    } catch (IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException
            | KeyStoreException | KeyManagementException e) {
        getLogger().error("Error building up SSL Context from the supplied configuration.", e);
        throw new InitializationException(e);
    }

    RestClientBuilder builder = RestClient.builder(hh).setHttpClientConfigCallback(httpClientBuilder -> {
        if (sslContext != null) {
            httpClientBuilder = httpClientBuilder.setSSLContext(sslContext);
        }

        if (username != null && password != null) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        return httpClientBuilder;
    }).setRequestConfigCallback(requestConfigBuilder -> {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(readTimeout);
        return requestConfigBuilder;
    }).setMaxRetryTimeoutMillis(retryTimeout);

    this.client = builder.build();
    this.highLevelClient = new RestHighLevelClient(client);
}

From source file:com.github.ibm.domino.client.BaseClient.java

public void setAddress(String address) {
    try {/*from   w w w  .j  ava  2  s .com*/
        URL url = new URL(address);
        setHost(url.getHost());
        if (url.getPort() > 0) {
            setPort(url.getPort());
        }
        setProtocol(url.getProtocol());
    } catch (MalformedURLException ex) {
        Logger.getLogger(BaseClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sinosoft.one.mvc.scanning.MvcScanner.java

/**
 * ????(WEB-INF/classestarget/classes?)/*w w  w . j a v  a  2s .  c o m*/
 * 
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public List<ResourceRef> getClassesFolderResources() throws IOException {
    if (classesFolderResources == null) {
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] start to found available classes folders ...");
        }
        List<ResourceRef> classesFolderResources = new ArrayList<ResourceRef>();
        Enumeration<URL> founds = resourcePatternResolver.getClassLoader().getResources("");
        while (founds.hasMoreElements()) {
            URL urlObject = founds.nextElement();
            if (!"file".equals(urlObject.getProtocol())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] Ignored classes folder because " + "not a file protocol url: "
                            + urlObject);
                }
                continue;
            }
            String path = urlObject.getPath();
            Assert.isTrue(path.endsWith("/"));
            if (!path.endsWith("/classes/") && !path.endsWith("/test-classes/") && !path.endsWith("/bin/")) {
                if (logger.isInfoEnabled()) {
                    logger.info("[classesFolder] Ignored classes folder because "
                            + "not ends with '/classes/' or '/bin/': " + urlObject);
                }
                continue;
            }
            File file;
            try {
                file = new File(urlObject.toURI());
            } catch (URISyntaxException e) {
                throw new IOException(e.getLocalizedMessage());
            }
            if (file.isFile()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] Ignored because not a directory: " + urlObject);
                }
                continue;
            }
            Resource resource = new FileSystemResource(file);
            ResourceRef resourceRef = ResourceRef.toResourceRef(resource);
            if (classesFolderResources.contains(resourceRef)) {
                // ???
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] remove replicated classes folder: " + resourceRef);
                }
            } else {
                classesFolderResources.add(resourceRef);
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] add classes folder: " + resourceRef);
                }
            }
        }
        // ?????
        Collections.sort(classesFolderResources);
        List<ResourceRef> toRemove = new LinkedList<ResourceRef>();
        for (int i = 0; i < classesFolderResources.size(); i++) {
            ResourceRef ref = classesFolderResources.get(i);
            String refURI = ref.getResource().getURI().toString();
            for (int j = i + 1; j < classesFolderResources.size(); j++) {
                ResourceRef refj = classesFolderResources.get(j);
                String refjURI = refj.getResource().getURI().toString();
                if (refURI.startsWith(refjURI)) {
                    toRemove.add(refj);
                    if (logger.isInfoEnabled()) {
                        logger.info("[classesFolder] remove wrapper classes folder: " //
                                + refj);
                    }
                } else if (refjURI.startsWith(refURI) && refURI.length() != refjURI.length()) {
                    toRemove.add(ref);
                    if (logger.isInfoEnabled()) {
                        logger.info("[classesFolder] remove wrapper classes folder: " //
                                + ref);
                    }
                }
            }
        }
        classesFolderResources.removeAll(toRemove);
        //
        this.classesFolderResources = new ArrayList<ResourceRef>(classesFolderResources);
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] found " + classesFolderResources.size() + " classes folders: "
                    + classesFolderResources);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] found cached " + classesFolderResources.size() + " classes folders: "
                    + classesFolderResources);
        }
    }
    return Collections.unmodifiableList(classesFolderResources);
}