Example usage for java.net URL getHost

List of usage examples for java.net URL getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Gets the host name of this URL , if applicable.

Usage

From source file:com.emcopentechnologies.viprcloudstorage.WAStorageClient.java

/**
 * Generates SAS URL for blob in Cloud storage account
 * @param storageAccountName//from   w w  w. ja  va 2s. co m
 * @param storageAccountKey
 * @param containerName
 * @param strBlobURL
 * @return SAS URL
 * @throws Exception
 */
public static String generateSASURL(String storageAccountName, String storageAccountKey, String containerName,
        String saBlobEndPoint) throws Exception {
    StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(storageAccountName,
            storageAccountKey);
    URL blobURL = new URL(saBlobEndPoint);
    String saBlobURI = new StringBuilder().append(blobURL.getProtocol()).append("://")
            .append(storageAccountName).append(".").append(blobURL.getHost()).append("/").toString();
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(credentials, new URI(saBlobURI),
            new URI(getCustomURI(storageAccountName, QUEUE, saBlobURI)),
            new URI(getCustomURI(storageAccountName, TABLE, saBlobURI)));
    // Create the blob client.
    CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference(containerName);

    // At this point need to throw an error back since container itself did not exist.
    if (!container.exists()) {
        throw new Exception("WAStorageClient: generateSASURL: Container " + containerName
                + " does not exist in storage account " + storageAccountName);
    }

    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.setTime(new Date());

    //policy.setSharedAccessStartTime(calendar.getTime());
    calendar.add(Calendar.HOUR, 1);
    policy.setSharedAccessExpiryTime(calendar.getTime());
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));

    BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
    containerPermissions.getSharedAccessPolicies().put("jenkins" + System.currentTimeMillis(), policy);
    container.uploadPermissions(containerPermissions);

    // Create a shared access signature for the container.
    String sas = container.generateSharedAccessSignature(policy, null);

    return sas;
}

From source file:hudson.plugins.ec2.EC2Cloud.java

/***
 * Connect to an EC2 instance./*from  ww  w. java  2 s  . c o  m*/
 * @return {@link AmazonEC2} client
 */
public synchronized static AmazonEC2 connect(String accessId, Secret secretKey, URL endpoint) {
    awsCredentials = new BasicAWSCredentials(accessId, Secret.toString(secretKey));
    ClientConfiguration config = new ClientConfiguration();
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
    if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        config.setProxyHost(address.getHostName());
        config.setProxyPort(address.getPort());
        if (null != proxyConfig.getUserName()) {
            config.setProxyUsername(proxyConfig.getUserName());
            config.setProxyPassword(proxyConfig.getPassword());
        }
    }
    AmazonEC2 client = new AmazonEC2Client(awsCredentials, config);
    client.setEndpoint(endpoint.toString());
    return client;
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Extracts domain name from the url. Also crops www.
 *
 * @param url url/*from  w  w  w .  j a v  a 2  s .  com*/
 * @return domain name
 */
public static String getDomainName(URL url) {
    String host = url.getHost();

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

    int dotIndex = host.lastIndexOf('.');
    if (dotIndex <= 0 || dotIndex == (host.length() - 1)) {
        // Check that dot is not the first or last char
        return null;
    }

    return StringUtils.lowerCase(cropWww(host));
}

From source file:com.zimbra.cs.util.SpamExtract.java

private static void extract(String authToken, Account account, Server server, String query, File outdir,
        boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException {
    String soapURL = getSoapURL(server, false);

    URL restURL = getServerURL(server, false);
    HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr
    HttpState state = new HttpState();
    GetMethod gm = new GetMethod();
    gm.setFollowRedirects(true);/* ww  w  .ja  va 2  s .  c  o m*/
    Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1,
            false);
    state.addCookie(authCookie);
    hc.setState(state);
    hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(),
            Protocol.getProtocol(restURL.getProtocol()));
    gm.getParams().setSoTimeout(60000);

    if (verbose) {
        LOG.info("Mailbox requests to: " + restURL);
    }

    SoapHttpTransport transport = new SoapHttpTransport(soapURL);
    transport.setRetryCount(1);
    transport.setTimeout(0);
    transport.setAuthToken(authToken);

    int totalProcessed = 0;
    boolean haveMore = true;
    int offset = 0;
    while (haveMore) {
        Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST);
        searchReq.addElement(MailConstants.A_QUERY).setText(query);
        searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString());
        searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset);
        searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE);

        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchReq.prettyPrint());
            }
            Element searchResp = transport.invoke(searchReq, false, true, account.getId());
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchResp.prettyPrint());
            }

            StringBuilder deleteList = new StringBuilder();

            List<String> ids = new ArrayList<String>();
            for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) {
                offset++;
                Element e = iter.next();
                String mid = e.getAttribute(MailConstants.A_ID);
                if (mid == null) {
                    LOG.warn("null message id SOAP response");
                    continue;
                }

                LOG.debug("adding id %s", mid);
                ids.add(mid);
                if (ids.size() >= BATCH_SIZE || !iter.hasNext()) {
                    StringBuilder path = new StringBuilder("/service/user/" + account.getName()
                            + "/?fmt=tgz&list=" + StringUtils.join(ids, ","));
                    LOG.debug("sending request for path %s", path.toString());
                    List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw);
                    if (ids.size() > extractedIds.size()) {
                        ids.removeAll(extractedIds);
                        LOG.warn("failed to extract %s", ids);
                    }
                    for (String id : extractedIds) {
                        deleteList.append(id).append(',');
                    }

                    ids.clear();
                }
                totalProcessed++;
            }

            haveMore = false;
            String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE);
            if (more != null && more.length() > 0) {
                try {
                    int m = Integer.parseInt(more);
                    if (m > 0) {
                        haveMore = true;
                        try {
                            Thread.sleep(SLEEP_TIME);
                        } catch (InterruptedException e) {
                        }
                    }
                } catch (NumberFormatException nfe) {
                    LOG.warn("more flag from server not a number: " + more, nfe);
                }
            }

            if (delete && deleteList.length() > 0) {
                deleteList.deleteCharAt(deleteList.length() - 1); // -1 removes trailing comma
                Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST);
                Element action = msgActionReq.addElement(MailConstants.E_ACTION);
                action.addAttribute(MailConstants.A_ID, deleteList.toString());
                action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionReq.prettyPrint());
                }
                Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionResp.prettyPrint());
                }
                offset = 0; //put offset back to 0 so we always get top N messages even after delete
            }
        } finally {
            gm.releaseConnection();
        }

    }
    LOG.info("Total messages processed: " + totalProcessed);
}

From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

public static URI URI(String urlString) {

    try {//from w  ww. j  av  a  2 s . c  om
        final URL url = new URL(urlString);

        return new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(),
                null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.erudika.para.utils.Utils.java

/**
 * Returns the host part of the URL/*from   w ww  .  j  a  va2s .  c o  m*/
 * @param url a URL
 * @return just the host
 */
public static String getHostFromURL(String url) {
    URL u = toURL(url);
    String host = (u == null) ? "" : u.getHost();
    return host;
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngineImpl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, boolean redirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    HttpClientBuilder builder = HttpClients.custom();

    // redirect/*  w ww.  j  av a2 s  .c  o  m*/
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    if (timeout > 0)
        builder.setConnectionTimeToLive(timeout, TimeUnit.MILLISECONDS);
    HttpContext context = setCredentials(builder, hh, username, password, false);
    setProxy(builder, request, proxy);
    CloseableHttpClient client = builder.build();
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, client.execute(request, context));
}

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

/**
 *
 * @param urlString//from w  w  w.ja v a 2 s. 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:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);//from   w  w w  .ja  v  a  2s .  c o  m
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, int maxRedirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    // TODO HttpConnectionManager manager=new SimpleHttpConnectionManager();//MultiThreadedHttpConnectionManager();
    BasicHttpParams params = new BasicHttpParams();
    DefaultHttpClient client = createClient(params, maxRedirect);
    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);/*from w  ww  .  j  a v  a  2  s  .  c o  m*/
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    setTimeout(params, timeout);
    HttpContext context = setCredentials(client, hh, username, password, false);
    setProxy(client, request, proxy);
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, execute(client, request, context));
}