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.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//from w  w  w  .java  2 s  . c  om
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.jboss.test.util.web.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);
    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {/*  www  .ja  v  a2  s .  c  o m*/
        log.debug("Connecting to: " + url);
        String userInfo = url.getUserInfo();
        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        log.debug("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        log.debug("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        log.debug(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.jboss.ejb3.test.clusteredservice.unit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {/*from   www  . j  a va 2  s. co m*/
        log.debug("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        log.debug("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        log.debug("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        log.debug(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.jenkins_ci.update_center.repo.NexusRepositoryImpl.java

/**
 * Loads a remote repository index (.zip or .gz), convert it to Lucene index and return it.
 *//*from   w ww.  j  av a2 s . c om*/
private static File loadIndex(String id, URL url) throws IOException, UnsupportedExistingLuceneIndexException {
    File dir = new File(new File(System.getProperty("java.io.tmpdir")), "maven-index/" + id);
    File local = new File(dir, "index" + getExtension(url));
    File expanded = new File(dir, "expanded");

    URLConnection con = url.openConnection();
    if (url.getUserInfo() != null) {
        con.setRequestProperty("Authorization",
                "Basic " + new sun.misc.BASE64Encoder().encode(url.getUserInfo().getBytes()));
    }

    if (!expanded.exists() || !local.exists() || local.lastModified() != con.getLastModified()) {
        System.out.println("Downloading " + url);
        // if the download fail in the middle, only leave a broken tmp file
        dir.mkdirs();
        File tmp = new File(dir, "index_" + getExtension(url));
        FileOutputStream o = new FileOutputStream(tmp);
        try {
            IOUtils.copy(con.getInputStream(), o);
        } finally {
            o.close();
        }

        if (expanded.exists()) {
            FileUtils.deleteDirectory(expanded);
        }
        expanded.mkdirs();

        if (url.toExternalForm().endsWith(".gz")) {
            FSDirectory directory = FSDirectory.getDirectory(expanded);
            NexusIndexWriter w = new NexusIndexWriter(directory, new NexusAnalyzer(), true);
            FileInputStream in = new FileInputStream(tmp);
            try {
                IndexDataReader dr = new IndexDataReader(in);
                dr.readIndex(w, new DefaultIndexingContext(id, id, null, expanded, null, null,
                        NexusIndexer.DEFAULT_INDEX, true));
            } finally {
                IndexUtils.close(w);
                IOUtils.closeQuietly(in);
                directory.close();
            }
        } else if (url.toExternalForm().endsWith(".zip")) {
            Expand e = new Expand();
            e.setSrc(tmp);
            e.setDest(expanded);
            e.execute();
        } else {
            throw new UnsupportedOperationException("Unsupported index format: " + url);
        }

        // as a proof that the expansion was properly completed
        tmp.renameTo(local);
        local.setLastModified(con.getLastModified());
    } else {
        System.out.println("Reusing the locally cached " + url + " at " + local);
    }

    return expanded;
}

From source file:sce.RESTAppMetricJob.java

public static URL convertToURLEscapingIllegalCharacters(String string) {
    try {/*w  w w.j  a  va  2  s. c  om*/
        String decodedURL = URLDecoder.decode(string, "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());
        return uri.toURL();
    } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eionet.cr.util.URLUtil.java

/**
 *
 * @param urlString/* w w  w  .  ja v a 2s. c o m*/
 * @return
 */
public static String normalizeUrl(String urlString) {

    // if given URL string is null, return it as it is
    if (urlString == null) {
        return urlString;
    }

    // we're going to need both the URL and URI wrappers
    URL url = null;
    URI uri = null;
    try {
        url = new URL(urlString.trim());
        uri = url.toURI();
    } catch (MalformedURLException e) {
        return urlString;
    } catch (URISyntaxException e) {
        return urlString;
    }

    // get all the various parts of this URL
    String protocol = url.getProtocol();
    String userInfo = url.getUserInfo();
    String host = url.getHost();
    int port = url.getPort();
    String path = url.getPath();
    String query = url.getQuery();
    String reference = url.getRef();

    // start building the result, processing each of the above-found URL parts

    StringBuilder result = new StringBuilder();

    try {
        if (!StringUtils.isEmpty(protocol)) {
            result.append(decodeEncode(protocol.toLowerCase())).append("://");
        }

        if (!StringUtils.isEmpty(userInfo)) {
            result.append(decodeEncode(userInfo, ":")).append("@");
        }

        if (!StringUtils.isEmpty(host)) {
            result.append(decodeEncode(host.toLowerCase()));
        }

        if (port != -1 && port != 80) {
            result.append(":").append(port);
        }

        if (!StringUtils.isEmpty(path)) {
            result.append(normalizePath(path));
        }

        if (!StringUtils.isEmpty(query)) {
            String normalizedQuery = normalizeQueryString(uri);
            if (!StringUtils.isBlank(normalizedQuery)) {
                result.append("?").append(normalizedQuery);
            }
        }

        if (!StringUtils.isEmpty(reference)) {
            result.append("#").append(decodeEncode(reference));
        }
    } catch (UnsupportedEncodingException e) {
        throw new CRRuntimeException("Unsupported encoding: " + e.getMessage(), e);
    }

    return result.toString();
}

From source file:org.mycore.common.xml.MCRXMLFunctions.java

/**
 * Encodes the given URL so, that it is a valid RFC 2396 URL.
 *//*from w  w w.  jav  a2 s. c o  m*/
public static String normalizeAbsoluteURL(String url) throws MalformedURLException, URISyntaxException {
    try {
        return new URI(url).toASCIIString();
    } catch (Exception e) {
        URL testURL = new URL(url);
        URI uri = new URI(testURL.getProtocol(), testURL.getUserInfo(), testURL.getHost(), testURL.getPort(),
                testURL.getPath(), testURL.getQuery(), testURL.getRef());
        return uri.toASCIIString();
    }
}

From source file:com.gargoylesoftware.htmlunit.util.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
 *///from   w  w  w . j a va  2s.  c o m
public static URL getUrlWithNewPort(final URL u, final int newPort) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getUserInfo(), u.getHost(), newPort, u.getPath(), u.getRef(),
            u.getQuery());
}

From source file:com.gargoylesoftware.htmlunit.util.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
 *//*  ww  w .j a v  a2 s . c om*/
public static URL getUrlWithNewHost(final URL u, final String newHost) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getUserInfo(), newHost, u.getPort(), u.getPath(), u.getRef(),
            u.getQuery());
}

From source file:com.adito.reverseproxy.ReverseProxyMethodHandler.java

/**
 * Encodes a URL //from w ww .j a v a  2  s .com
 * @param location
 * @return
 */
public static final String encodeURL(String location) {

    try {
        URL url = new URL(location);

        StringBuffer buf = new StringBuffer();
        buf.append(url.getProtocol());
        buf.append("://");
        if (!Util.isNullOrTrimmedBlank(url.getUserInfo())) {
            buf.append(DAVUtilities.encodeURIUserInfo(url.getUserInfo()));
            buf.append("@");
        }
        buf.append(url.getHost());
        if (url.getPort() != -1) {
            buf.append(":");
            buf.append(url.getPort());
        }
        if (!Util.isNullOrTrimmedBlank(url.getPath())) {
            buf.append(URLUTF8Encoder.encode(url.getPath(), false));
        }
        if (!Util.isNullOrTrimmedBlank(url.getQuery())) {
            buf.append("?");
            buf.append(encodeQuery(url.getQuery()));
        }

        return buf.toString();
    } catch (MalformedURLException e) {

        int idx = location.indexOf('?');
        if (idx > -1 && idx < location.length() - 1) {
            return URLUTF8Encoder.encode(location.substring(0, idx), false) + "?"
                    + encodeQuery(location.substring(idx + 1));
        } else
            return URLUTF8Encoder.encode(location, false);
    }
}