Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

In this page you can find the example usage for java.net URI getHost.

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:com.amarinfingroup.net.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString//from   w  w w. j  a  va2 s .c  o m
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                Collect.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:ac.elements.io.Signature.java

/**
 * Calculate String to Sign for SignatureVersion 2.
 * /*from w  ww . j ava  2  s  . c  o m*/
 * @param parameters
 *            request parameters
 * 
 * @return String to Sign
 * 
 * @throws java.security.SignatureException
 */
private static String calculateStringToSignV2(Map<String, String> parameters) {
    StringBuilder data = new StringBuilder();
    data.append("POST");
    data.append("\n");
    URI endpoint = null;
    try {
        endpoint = new URI(SERVICE_URL);
    } catch (URISyntaxException ex) {
        // log.error("URI Syntax Exception", ex);
        throw new RuntimeException("URI Syntax Exception thrown " + "while constructing string to sign", ex);
    }
    data.append(endpoint.getHost());
    data.append("\n");
    String uri = endpoint.getPath();
    if (uri == null || uri.length() == 0) {
        uri = "/";
    }
    data.append(urlEncode(uri, true));
    data.append("\n");
    Map<String, String> sorted = new TreeMap<String, String>();
    sorted.putAll(parameters);
    Iterator<Map.Entry<String, String>> pairs = sorted.entrySet().iterator();
    while (pairs.hasNext()) {
        Map.Entry<String, String> pair = pairs.next();
        String key = pair.getKey();
        data.append(urlEncode(key, false));
        data.append("=");
        String value = pair.getValue();
        data.append(urlEncode(value, false));
        if (pairs.hasNext()) {
            data.append("&");
        }
    }

    return data.toString();
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * get the domain portion of the uri. For example, "http://www.goo.com/index.html" would return
 * "goo.com"/*from   w  w w  .  j av  a2  s . c  om*/
 *
 * @param uri
 * @return the domain
 */
public static String getDomain(URI uri) {
    String domain = null;
    if (uri != null) {
        uri = createUriWithSchema(uri);
        // TODO: possible internationalization problem (Turkey's I and i )
        domain = uri.getHost().toLowerCase();
        // the domain splitting is to look out for some domain like "www.es" where the domain itself is 'www'
        String[] domainComponents = domain.split("\\.");
        if (domainComponents.length > 2 && domainComponents[0].equalsIgnoreCase("www")) {
            // exclude the 'www.' part
            domain = domain.substring(4);
        }
    }
    return domain;
}

From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java

public static RomData getROMFrom(final String url) throws IOException {
    final URI uri;
    try {//  ww w.j a  v a 2  s.  co  m
        uri = new URI(url);
    } catch (URISyntaxException ex) {
        throw new IOException("Error in URL '" + url + "\'", ex);
    }
    final String scheme = uri.getScheme();
    final String userInfo = uri.getUserInfo();
    final String name;
    final String password;
    if (userInfo != null) {
        final String[] splitted = userInfo.split("\\:");
        name = splitted[0];
        password = splitted[1];
    } else {
        name = null;
        password = null;
    }

    final byte[] loaded;
    if (scheme.startsWith("http")) {
        loaded = loadHTTPArchive(url);
    } else if (scheme.startsWith("ftp")) {
        loaded = loadFTPArchive(uri.getHost(), uri.getPath(), name, password);
    } else {
        throw new IllegalArgumentException("Unsupported scheme [" + scheme + ']');
    }

    final ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(loaded));

    byte[] rom48 = null;
    byte[] rom128 = null;
    byte[] romTrDos = null;

    while (true) {
        final ZipArchiveEntry entry = in.getNextZipEntry();
        if (entry == null) {
            break;
        }

        if (entry.isDirectory()) {
            continue;
        }

        if (ROM_48.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM 48 has too big size");
            }
            rom48 = new byte[16384];
            IOUtils.readFully(in, rom48, 0, size);
        } else if (ROM_128TR.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM 128TR has too big size");
            }
            rom128 = new byte[16384];
            IOUtils.readFully(in, rom128, 0, size);
        } else if (ROM_TRDOS.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM TRDOS has too big size");
            }
            romTrDos = new byte[16384];
            IOUtils.readFully(in, romTrDos, 0, size);
        }
    }

    if (rom48 == null) {
        throw new IOException(ROM_48 + " not found");
    }
    if (rom128 == null) {
        throw new IOException(ROM_128TR + " not found");
    }
    if (romTrDos == null) {
        throw new IOException(ROM_TRDOS + " not found");
    }

    return new RomData(rom48, rom128, romTrDos);
}

From source file:com.facebook.presto.hive.s3.PrestoS3FileSystem.java

/**
 * Helper function used to work around the fact that if you use an S3 bucket with an '_' that java.net.URI
 * behaves differently and sets the host value to null whereas S3 buckets without '_' have a properly
 * set host field. '_' is only allowed in S3 bucket names in us-east-1.
 *
 * @param uri The URI from which to extract a host value.
 * @return The host value where uri.getAuthority() is used when uri.getHost() returns null as long as no UserInfo is present.
 * @throws IllegalArgumentException If the bucket can not be determined from the URI.
 *//*from  w  ww  .  ja v a2  s  .c  o m*/
public static String getBucketName(URI uri) {
    if (uri.getHost() != null) {
        return uri.getHost();
    }

    if (uri.getUserInfo() == null) {
        return uri.getAuthority();
    }

    throw new IllegalArgumentException("Unable to determine S3 bucket from URI.");
}

From source file:com.smartitengineering.cms.ws.resources.content.ContentResource.java

protected static ContentResource getContentResource(String contentUrl, UriBuilder absBuilder,
        ResourceContext context)/*from w w  w .j a  v a  2s.  com*/
        throws ContainerException, IllegalArgumentException, ClassCastException, UriBuilderException {
    final URI uri;
    if (contentUrl.startsWith("http:")) {
        uri = URI.create(contentUrl);
    } else {
        URI absUri = absBuilder.build();
        uri = UriBuilder.fromPath(contentUrl).host(absUri.getHost()).port(absUri.getPort())
                .scheme(absUri.getScheme()).build();
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("URI to content is " + uri);
    }
    ContentResource resource = context.matchResource(uri, ContentResource.class);
    return resource;
}

From source file:jetbrains.buildServer.clouds.azure.asm.connector.AzureApiConnector.java

private static ArrayList<ConfigurationSet> createConfigurationSetList(int port, String serverLocation) {
    ArrayList<ConfigurationSet> retval = new ArrayList<>();
    final ConfigurationSet value = new ConfigurationSet();
    value.setConfigurationSetType(ConfigurationSetTypes.NETWORKCONFIGURATION);
    final ArrayList<InputEndpoint> endpointsList = new ArrayList<>();
    value.setInputEndpoints(endpointsList);

    if (port > 0) {
        InputEndpoint endpoint = new InputEndpoint();
        endpointsList.add(endpoint);/*w  w  w . j  a  v a 2  s.  co  m*/
        endpoint.setLocalPort(port);
        endpoint.setPort(port);
        endpoint.setProtocol("TCP");
        endpoint.setName(AzurePropertiesNames.ENDPOINT_NAME);
        final EndpointAcl acl = new EndpointAcl();
        endpoint.setEndpointAcl(acl);

        final URI serverUri = URI.create(serverLocation);
        List<InetAddress> serverAddresses = new ArrayList<>();
        try {
            serverAddresses.addAll(Arrays.asList(InetAddress.getAllByName(serverUri.getHost())));
            serverAddresses.add(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            LOG.warn("Unable to identify server name ip list", e);
        }
        final ArrayList<AccessControlListRule> aclRules = new ArrayList<>();
        acl.setRules(aclRules);
        int order = 1;
        for (final InetAddress address : serverAddresses) {
            if (!(address instanceof Inet4Address)) {
                continue;
            }
            final AccessControlListRule rule = new AccessControlListRule();
            rule.setOrder(order++);
            rule.setAction("Permit");
            rule.setRemoteSubnet(address.getHostAddress() + "/32");
            rule.setDescription("Server");
            aclRules.add(rule);
        }
    }

    retval.add(value);
    return retval;
}

From source file:com.mpower.clientcollection.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*from   w  ww  .  j a v a2 s .co  m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    //req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                ClientCollection.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static boolean validateUrl(String url, List<String> errorMsgs) {
    if (errorMsgs == null) {
        errorMsgs = new ArrayList<String>();
    }//from  w  ww. ja  va2  s.  c  o  m
    boolean result = true;
    try {
        URI uri = new URI(url);
        String schema = uri.getScheme();
        if (!"https".equalsIgnoreCase(schema) && !"http".equalsIgnoreCase(schema)) {
            errorMsgs.add("URL should starts with http or https");
            result = false;
        }
        if ("https".equalsIgnoreCase(schema) && uri.getHost().matches(Constants.IP_PATTERN)) {
            errorMsgs.add("You should use FQDN instead of ip address when using https protocol");
            result = false;
        }
    } catch (URISyntaxException e) {
        logger.error("invalid URL syntax ", e);
        errorMsgs.add("invalid URL syntax");
        return false;
    }

    return result;
}

From source file:com.smartitengineering.cms.ws.resources.content.ContentResource.java

protected static ContentTypeResource getContentTypeResource(String uri, ServerResourceInjectables injectables)
        throws ClassCastException, ContainerException {
    final URI checkUri;
    if (uri.startsWith("http:")) {
        checkUri = URI.create(uri);
    } else {/* ww  w . j ava 2 s .c o  m*/
        URI absUri = injectables.getUriInfo().getBaseUriBuilder().build();
        checkUri = UriBuilder.fromPath(uri).host(absUri.getHost()).port(absUri.getPort())
                .scheme(absUri.getScheme()).build();
    }
    return injectables.getResourceContext().matchResource(checkUri, ContentTypeResource.class);
}