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.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);//from   w  w w. j  a  va 2s . c om
    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:org.openmrs.module.metadatasharing.model.validator.UrlValidator.java

/**
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should reject value if the length is greater than maxLength
 * @should reject non available protocols
 * @should not reject available protocols
 *///from   ww  w  .j  av a  2s.  c  o m
@Override
public void validate(Object target, Errors errors) {
    if (((String) target).length() > maxLength) {
        errors.reject("metadatasharing.error.subscription.url.tooLong", new Integer[] { maxLength }, null);
    }
    try {
        URL url = new URL((String) target);
        Set<String> protocols = downloaderFactory.getAvailableProtocols();
        if (!protocols.contains(url.getProtocol())) { //let's provide information about avilable protocols
            String message = "";
            Iterator<String> it = protocols.iterator();
            while (it.hasNext()) {
                message += it.next();
                if (it.hasNext())
                    message += ", ";
            }
            errors.reject("metadatasharing.error.subscription.url.unsupported", new Object[] { message }, null);
        }
    } catch (MalformedURLException e) {
        errors.reject("metadatasharing.error.subscription.url.invalid");
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the signing certificate chain URL and returns a {@code URL} object.
 *
 * @param signingCertificateChainUrl/*  w w  w. j av  a2  s  .c o m*/
 *            the external form of the URL
 * @return the URL
 * @throws CertificateException
 *             if the URL is malformed or contains an invalid hostname, an unsupported protocol,
 *             or an invalid port (if specified)
 */
static URL getAndVerifySigningCertificateChainUrl(final String signingCertificateChainUrl)
        throws CertificateException {
    try {
        URL url = new URI(signingCertificateChainUrl).normalize().toURL();
        // Validate the hostname
        if (!VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME.equalsIgnoreCase(url.getHost())) {
            throw new CertificateException(String.format(
                    "SigningCertificateChainUrl [%s] does not contain the required hostname" + " of [%s]",
                    signingCertificateChainUrl, VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME));
        }

        // Validate the path prefix
        String path = url.getPath();
        if (!path.startsWith(VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX)) {
            throw new CertificateException(String.format(
                    "SigningCertificateChainUrl path [%s] is invalid. Expecting path to " + "start with [%s]",
                    signingCertificateChainUrl, VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX));
        }

        // Validate the protocol
        String urlProtocol = url.getProtocol();
        if (!VALID_SIGNING_CERT_CHAIN_PROTOCOL.equalsIgnoreCase(urlProtocol)) {
            throw new CertificateException(
                    String.format("SigningCertificateChainUrl [%s] contains an unsupported protocol [%s]",
                            signingCertificateChainUrl, urlProtocol));
        }

        // Validate the port uses the default of 443 for HTTPS if explicitly defined in the URL
        int urlPort = url.getPort();
        if ((urlPort != UNSPECIFIED_SIGNING_CERT_CHAIN_URL_PORT_VALUE) && (urlPort != url.getDefaultPort())) {
            throw new CertificateException(
                    String.format("SigningCertificateChainUrl [%s] contains an invalid port [%d]",
                            signingCertificateChainUrl, urlPort));
        }

        return url;
    } catch (IllegalArgumentException | MalformedURLException | URISyntaxException ex) {
        throw new CertificateException(
                String.format("SigningCertificateChainUrl [%s] is malformed", signingCertificateChainUrl), ex);
    }
}

From source file:com.beyondjservlet.gateway.servlet.ProxyDetails.java

public ProxyDetails(boolean valid, String stringProxyURL, HttpProxyRule proxyRule) {
    this.valid = valid;
    this.stringProxyURL = stringProxyURL;
    this.proxyRule = proxyRule;

    int port = 0;
    String host = "";

    try {//from w ww . ja va  2s. c  o m
        URL url = new URL(stringProxyURL);
        proxyPath = url.getPath();
        protocol = url.getProtocol();
        proxyHostAndPort = url.getHost() + ":" + url.getPort();
    } catch (Exception e) {
        while (proxyHostAndPort.startsWith("/")) {
            proxyHostAndPort = proxyHostAndPort.substring(1);
        }
        host = proxyHostAndPort;
        int idx = indexOf(proxyHostAndPort, ":", "/");
        if (idx > 0) {
            host = proxyHostAndPort.substring(0, idx);
            String portText = proxyHostAndPort.substring(idx + 1);
            idx = portText.indexOf("/");
            if (idx >= 0) {
                proxyPath = portText.substring(idx);
                portText = portText.substring(0, idx);
            }

            if (StringUtils.isNotBlank(portText)) {
                // portText may be a port unless its default
                try {
                    port = Integer.parseInt(portText);
                    proxyHostAndPort = host + ":" + port;
                } catch (NumberFormatException ex) {
                    port = 80;
                    // we do not have a port, so proxyPath is the portText
                    proxyPath = "/" + portText + proxyPath;
                    proxyHostAndPort = host;
                }
            } else {
                proxyHostAndPort = host;
            }
        }
    }
}

From source file:com.smartitengineering.util.simple.reflection.DefaultClassScannerImpl.java

private URI getURI(URL url) throws URISyntaxException {
    if (url.getProtocol().equalsIgnoreCase("vfsfile")) {
        // Used with JBoss 5.x: trim prefix "vfs"
        // This code learnt and followed from project Jersey
        return new URI(url.toString().substring(3));
    } else {/*from   ww w  .j a  va  2  s .  c o m*/
        return url.toURI();
    }
}

From source file:com.webcohesion.ofx4j.client.net.OFXV1Connection.java

public ResponseEnvelope sendRequest(RequestEnvelope request, URL url) throws OFXConnectionException {
    try {/*from w  ww .  j ava2  s  . c o m*/
        if (!url.getProtocol().toLowerCase().startsWith("http")) {
            throw new IllegalArgumentException("Invalid URL: " + url + " only http(s) is supported.");
        }

        //marshal to memory so we can determine the size...
        ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
        OFXWriter ofxWriter = newOFXWriter(outBuffer);
        getMarshaller().marshal(request, ofxWriter);
        ofxWriter.close();
        logRequest(outBuffer);
        InputStream in = sendBuffer(url, outBuffer);
        return unmarshal(in);
    } catch (IOException e) {
        throw new OFXConnectionException(e);
    }
}

From source file:org.wso2.carbon.apimgt.gateway.throttling.util.KeyTemplateRetriever.java

/**
 * This method will retrieve KeyTemplates
 *
 * @return String object array which contains Blocking conditions.
 *///from  www .java2  s  .c o m
private String[] retrieveKeyTemplateData() {

    try {
        ThrottleProperties.BlockCondition blockConditionRetrieverConfiguration = ServiceReferenceHolder
                .getInstance().getThrottleProperties().getBlockCondition();
        String url = blockConditionRetrieverConfiguration.getServiceUrl() + "/keyTemplates";
        byte[] credentials = Base64.encodeBase64((blockConditionRetrieverConfiguration.getUsername() + ":"
                + blockConditionRetrieverConfiguration.getPassword()).getBytes(StandardCharsets.UTF_8));
        HttpGet method = new HttpGet(url);
        method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
        URL keyMgtURL = new URL(url);
        int keyMgtPort = keyMgtURL.getPort();
        String keyMgtProtocol = keyMgtURL.getProtocol();
        HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol);
        HttpResponse httpResponse = null;
        int retryCount = 0;
        boolean retry;
        do {
            try {
                httpResponse = httpClient.execute(method);
                retry = false;
            } catch (IOException ex) {
                retryCount++;
                if (retryCount < keyTemplateRetrievalRetries) {
                    retry = true;
                    log.warn("Failed retrieving throttling data from remote endpoint: " + ex.getMessage()
                            + ". Retrying after " + keyTemplateRetrievalTimeoutInSeconds + " seconds...");
                    Thread.sleep(keyTemplateRetrievalTimeoutInSeconds * 1000);
                } else {
                    throw ex;
                }
            }
        } while (retry);

        String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        if (responseString != null && !responseString.isEmpty()) {
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseString);
            return (String[]) jsonArray.toArray(new String[jsonArray.size()]);
        }
    } catch (IOException | InterruptedException | ParseException e) {
        log.error("Exception when retrieving throttling data from remote endpoint ", e);
    }
    return null;
}

From source file:de.spqrinfo.cups4j.operations.IppOperation.java

/**
 * Removes the port number in the submitted URL
 *
 * @param url/*ww  w .  j  a  v  a  2 s  .c  o  m*/
 * @return url without port number
 */
protected String stripPortNumber(URL url) {
    String protocol = url.getProtocol();
    if ("ipp".equals(protocol)) {
        protocol = "http";
    }

    return protocol + "://" + url.getHost() + url.getPath();
}

From source file:edu.kit.dama.staging.util.DataOrganizationUtils.java

/**
 * Generate a map of zip entries that have to be considered when zipping
 * pNode. This method calls itself recursively to traverse through
 * sub-directories. The provided map finally contains all files and folders
 * that have to be in the zip file. For files, the value of a map entry is
 * defined, for (empty) folders the value is null. The returned value is the
 * summed size of all files and can be used to decide whether or not the zip
 * should be finally created.//from w ww.  j a  v  a  2 s. co m
 *
 * @param pNode The node that should be handled. Filenodes will be directly
 * added to pMap, CollectionNodes will be traversed.
 * @param pPath The current part that is accessed.
 * @param pMap The map of resulting entries.
 *
 * @return The overall amount of data.
 */
private static long generateZipEntries(IDataOrganizationNode pNode, String pPath, Map<String, File> pMap) {
    long size = 0;
    String basePath = (pPath == null) ? pNode.getName() : pPath + "/" + pNode.getName();
    if (pNode instanceof ICollectionNode) {
        ICollectionNode node = (ICollectionNode) pNode;
        if (!node.getChildren().isEmpty()) {
            for (IDataOrganizationNode childNode : node.getChildren()) {
                size += generateZipEntries(childNode, basePath, pMap);
            }
        } else {
            //empty node
            pMap.put(basePath, null);
        }
    } else if (pNode instanceof IFileNode) {
        IFileNode node = (IFileNode) pNode;
        File f = null;
        String lfn = node.getLogicalFileName().asString();
        try {
            URL lfnUrl = new URL(lfn);
            if ("file".equals(lfnUrl.getProtocol())) {
                f = new File(lfnUrl.toURI());
                size += f.length();
            } else {
                throw new MalformedURLException(
                        "Protocol " + lfnUrl.getProtocol() + " currently not supported.");
            }
            pMap.put(basePath, f);
        } catch (MalformedURLException | URISyntaxException ex) {
            LOGGER.warn("Unsupported LFN " + lfn
                    + ". Only LFNs refering to locally accessible files are supported.");
        }
    } else {
        throw new IllegalArgumentException("Argument " + pNode
                + " is not a supported argument. Only nodes of type ICollectionNode or IFileNode are supported.");
    }
    return size;
}

From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return CookieOrigin suitable for validating session cookies from the given base URL
 *///from w  ww  .  j  a  va 2  s.  c  o  m
protected CookieOrigin cookieOrigin(final URL url) {
    return new CookieOrigin(url.getHost(), url.getPort(), cookiePath(url), url.getProtocol().equals("https"));
}