Example usage for org.apache.http.client.utils URIBuilder build

List of usage examples for org.apache.http.client.utils URIBuilder build

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder build.

Prototype

public URI build() throws URISyntaxException 

Source Link

Document

Builds a URI instance.

Usage

From source file:com.jaspersoft.studio.server.protocol.restv2.RestV2Connection.java

@Override
public ResourceDescriptor addOrModifyResource(IProgressMonitor monitor, ResourceDescriptor rd, File inputFile)
        throws Exception {
    URIBuilder ub = new URIBuilder(url("resources" + rd.getUriString()));
    ub.addParameter("createFolders", "true");
    ub.addParameter("overwrite", "true");
    Request req = HttpUtils.put(ub.build().toASCIIString(), sp);
    String rtype = WsTypes.INST().toRestType(rd.getWsType());
    ContentType ct = ContentType.create("application/repository." + rtype + "+" + FORMAT);
    req.bodyString(mapper.writeValueAsString(Soap2Rest.getResource(this, rd)), ct);
    ClientResource<?> crl = toObj(req, WsTypes.INST().getType(rtype), monitor);
    if (crl != null)
        return Rest2Soap.getRD(this, crl, rd);
    return null;/*  w  ww.  j  a v a 2s .c o  m*/
}

From source file:com.cloud.utils.UriUtils.java

public static String getUpdateUri(String url, boolean encrypt) {
    String updatedPath = null;/*from w w w.  j  a v a2 s  .  c  o m*/
    try {
        String query = URIUtil.getQuery(url);
        URIBuilder builder = new URIBuilder(url);
        builder.removeQuery();

        StringBuilder updatedQuery = new StringBuilder();
        List<NameValuePair> queryParams = getUserDetails(query);
        ListIterator<NameValuePair> iterator = queryParams.listIterator();
        while (iterator.hasNext()) {
            NameValuePair param = iterator.next();
            String value = null;
            if ("password".equalsIgnoreCase(param.getName()) && param.getValue() != null) {
                value = encrypt ? DBEncryptionUtil.encrypt(param.getValue())
                        : DBEncryptionUtil.decrypt(param.getValue());
            } else {
                value = param.getValue();
            }

            if (updatedQuery.length() == 0) {
                updatedQuery.append(param.getName()).append('=').append(value);
            } else {
                updatedQuery.append('&').append(param.getName()).append('=').append(value);
            }
        }

        String schemeAndHost = "";
        URI newUri = builder.build();
        if (newUri.getScheme() != null) {
            schemeAndHost = newUri.getScheme() + "://" + newUri.getHost();
        }

        updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery;
    } catch (URISyntaxException e) {
        throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage());
    }

    return updatedPath;
}

From source file:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

private List<ActivityEx> getObjectBodies(CloseableHttpClient httpclient, ExecutorService executor,
        String authorizationToken, List<Activity> activities) throws Exception {
    List<ActivityEx> activitiesEx = new ArrayList<>();
    Map<Integer, Future<String>> dataFutures = new HashMap<>();
    Map<Integer, Future<String>> parentDataFutures = new HashMap<>();
    Map<Integer, Future<String>> userFutures = new HashMap<>();
    JsonParser parser = new JsonParser();

    for (int i = 0; i < activities.size(); i++) {
        Activity activity = activities.get(i);
        if (activity.getDataUrl() != null && !activity.getDataUrl().isEmpty()) {
            URIBuilder uriBuilder = new URIBuilder(activity.getDataUrl());
            URI uri = uriBuilder.build();
            HttpGet httpget = new HttpGet(uri);
            if (!authorizationToken.isEmpty()) {
                httpget.addHeader("authorization", authorizationToken);
            }/*from w  w w.  ja  v a2 s.  com*/
            dataFutures.put(activity.getId(), executor.submit(new HttpRequestCallable(httpclient, httpget)));
        }
        if (activity.getParentDataUrl() != null && !activity.getParentDataUrl().isEmpty()) {
            URIBuilder uriBuilder = new URIBuilder(activity.getParentDataUrl());
            URI uri = uriBuilder.build();
            HttpGet httpget = new HttpGet(uri);
            if (!authorizationToken.isEmpty()) {
                httpget.addHeader("authorization", authorizationToken);
            }
            parentDataFutures.put(activity.getId(),
                    executor.submit(new HttpRequestCallable(httpclient, httpget)));
        }
        if (activity.getUserUrl() != null && !activity.getUserUrl().isEmpty()) {
            URIBuilder uriBuilder = new URIBuilder(activity.getUserUrl());
            URI uri = uriBuilder.build();
            HttpGet httpget = new HttpGet(uri);
            if (!authorizationToken.isEmpty()) {
                httpget.addHeader("authorization", authorizationToken);
            }
            userFutures.put(activity.getId(), executor.submit(new HttpRequestCallable(httpclient, httpget)));
        }
    }

    for (int i = 0; i < activities.size(); i++) {
        try {
            Activity activity = activities.get(i);
            ActivityEx activityEx = ActivityEx.getBuilderEx().activity(activity).build();
            Future<String> dataFuture = dataFutures.get(activity.getId());
            if (dataFuture != null) {
                activityEx.setData(parser.parse(dataFuture.get()));
            }
            Future<String> parentDataFuture = parentDataFutures.get(activity.getId());
            if (parentDataFuture != null) {
                activityEx.setParentData(parser.parse(parentDataFuture.get()));
            }
            Future<String> userFuture = userFutures.get(activity.getId());
            if (userFuture != null) {
                activityEx.setUser(parser.parse(userFuture.get()));
            }
            activitiesEx.add(activityEx);
        } catch (Exception ex) {
            Throwable exCause = ex.getCause();
            if (exCause instanceof ActivityTrackerException
                    && ((ActivityTrackerException) exCause).getErrorCode() == ErrorCode.AUTHORIZATION) {
                Context.logMessage(this, "Object not visible for user token or anonymous. Skip object.");
            } else if (exCause instanceof ActivityTrackerException
                    && ((ActivityTrackerException) exCause).getErrorCode() == ErrorCode.NOT_FOUND) {
                Context.logMessage(this, "Resource not found. Skip object.");
            } else {
                throw ex;
            }
        }
    }
    return activitiesEx;
}

From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java

@Override
public int PutQuery(String url, List<Pair<String, String>> queryParams, StringBuilder redirect) {
    try {//from   ww  w  .j a v  a 2s .  com
        HttpPut httpPut = new HttpPut();
        URIBuilder fileUri = new URIBuilder(url);

        if (queryParams != null) {
            for (Pair<String, String> queryParam : queryParams) {
                fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond());
            }
        }

        httpPut = new HttpPut(fileUri.build());
        CloseableHttpResponse response = clientImpl.execute(httpPut);
        try {
            Header[] hdrs = response.getHeaders("Location");
            if (redirect != null && hdrs.length > 0) {
                String redirectLocation = hdrs[0].getValue();

                redirect.append(redirectLocation);
                LOGGER.debug("Redirect to: " + redirectLocation);
            }

            return response.getStatusLine().getStatusCode();
        } finally {
            // I believe this releases the connection to the client pool, but does not
            // close the connection.
            response.close();
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Apache method putQuery: " + ex.getMessage());
    }
}

From source file:it.txt.ens.core.impl.BasicENSResource.java

/**
 * //from   w w  w .j  a v  a 2  s.co m
 * @param host
 * @param path
 * @param namespace
 * @param pattern
 * @throws IllegalArgumentException if at least one parameter is <code>null</code> or an empty string.
 * @throws URIBuildingException if an error occurs while building the URI
 */
/*private*/ BasicENSResource(String host, String path, String namespace, String pattern)
        throws IllegalArgumentException, URIBuildingException {
    if (host == null)
        throw new IllegalArgumentException("The host cannot be null");
    if (host.length() == 0)
        throw new IllegalArgumentException("The host cannot be an empty string");

    if (path == null)
        throw new IllegalArgumentException("The path cannot be null");
    if (path.length() == 0)
        throw new IllegalArgumentException("The path cannot be an empty string");

    if (namespace == null)
        throw new IllegalArgumentException("The namespace cannot be null");
    if (namespace.length() == 0)
        throw new IllegalArgumentException("The namespace cannot be an empty string");

    if (pattern == null)
        throw new IllegalArgumentException("The pattern cannot be null");
    if (pattern.length() == 0)
        throw new IllegalArgumentException("The pattern cannot be an empty string");
    this.host = host;
    this.namespace = namespace;
    if (path.startsWith(SLASH))
        this.path = path;
    else
        this.path = SLASH + path;
    this.pattern = pattern;
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.addParameter(NAMESPACE_PARAMETER_NAME, this.namespace);
    uriBuilder.addParameter(PATTERN_PARAMETER_NAME, this.pattern);
    uriBuilder.setHost(this.host);
    uriBuilder.setPath(this.path);
    uriBuilder.setScheme(URI_SCHEME);
    try {
        this.uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new URIBuildingException("getURI.URISyntaxException.log", e);
    }
}

From source file:Good_GUi.java

private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
    box += "Processing...\n";
    jTextArea1.setText(box);//  w  w  w .ja v  a  2s. c o  m
    String url = jTextField1.getText();
    HttpClient httpClient = new DefaultHttpClient();
    try {
        URIBuilder uriBuilder = new URIBuilder("https://eastus2.api.cognitive.microsoft.com/vision/v1.0/ocr");

        uriBuilder.setParameter("language", "unk");
        uriBuilder.setParameter("detectOrientation ", "true");

        URI uri = uriBuilder.build();
        HttpPost request = new HttpPost(uri);

        // Request headers - replace this example key with your valid subscription key.
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Ocp-Apim-Subscription-Key", "43a031e5db9f438aac7c50a7df692016");
        // Request body. Replace the example URL with the URL of a JPEG image containing text.
        StringEntity requestEntity = new StringEntity("{\"url\":\"" + jTextField1.getText() + "\"}");
        request.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity);
        ArrayList<String> list = new ArrayList<>();
        if (s.contains("Invalid")) {
            box += "Can't fetch the image @ " + url + "\n";
            jTextArea1.setText(box);

        } else {
            System.out.println(s);
            String[] splitted = s.split("}");
            for (String c : splitted) {
                list.add(c.substring(c.lastIndexOf(":") + 2).replaceAll("\"", ""));
            }
            String out = "";
            for (int i = 0; i < list.size(); i++) {
                out += list.get(i) + " ";
            }
            out.replaceAll("  ", " ");
            String x = "";
            for (int i = 0; i < out.length(); i++) {
                x += out.substring(i, i + 1);

            }
            try {
                PrintWriter writer = new PrintWriter("ITT.txt", "UTF-8");
                writer.println(x);
                writer.close();
                box += "Success! File saved as ITT.txt\n";
                jTextArea1.setText(box);

                ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "ITT.txt");
                pb.start();
            } catch (IOException e) {
                box += e.toString();
                jTextArea1.setText(box);
            }

            Parser p = new Parser(x);
            p.parse();
            StringSelection stringSelection = new StringSelection(p.toString());
            java.awt.datatransfer.Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
            clpbrd.setContents(stringSelection, null);
            JOptionPane.showMessageDialog(null, "Github data copied to clipboard!");
        }
    } catch (Exception e) {
        box += e.toString() + "\n";
        jTextField1.setText(box);

    }

}

From source file:net.datacrow.onlinesearch.discogs.task.DiscogsMusicSearch.java

@Override
protected DcObject getItem(Object key, boolean full) throws Exception {
    HttpClient httpClient = getHttpClient();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost("api.discogs.com");
    builder.setPath("/release/" + key);
    URI uri = builder.build();
    HttpGet httpGet = new HttpGet(uri);

    HttpOAuthHelper au = new HttpOAuthHelper("application/json");
    au.handleRequest(httpGet, _CONSUMER_KEY, _CONSUMER_SECRET);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    String response = getReponseText(httpResponse);
    httpClient.getConnectionManager().shutdown();

    MusicAlbum ma = new MusicAlbum();

    ma.addExternalReference(DcRepository.ExternalReferences._DISCOGS, (String) key);
    ma.setValue(DcObject._SYS_SERVICEURL, uri.toString());

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(response);
    JsonObject eRespone = jsonObject.getAsJsonObject("resp");
    JsonObject eRelease = eRespone.getAsJsonObject("release");

    if (eRelease != null) {
        ma.setValue(MusicAlbum._A_TITLE, eRelease.get("title").getAsString());
        ma.setValue(MusicAlbum._C_YEAR, eRelease.get("year").getAsString());
        ma.setValue(MusicAlbum._N_WEBPAGE, eRelease.get("uri").getAsString());

        ma.createReference(MusicAlbum._F_COUNTRY, eRelease.get("country").getAsString());

        setStorageMedium(ma, eRelease);/*from www .j  a  va 2s  .c om*/
        setRating(ma, eRelease);
        setGenres(ma, eRelease);
        setArtists(ma, eRelease);
        addTracks(ma, eRelease);
        setImages(ma, eRelease);
    }

    Thread.sleep(1000);
    return ma;
}

From source file:eu.hansolo.accs.RestClient.java

private JSONArray getAll(final DbCollection COLLECTION) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("api.mlab.com").setPort(80).setPath(COLLECTION.REST_URL)
                .setParameter("apiKey", MLAB_API_KEY);
        HttpGet get = new HttpGet(builder.build());
        get.setHeader("accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //throw new RuntimeException("Failed: HTTP error code: " + statusCode);
            return new JSONArray();
        }//from www .  ja va  2  s  . co  m

        String output = getFromResponse(response);
        JSONArray jsonArray = (JSONArray) JSONValue.parse(output);
        return jsonArray;
    } catch (URISyntaxException | IOException e) {
        return new JSONArray();
    }
}

From source file:org.duracloud.durastore.rest.ManifestRest.java

protected URI buildURI(String adminSpace, String contentId) throws URISyntaxException {
    String host = request.getAttribute(Constants.SERVER_HOST).toString();
    int port = (Integer) request.getAttribute(Constants.SERVER_PORT);
    String context = request.getContextPath();

    URIBuilder builder = new URIBuilder().setHost(host).setScheme("http" + (port == 443 ? "s" : ""))
            .setPath(context + "/" + adminSpace + "/" + contentId);

    if (port != 443 && port != 80) {
        builder = builder.setPort(port);
    }/*from   ww w  . j  av  a 2  s.  co  m*/

    return builder.build();
}