Example usage for java.net URL getUserInfo

List of usage examples for java.net URL getUserInfo

Introduction

In this page you can find the example usage for java.net URL getUserInfo.

Prototype

public String getUserInfo() 

Source Link

Document

Gets the userInfo part 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  ww w . j av a2  s. c o  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:sce.RESTJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {//from w ww. j av  a  2 s .  com
        JobKey key = context.getJobDetail().getKey();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");

        URL u = new URL(url);

        //get user credentials from URL, if present
        final String usernamePassword = u.getUserInfo();

        //set the basic authentication credentials for the connection
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }

        //set the url connection, to disconnect if interrupt() is requested
        this.urlConnection = u.openConnection();
        String result = getUrlContents(this.urlConnection);

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        //if notificationEmail is defined in the job data map, then send a notification email to it
        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }

        //trigger the linked jobs of the finished job, depending on the job result [true, false]
        jobChain(context);

        //Mail.sendMail("prova", "disdsit@gmail.com", "prova di email", "", "");
        //System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (MalformedURLException e) {
        throw new JobExecutionException(e);
    } catch (IOException e) {
        throw new JobExecutionException(e);
    }
}

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

/**
 * Validate the URL./* www  .ja  v  a2 s. co  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:com.enonic.cms.core.http.HTTPService.java

private URLConnection setUpConnection(String address, int timeoutMs, int readTimeoutMs) throws IOException {
    URL url = new URL(address);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(timeoutMs > 0 ? timeoutMs : DEFAULT_CONNECTION_TIMEOUT);
    urlConn.setReadTimeout(readTimeoutMs > 0 ? readTimeoutMs : DEFAULT_READ_TIMEOUT);
    urlConn.setRequestProperty("User-Agent", userAgent);
    String userInfo = url.getUserInfo();
    if (StringUtils.isNotBlank(userInfo)) {
        String userInfoBase64Encoded = new String(Base64.encodeBase64(userInfo.getBytes()));
        urlConn.setRequestProperty("Authorization", "Basic " + userInfoBase64Encoded);
    }//from  w  w w  .j  a v a  2  s.com
    return urlConn;

}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, //from ww w . ja  v  a  2s  .co  m
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.sonar.updatecenter.mojo.HttpDownloader.java

File downloadFile(URL fileURL, File toFile) {
    log.info("Download " + fileURL + " in " + toFile);
    try {//from   w  w  w  .jav a2s  .c om
        if ("file".equals(fileURL.getProtocol())) {
            File src = new File(fileURL.toURI());
            FileUtils.copyFile(src, toFile);
        } else {
            HttpRequest request = HttpRequest.get(fileURL).followRedirects(true);
            if (fileURL.getUserInfo() != null) {
                request.header("Authorization", "Basic "
                        + com.github.kevinsawicki.http.HttpRequest.Base64.encode(fileURL.getUserInfo()));
            }

            if (!request.receive(toFile).ok()) {
                throw new IllegalStateException(request.message());
            }
        }
    } catch (Exception e) {
        FileUtils.deleteQuietly(toFile);
        throw new IllegalStateException("Fail to download " + fileURL + " to " + toFile, e);
    }
    return toFile;
}

From source file:sce.RESTJobStateful.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*from   ww w.  ja  v  a 2  s .  com*/
        JobKey key = context.getJobDetail().getKey();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");

        URL u = new URL(url);

        //get user credentials from URL, if present
        final String usernamePassword = u.getUserInfo();

        //set the basic authentication credentials for the connection
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }

        //set the url connection, to disconnect if interrupt() is requested
        this.urlConnection = u.openConnection();
        String result = getUrlContents(this.urlConnection);

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        //if notificationEmail is defined in the job data map, then send a notification email to it
        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }

        //trigger the linked jobs of the finished job, depending on the job result [true, false]
        jobChain(context);

        //Mail.sendMail("prova", "disdsit@gmail.com", "prova di email", "", "");
        System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (MalformedURLException e) {
        throw new JobExecutionException(e);
    } catch (IOException e) {
        throw new JobExecutionException(e);
    }
}

From source file:org.sakaiproject.shortenedurl.impl.RandomisedUrlService.java

/**
 * Encodes a full URL.//ww w  .j av  a  2s.co m
 * 
 * @param rawUrl the URL to encode.
 */
private String encodeUrl(String rawUrl) {
    if (StringUtils.isBlank(rawUrl)) {
        return null;
    }
    String encodedUrl = null;

    try {
        URL url = new URL(rawUrl);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        encodedUrl = uri.toASCIIString();
    } catch (Exception e) {
        log.warn("encoding url: " + rawUrl + ", " + e.getMessage(), e);
    }

    return encodedUrl;
}

From source file:io.github.bonigarcia.wdm.WdmHttpClient.java

private final BasicCredentialsProvider createBasicCredentialsProvider(String proxy, String proxyUser,
        String proxyPass, HttpHost proxyHost) {
    URL proxyUrl = determineProxyUrl(proxy);
    if (proxyUrl == null) {
        return null;
    }/*  w ww  . java  2  s  . c  o m*/
    try {
        String username = null;
        String password = null;

        // apply env value
        String userInfo = proxyUrl.getUserInfo();
        if (userInfo != null) {
            StringTokenizer st = new StringTokenizer(userInfo, ":");
            username = st.hasMoreTokens() ? URLDecoder.decode(st.nextToken(), StandardCharsets.UTF_8.name())
                    : null;
            password = st.hasMoreTokens() ? URLDecoder.decode(st.nextToken(), StandardCharsets.UTF_8.name())
                    : null;
        }
        String envProxyUser = System.getenv("HTTPS_PROXY_USER");
        String envProxyPass = System.getenv("HTTPS_PROXY_PASS");
        username = (envProxyUser != null) ? envProxyUser : username;
        password = (envProxyPass != null) ? envProxyPass : password;

        // apply option value
        username = (proxyUser != null) ? proxyUser : username;
        password = (proxyPass != null) ? proxyPass : password;

        if (username == null) {
            return null;
        }

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        return credentialsProvider;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Invalid encoding.", e);
    }
}