Example usage for org.apache.commons.httpclient.util URIUtil encodePathQuery

List of usage examples for org.apache.commons.httpclient.util URIUtil encodePathQuery

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util URIUtil encodePathQuery.

Prototype

public static String encodePathQuery(String unescaped) throws URIException 

Source Link

Document

Escape and encode a string regarded as the path and query components of an URI with the default protocol charset.

Usage

From source file:com.mmounirou.spotirss.spotify.tracks.SpotifyHrefQuery.java

public Map<Track, String> getTrackHrefs(Set<Track> tracks) throws SpotifyException {
    Map<Track, String> result = Maps.newLinkedHashMap();
    int queryCount = 0;

    for (Track track : tracks) {
        String strHref = getFromCache(track);
        if (strHref == null) {
            if (queryCount != 0 && (queryCount % QUERY_LIMIT_BY_SECONDS) == 0) {
                try {
                    Thread.sleep(TimeUnit.SECONDS.toMillis(1));
                } catch (InterruptedException e) {
                    // DO nothing
                }//from   ww w .j a  va2 s.  c  o  m
            }

            try {
                Client client = Client.create();
                WebResource resource = client.resource("http://ws.spotify.com");
                String strXmlResult = resource.path("search/1/track")
                        .queryParam("q", URIUtil.encodePathQuery(track.getSong())).get(String.class);
                // System.out.println(strXmlResult);
                List<XTracks> xtracks = parseResult(strXmlResult);
                if (xtracks.isEmpty()) {
                    SpotiRss.LOGGER.warn(String.format("no spotify song for %s:%s",
                            Joiner.on("&").join(track.getArtists()), track.getSong()));
                } else {
                    strHref = findBestMatchingTrack(xtracks, track).getHref();
                    putInCache(track, strHref);
                    queryCount++;
                }
            } catch (IOException e) {
                throw new SpotifyException(e);
            } catch (SAXException e) {
                throw new SpotifyException(e);
            }
        }
        if (strHref != null) {
            result.put(track, strHref);
        }
    }
    return ImmutableMap.copyOf(result);
}

From source file:mitm.common.util.URIUtils.java

/**
 * Tries to create a URI out of the string. It first tries to create a URI directly. If that fails
 * it tries to URI encode the string and then create the URI. 
 * @param identifier//from   w w w  .  ja v a 2 s.c  o  m
 * @return
 */
public static URI toURI(String identifier, boolean encode) throws URISyntaxException {
    identifier = StringUtils.trimToNull(identifier);

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

    URI uri = null;

    try {
        uri = new URI(identifier);
    } catch (URISyntaxException e) {
        logger.debug("Not a valid URI. Trying encoded version. Identifier: " + identifier);

        if (!encode) {
            throw e;
        }

        /* 
         * try to URI encode the string
         */
        try {
            identifier = URIUtil.encodePathQuery(identifier);
        } catch (URIException urie) {
            throw new CausableURISyntaxException(identifier, urie.getMessage(), urie);
        }

        uri = new URI(identifier);
    }

    return uri;
}

From source file:ch.cyberduck.core.dav.DAVResource.java

/**
 * Get InputStream for the GET method for the given path.
 *
 * @param path the server relative path of the resource to get
 * @return InputStream//from   ww w . ja v  a  2s .  c  o  m
 * @throws IOException
 */
@Override
public InputStream getMethodData(String path) throws IOException {
    setClient();

    GetMethod method = new GetMethod(URIUtil.encodePathQuery(path));
    method.setFollowRedirects(super.followRedirects);

    generateTransactionHeader(method);
    generateAdditionalHeaders(method);
    final int statusCode = client.executeMethod(method);
    Header contentRange = method.getResponseHeader("Content-Range");
    resume = contentRange != null;

    setStatusCode(statusCode, method.getStatusText());

    if (isHttpSuccess(statusCode)) {
        Header contentEncoding = method.getResponseHeader("Content-Encoding");
        boolean zipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue());
        if (zipped) {
            return new GZIPInputStream(method.getResponseBodyAsStream());
        }
        return method.getResponseBodyAsStream();
    } else {
        throw new IOException(method.getStatusText());
    }
}

From source file:com.basus.fins.data.YahooQuote.java

public void initQuote() {
    yahooHost = new HostConfiguration();
    method = new GetMethod();
    client = new HttpClient();

    yahooHost.setHost(quoteParams.getHostUri());
    quoteParams.createQueryString();//w ww.  ja v a  2 s  .co  m
    try {
        method.setPath(URIUtil.encodePathQuery(quoteParams.getPath()));
        method.setQueryString(URIUtil.encodePathQuery(strQuery));
    } catch (URIException uriEx) {
        log.error(uriEx);
    }
}

From source file:flex.messaging.services.http.proxy.ProxyContextFilter.java

protected void setupTarget(ProxyContext context) {
    Target target = context.getTarget();
    String source = context.getUrl();
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();

    try {//from   ww w .j  a  v a2  s .co  m
        target.setUrl(new URL(source));
    } catch (MalformedURLException e) {
        try {
            //[Pete] Enhancement Req. 80172 - relative URLs from webroot (not
            //       webapp context root)
            if (clientRequest != null) {
                String baseurl = "http" + (clientRequest.isSecure() ? "s" : "") + "://"
                        + clientRequest.getServerName() + ":" + clientRequest.getServerPort();

                target.setUrl(new URL(baseurl + source));
            } else {
                ProxyException pe = new ProxyException();
                pe.setMessage(RELATIVE_NOT_SUPPORTED, new Object[] { source });
                throw pe;
            }
        } catch (MalformedURLException ex) {
            target.setUrl(null);
        }
    }

    if (target.getUrl() == null) {
        ProxyException pe = new ProxyException();
        pe.setMessage(INVALID_TARGET, new Object[] { source });
        throw pe;
    }

    target.setHTTPS(target.getUrl().getProtocol().equalsIgnoreCase("https"));
    target.setEncodedPath(target.getUrl().getPath());
    String queryStr = target.getUrl().getQuery();
    if (queryStr != null) {
        target.setEncodedPath(target.getEncodedPath() + ("?" + queryStr));
    }
    try {
        target.setEncodedPath(URIUtil.encodePathQuery(target.getEncodedPath()));
    } catch (URIException e) {
        // exception is thrown if the default charset is not supported.
        // proceed with the provided URL.
    }

    target.setHostConfig(new HostConfiguration());
    String targetHost = target.getUrl().getHost();
    int targetPort = target.getUrl().getPort();

    // Check for a custom protocol
    Protocol customProtocol = context.getProtocol();
    if (customProtocol != null) {
        target.getHostConfig().setHost(targetHost, targetPort, customProtocol);
    } else if (target.isHTTPS() && context.allowLaxSSL()) {
        target.getHostConfig().setHost(targetHost, targetPort, myhttps);
    } else {
        String targetProtocol = target.getUrl().getProtocol();
        target.getHostConfig().setHost(targetHost, targetPort, targetProtocol);
    }

    if (context.getConnectionManager() != null) {
        context.setHttpClient(new HttpClient(context.getConnectionManager()));
    } else {
        context.setHttpClient(new HttpClient());
    }

    // Determine if target domain matches this proxy's domain and port
    boolean localDomain = false;
    boolean localPort = false;
    if (clientRequest != null) {
        String proxyDomain = clientRequest.getServerName().contains(STRING_LOCALHOST) ? getResolvedLocalhost()
                : clientRequest.getServerName();
        String resolvedTargetHost = targetHost.contains(STRING_LOCALHOST) ? getResolvedLocalhost() : targetHost;
        if (proxyDomain.equalsIgnoreCase(resolvedTargetHost)) {
            localDomain = true;
            int proxyPort = clientRequest.getServerPort();
            localPort = proxyPort == targetPort;
        }
    }
    context.setLocalDomain(localDomain);
    context.setLocalPort(localPort);
}

From source file:ch.cyberduck.core.dav.DAVResource.java

/**
 * Execute the PUT method for the given path.
 *
 * @param path          the server relative path to put the data
 * @param requestEntity The input stream.
 * @return true if the method is succeeded.
 * @throws IOException/*from   w  w  w.  j  av  a  2  s  .co  m*/
 */
public boolean putMethod(String path, RequestEntity requestEntity) throws IOException {

    setClient();

    PutMethod method = new PutMethod(URIUtil.encodePathQuery(path)) {
        @Override
        public boolean getFollowRedirects() {
            // See #3206. Redirects for uploads are not allowed without user interaction by default.
            return true;
        }
    };

    // Activates 'Expect: 100-Continue' handshake. The purpose of
    // the 'Expect: 100-Continue' handshake to allow a client that is
    // sending a request message with a request body to determine if
    // the origin server is willing to accept the request (based on
    // the request headers) before the client sends the request body.
    //
    // Otherwise, upload will fail when using digest authentication.
    // Fix #2268
    method.setUseExpectHeader(true);

    generateIfHeader(method);
    method.setRequestEntity(requestEntity);

    generateTransactionHeader(method);
    generateAdditionalHeaders(method);
    int statusCode = client.executeMethod(method);

    method.releaseConnection();

    setStatusCode(statusCode, method.getStatusText());
    return isHttpSuccess(statusCode);
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Get extended address book information for person with gallookup.
 * Does not work with Exchange 2007//www. j  a  v  a 2s .  c  o m
 *
 * @param contact galfind contact
 */
public void galLookup(Contact contact) {
    if (!disableGalLookup) {
        LOGGER.debug("galLookup(" + contact.get("smtpemail1") + ')');
        GetMethod getMethod = null;
        try {
            getMethod = new GetMethod(URIUtil
                    .encodePathQuery(getCmdBasePath() + "?Cmd=gallookup&ADDR=" + contact.get("smtpemail1")));
            DavGatewayHttpClientFacade.executeGetMethod(httpClient, getMethod, true);
            Map<String, Map<String, String>> results = XMLStreamUtil
                    .getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "person", "alias");
            // add detailed information
            if (!results.isEmpty()) {
                Map<String, String> personGalLookupDetails = results.get(contact.get("uid").toLowerCase());
                if (personGalLookupDetails != null) {
                    buildGalfindContact(contact, personGalLookupDetails);
                }
            }
        } catch (IOException e) {
            LOGGER.warn("Unable to gallookup person: " + contact + ", disable GalLookup");
            disableGalLookup = true;
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
        }
    }
}

From source file:net.di2e.ecdr.search.transform.atom.AbstractAtomTransformer.java

protected Entry getMetacardEntry(CDRMetacard metacard, Map<String, Serializable> properties)
        throws URIException {

    String format = (String) properties.get(SearchConstants.FORMAT_PARAMETER);

    Entry entry = Abdera.getInstance().newEntry();

    entry.declareNS(AtomResponseConstants.GEORSS_NAMESPACE, AtomResponseConstants.GEORSS_NAMESPACE_PREFIX);
    entry.declareNS(AtomResponseConstants.RELEVANCE_NAMESPACE,
            AtomResponseConstants.RELEVANCE_NAMESPACE_PREFIX);

    entry.setId(URIUtil.encodePathQuery(metacard.getAtomId()));
    entry.setTitle(metacard.getTitle());
    entry.setUpdated(metacard.getModifiedDate());
    Date effective = metacard.getEffectiveDate();
    if (effective != null) {
        entry.setPublished(effective);/*from ww w .j a va 2 s .  com*/
    }

    entry.addCategory(metacard.getContentTypeVersion(), metacard.getContentTypeName(), "Content Type");

    String sourceId = metacard.getSourceId();
    if (sourceId != null) {
        ExtensibleElement element = entry.addExtension(AtomResponseConstants.CDRB_NAMESPACE,
                AtomResponseConstants.RESULT_SOURCE_ELEMENT, AtomResponseConstants.CDRB_NAMESPACE_PREFIX);
        element.setAttributeValue(new QName(AtomResponseConstants.CDRB_NAMESPACE, "sourceId",
                AtomResponseConstants.CDRB_NAMESPACE_PREFIX), sourceId);
        element.setText(sourceId);
    }

    addLinksToEntry(entry, metacard, format, properties);

    if (metacard.hasLocation()) {
        addLocation(entry, metacard, useGmlEncoding(properties));
    }

    Date createdDate = metacard.getCreatedDate();
    if (createdDate != null) {
        entry.addSimpleExtension(AtomResponseConstants.METACARD_ATOM_NAMESPACE,
                AtomResponseConstants.METACARD_CREATED_DATE_ELEMENT,
                AtomResponseConstants.METACARD_ATOM_NAMESPACE_PREFIX,
                DATE_FORMATTER.print(createdDate.getTime()));
    }

    Date expirationDate = metacard.getExpirationDate();
    if (expirationDate != null) {
        entry.addSimpleExtension(AtomResponseConstants.METACARD_ATOM_NAMESPACE,
                AtomResponseConstants.METADATA_EXPIRATION_DATE_ELEMENT,
                AtomResponseConstants.METACARD_ATOM_NAMESPACE_PREFIX,
                DATE_FORMATTER.print(expirationDate.getTime()));
    }

    addEntryElements(entry, metacard, properties);

    return entry;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder.// w  ww  . j av  a  2 s.c om
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:org.apache.maven.wagon.providers.webdav.CorrectedWebdavResource.java

/**
 * Get InputStream for the GET method for the given path.
 *
 * @param path the server relative path of the resource to get
 *
 * @return InputStream//from  w w  w .ja  v  a  2s.  c  o  m
 */
public InputStream getMethodData(String path) throws IOException {
    setClient();

    GetMethod method = new GetMethod(URIUtil.encodePathQuery(path));
    method.setFollowRedirects(super.followRedirects);

    generateTransactionHeader(method);
    generateAdditionalHeaders(method);
    client.executeMethod(method);

    int statusCode = method.getStatusLine().getStatusCode();
    setStatusCode(statusCode);

    if (isHttpSuccess(statusCode)) {
        Header contentEncoding = method.getResponseHeader("Content-Encoding");
        boolean isGZipped = contentEncoding == null ? false
                : "gzip".equalsIgnoreCase(contentEncoding.getValue());

        if (isGZipped) {
            return new GZIPInputStream(method.getResponseBodyAsStream());
        }
        return method.getResponseBodyAsStream();
    } else {
        throw new IOException("Couldn't get file");
    }
}