Example usage for java.net URI toASCIIString

List of usage examples for java.net URI toASCIIString

Introduction

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

Prototype

public String toASCIIString() 

Source Link

Document

Returns the content of this URI as a US-ASCII string.

Usage

From source file:org.apache.olingo.client.core.uri.URIUtils.java

public static URI buildFunctionInvokeURI(final URI uri, final Map<String, ClientValue> parameters) {
    final String rawQuery = uri.getRawQuery();
    String baseURI = StringUtils.substringBefore(uri.toASCIIString(), "?" + rawQuery);
    if (baseURI.endsWith("()")) {
        baseURI = baseURI.substring(0, baseURI.length() - 2);
    }/*from   w ww .ja v a  2s . c  o  m*/

    final StringBuilder inlineParams = new StringBuilder();
    for (Map.Entry<String, ClientValue> param : parameters.entrySet()) {
        inlineParams.append(param.getKey()).append("=");

        Object value = null;
        if (param.getValue().isPrimitive()) {
            value = param.getValue().asPrimitive().toValue();
        } else if (param.getValue().isComplex()) {
            value = param.getValue().asComplex().asJavaMap();
        } else if (param.getValue().isCollection()) {
            value = param.getValue().asCollection().asJavaCollection();
        } else if (param.getValue().isEnum()) {
            value = param.getValue().asEnum().toString();
        }

        inlineParams.append(URIUtils.escape(value)).append(',');
    }

    if (inlineParams.length() > 0) {
        inlineParams.deleteCharAt(inlineParams.length() - 1);
    }

    try {
        return URI.create(baseURI + "(" + URLEncoder.encode(inlineParams.toString(), Constants.UTF8) + ")"
                + (StringUtils.isNotBlank(rawQuery) ? "?" + rawQuery : StringUtils.EMPTY));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("While adding GET parameters", e);
    }

}

From source file:org.apache.tika.dl.imagerec.DL4JInceptionV3Net.java

public static synchronized File cachedDownload(File cacheDir, URI uri) throws IOException {

    if ("file".equals(uri.getScheme()) || uri.getScheme() == null) {
        return new File(uri);
    }/*  ww w  . jav  a  2 s .  c o  m*/
    if (!cacheDir.exists()) {
        cacheDir.mkdirs();
    }
    String[] parts = uri.toASCIIString().split("/");
    File cacheFile = new File(cacheDir, parts[parts.length - 1]);
    File successFlag = new File(cacheFile.getAbsolutePath() + ".success");

    if (cacheFile.exists() && successFlag.exists()) {
        LOG.info("Cache exist at {}. Not downloading it", cacheFile.getAbsolutePath());
    } else {
        if (successFlag.exists()) {
            successFlag.delete();
        }
        LOG.info("Cache doesn't exist. Going to make a copy");
        LOG.info("This might take a while! GET {}", uri);
        FileUtils.copyURLToFile(uri.toURL(), cacheFile, 5000, 5000);
        //restore the success flag again
        FileUtils.write(successFlag, "CopiedAt:" + System.currentTimeMillis(), Charset.defaultCharset());
    }
    return cacheFile;
}

From source file:com.amazonaws.client.regions.RegionUtils.java

/**
 * Loads a set of region metadata by downloading an XML file from the
 * given URI and parsing it./* www  .j av  a2  s.  co m*/
 *
 * @param uri the uri of the XML file to parse
 * @param config configuration for the HTTP client to use to fetch the file
 * @throws AmazonClientException on error
 */
public static synchronized void initializeFromURI(final URI uri, final ClientConfiguration config) {

    doInitializeFromURI(uri, config);
    source = uri.toASCIIString();
}

From source file:org.apache.olingo.ext.proxy.utils.ProxyUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getEntityCollectionProxy(final AbstractService<?> service, final Class<?> typeRef,
        final Class<?> typeCollectionRef, final URI targetEntitySetURI, final ClientEntitySet entitySet,
        final URI uri, final boolean checkInTheContext) {

    final List<Object> items = extractItems(service, typeRef, entitySet, uri, checkInTheContext);

    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { typeCollectionRef },
            new EntityCollectionInvocationHandler(service, items, typeCollectionRef, targetEntitySetURI,
                    uri == null ? null : service.getClient().newURIBuilder(uri.toASCIIString())));
}

From source file:io.seldon.importer.articles.FileItemAttributesImporter.java

public static String getUrlEncodedString(String input) {
    URL url = null;/* w w  w.j a va  2s .c  o  m*/
    try {
        url = new URL(input);

        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);

        String encoded = uri.toASCIIString();

        return encoded;

    } catch (MalformedURLException mue) {
        logger.error("Malformed url " + input);
        return null;
    } catch (URISyntaxException e) {
        logger.error("Failed to tranform url into uri ", e);
        return null;
    }
}

From source file:com.zimbra.common.util.HttpUtil.java

/**
 * URL-encodes the given URL path./*ww  w.ja v a  2s  . co m*/
 *
 * @return the encoded path, or the original path if it
 * is malformed
 */
public static String encodePath(String path) {
    String encoded = path;
    try {
        URI uri = new URI(null, null, path, null);
        encoded = uri.toASCIIString();
    } catch (URISyntaxException e) {
        // ignore and just return the orig path
    }
    return encoded;
}

From source file:org.eclipse.skalli.commons.URLUtils.java

/**
 * Converts a given string into a corresponding URL.
 * <p>//from   w ww  .  ja  va  2 s . c  o  m
 * Encodes path and/or query parts of the given string according to
 * {@link URI#URI(String, String, String, int, String, String, String)}.
 * For example, blanks in the path are converted to <tt>%20</tt>.
 *
 * @param s  the string to convert to an URL.
 * @return  an URL, or <code>null</code> if the string is <code>null</code>, empty or whitespace.
 *
 * @throws MalformedURLException  if the given string is not a valid URL and cannot be
 * "sanitized" to yield a valid URL even after proper encoding of its parts.
 */
public static URL stringToURL(String s) throws MalformedURLException {
    if (StringUtils.isBlank(s)) {
        return null;
    }
    URI uri = null;
    try {
        uri = new URI(s);
    } catch (URISyntaxException e) {
        URL url = new URL(s);
        try {
            uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                    url.getQuery(), url.getRef());
        } catch (URISyntaxException e1) {
            MalformedURLException e2 = new MalformedURLException(e1.getMessage());
            e2.initCause(e1);
            throw e2;
        }
    }
    return new URL(uri.toASCIIString());
}

From source file:org.apache.bigtop.bigpetstore.qstream.Utils.java

public static HttpResponse get(URI uri) throws Exception {
    HttpGet httppost = new HttpGet(uri);
    HttpClient httpclient = HttpClients.createDefault();
    //Execute and get the response.
    try {//from www.j  a  va 2  s . c o m
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200)
            System.err.println("FAILURE! " + response.getStatusLine().getStatusCode());
        return response;
    } catch (Throwable t) {
        System.out.println("failed, sleeping");
        Thread.sleep(10000);
    }
    System.err.println("FAILURE getting URI " + uri.toASCIIString());
    return null;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

/**
 * Gets <tt>ODataEntitySet</tt> from the given feed resource.
 *
 * @param resource feed resource./* www  .  j a  va  2  s .co m*/
 * @param defaultBaseURI default base URI.
 * @return <tt>ODataEntitySet</tt> object.
 */
public static ODataEntitySet getODataEntitySet(final FeedResource resource, final URI defaultBaseURI) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        Serializer.feed(resource, writer);
        writer.flush();
        LOG.debug("FeedResource -> ODataEntitySet:\n{}", writer.toString());
    }

    final URI base = defaultBaseURI == null ? resource.getBaseURI() : defaultBaseURI;

    final URI next = resource.getNext();

    final ODataEntitySet entitySet = next == null ? ODataFactory.newEntitySet()
            : ODataFactory.newEntitySet(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getCount() != null) {
        entitySet.setCount(resource.getCount());
    }

    for (EntryResource entryResource : resource.getEntries()) {
        entitySet.addEntity(getODataEntity(entryResource));
    }

    return entitySet;
}

From source file:org.apache.syncope.fit.AbstractITCase.java

public static <T> T getObject(final URI location, final Class<?> serviceClass, final Class<T> resultClass) {
    WebClient webClient = WebClient.fromClient(WebClient.client(adminClient.getService(serviceClass)));
    webClient.accept(clientFactory.getContentType().getMediaType()).to(location.toASCIIString(), false);

    return webClient.header(RESTHeaders.DOMAIN, adminClient.getDomain())
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.getJWT()).get(resultClass);
}