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

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

Introduction

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

Prototype

public URIBuilder(final URI uri) 

Source Link

Document

Construct an instance from the provided URI.

Usage

From source file:ezbake.azkaban.manager.ProjectManager.java

/**
 * Manages Azkaban projects//from  w ww  .ja  v  a 2  s.co m
 *
 * @param azkabanUri The URL of the Azkaban server
 * @param username   The username for the project
 * @param password   The password for the project
 */
public ProjectManager(URI azkabanUri, String username, String password) {
    this.azkabanUri = azkabanUri;
    try {
        this.managerUri = new URIBuilder(azkabanUri).setPath("/manager").build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    this.sessionId = new AuthenticationManager(azkabanUri, username, password).login().getSessionId();
}

From source file:org.eclipse.packagedrone.testing.server.channel.UploadApiV2Test.java

@Test
public void upload1() throws URISyntaxException, IOException {
    final ChannelTester tester = getTester();

    final File file = getAbsolutePath(CommonResources.BUNDLE_1_RESOURCE);

    final URIBuilder b = new URIBuilder(
            resolve("/api/v2/upload/channel/%s/%s", tester.getId(), file.getName()));
    b.setUserInfo("deploy", this.deployKey);
    b.addParameter("foo:bar", "baz");

    try (final CloseableHttpResponse response = upload(b, file)) {
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    }//from w w  w  .j a v  a2  s. co  m

    final Set<String> arts = tester.getAllArtifactIds();

    Assert.assertEquals(1, arts.size());
}

From source file:org.artifactory.webapp.wicket.util.validation.UriValidator.java

@Override
protected void onValidate(IValidatable validatable) {
    String uri = (String) validatable.getValue();

    if (!PathUtils.hasText(uri)) {
        addError(validatable, "The URL cannot be empty");
        return;/*from   w w w.j ava2  s  .  c o  m*/
    }

    try {
        URI parsedUri = new URIBuilder(uri).build();
        String scheme = parsedUri.getScheme();
        if (!anySchemaAllowed() && StringUtils.isBlank(scheme)) {
            addError(validatable,
                    String.format(
                            "Url scheme cannot be empty. The following schemes are allowed: %s. "
                                    + "For example: %s://host",
                            Arrays.asList(allowedSchemes), allowedSchemes[0]));

        } else if (!allowedSchema(scheme)) {
            addError(validatable,
                    String.format("Scheme '%s' is not allowed. The following schemes are allowed: %s", scheme,
                            Arrays.asList(allowedSchemes)));
        }

        HttpHost host = URIUtils.extractHost(parsedUri);
        if (host == null) {
            addError(validatable, "Cannot resolve host from url: " + uri);
        }
    } catch (URISyntaxException e) {
        addError(validatable, String.format("'%s' is not a valid url", uri));
    }
}

From source file:org.talend.dataprep.api.service.command.preparation.PreparationList.java

private HttpRequestBase onExecute(Sort sort, Order order, Format format) {
    try {/*from  w w w  .  jav a2 s .  c om*/
        URIBuilder uriBuilder;
        if (Format.SHORT.equals(format)) {
            uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations"); //$NON-NLS-1$
        } else if (Format.SUMMARY.equals(format)) {
            uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations/summaries"); //$NON-NLS-1$
        } else {
            uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations/details"); //$NON-NLS-1$
        }

        uriBuilder.addParameter("sort", sort.camelName());
        uriBuilder.addParameter("order", order.camelName());
        return new HttpGet(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}

From source file:com.kurtraschke.septa.gtfsrealtime.services.TrainViewService.java

public Collection<Train> getTrains() throws URISyntaxException, ClientProtocolException, IOException {
    URIBuilder b = new URIBuilder("http://www3.septa.org/hackathon/TrainView/");

    CloseableHttpClient client = HttpClients.custom().setConnectionManager(_connectionManager).build();

    HttpGet httpget = new HttpGet(b.build());
    try (CloseableHttpResponse response = client.execute(httpget);
            InputStream responseInputStream = response.getEntity().getContent();
            Reader responseEntityReader = new InputStreamReader(responseInputStream)) {
        JsonParser parser = new JsonParser();

        JsonArray trainObjects = (JsonArray) parser.parse(responseEntityReader);

        ArrayList<Train> allTrains = new ArrayList<>(trainObjects.size());

        for (JsonElement trainElement : trainObjects) {
            JsonObject trainObject = (JsonObject) trainElement;

            try {
                allTrains.add(new Train(trainObject.get("lat").getAsDouble(),
                        trainObject.get("lon").getAsDouble(), trainObject.get("trainno").getAsString(),
                        trainObject.get("service").getAsString(), trainObject.get("dest").getAsString(),
                        trainObject.get("nextstop").getAsString(), trainObject.get("late").getAsInt(),
                        trainObject.get("SOURCE").getAsString()));
            } catch (Exception e) {
                _log.warn("Exception processing train JSON", e);
                _log.warn(trainObject.toString());
            }//w ww .j a  va  2 s  . c o  m
        }
        return allTrains;
    }
}

From source file:de.dentrassi.pm.jenkins.UploaderV2.java

private URI makeUrl(final String file) throws URIException, IOException {
    final URI fullUri;
    try {//from  w w  w  .  j  av a2  s .c o  m

        final URIBuilder b = new URIBuilder(this.serverUrl);

        b.setUserInfo("deploy", this.deployKey);

        b.setPath(b.getPath() + String.format("/api/v2/upload/channel/%s/%s",
                URIUtil.encodeWithinPath(this.channelId), file));

        b.addParameter("jenkins:buildUrl", this.runData.getUrl());
        b.addParameter("jenkins:buildId", this.runData.getId());
        b.addParameter("jenkins:buildNumber", String.valueOf(this.runData.getNumber()));
        b.addParameter("jenkins:jobName", this.runData.getFullName());

        final Map<String, String> properties = new HashMap<String, String>();
        fillProperties(properties);

        for (final Map.Entry<String, String> entry : properties.entrySet()) {
            b.addParameter(entry.getKey(), entry.getValue());
        }

        fullUri = b.build();

    } catch (final URISyntaxException e) {
        throw new IOException(e);
    }
    return fullUri;
}

From source file:org.wso2.carbon.appmgt.mdm.restconnector.utils.RestUtils.java

/**
 * If not exists generate new access key or return existing one.
 *
 * @param remoteServer bean that holds information about remote server
 * @param generateNewKey whether generate new access key or not
 * @return generated access key/*from  w w w  . j a v a2 s .  c o  m*/
 */
public static String getAPIToken(RemoteServer remoteServer, boolean generateNewKey) {

    if (!generateNewKey) {
        if (!(AuthHandler.authKey == null || "null".equals(AuthHandler.authKey))) {
            return AuthHandler.authKey;
        }
    }

    HttpClient httpClient = AppManagerUtil.getHttpClient(remoteServer.getTokenApiURL());
    HttpPost postMethod = null;
    HttpResponse response = null;
    String responseString = "";
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(
                new BasicNameValuePair(Constants.RestConstants.GRANT_TYPE, Constants.RestConstants.PASSWORD));
        nameValuePairs
                .add(new BasicNameValuePair(Constants.RestConstants.USERNAME, remoteServer.getAuthUser()));
        nameValuePairs
                .add(new BasicNameValuePair(Constants.RestConstants.PASSWORD, remoteServer.getAuthPass()));
        URIBuilder uriBuilder = new URIBuilder(remoteServer.getTokenApiURL());
        uriBuilder.addParameters(nameValuePairs);
        postMethod = new HttpPost(uriBuilder.build());

        postMethod.setHeader(Constants.RestConstants.AUTHORIZATION,
                Constants.RestConstants.BASIC + new String(Base64.encodeBase64((remoteServer.getClientKey()
                        + Constants.RestConstants.COLON + remoteServer.getClientSecret()).getBytes())));
        postMethod.setHeader(Constants.RestConstants.CONTENT_TYPE,
                Constants.RestConstants.APPLICATION_FORM_URL_ENCODED);
    } catch (URISyntaxException e) {
        String errorMessage = "Cannot construct the Httppost. Url Encoded error.";
        log.error(errorMessage, e);
        return null;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Sending POST request to API Token endpoint. Request path:  "
                    + remoteServer.getTokenApiURL());
        }

        response = httpClient.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("Status code " + statusCode + " received while accessing the API Token endpoint.");
        }

    } catch (IOException e) {
        String errorMessage = "Cannot connect to Token API Endpoint.";
        log.error(errorMessage, e);
        return null;
    }

    try {
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            responseString = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        }

    } catch (IOException e) {
        String errorMessage = "Cannot get response body for auth.";
        log.error(errorMessage, e);
        return null;
    }
    JSONObject token = (JSONObject) new JSONValue().parse(responseString);

    AuthHandler.authKey = String.valueOf(token.get(Constants.RestConstants.ACCESS_TOKEN));
    return AuthHandler.authKey;
}

From source file:org.restcomm.connect.java.sdk.http.Request.java

public void addGetParameters(String a, String b) throws MalformedURLException, URISyntaxException {

    URIBuilder urib = new URIBuilder(Url);
    urib.addParameter(a, b);/*from   w  ww .ja v a 2 s . c o m*/
    urib.build();
    Url = new URL(urib.toString()).toString();
}

From source file:com.google.appengine.tck.blobstore.support.FileUploader.java

private String getUploadUrl(URL url, Method method, Map<String, String> params)
        throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(url.toURI());
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.addParameter(entry.getKey(), entry.getValue());
    }//www.  j a  v  a  2s .c  om
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpUriRequest request;
        switch (method) {
        case GET:
            request = new HttpGet(builder.build());
            break;
        case POST:
            request = new HttpPost(builder.build());
            break;
        default:
            throw new IllegalArgumentException(String.format("No such method: %s", method));
        }
        HttpResponse response = httpClient.execute(request);
        return EntityUtils.toString(response.getEntity()).trim();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.griddynamics.jagger.invoker.http.HttpInvoker.java

@Override
protected HttpRequestBase getHttpMethod(HttpQuery query, String endpoint) {

    try {//  w ww .j  a v a 2s .  c o m
        URIBuilder uriBuilder = new URIBuilder(endpoint);

        if (!HttpQuery.Method.POST.equals(query.getMethod())) {
            for (Map.Entry<String, String> methodParam : query.getMethodParams().entrySet()) {
                uriBuilder.setParameter(methodParam.getKey(), methodParam.getValue());
            }
        }

        return createMethod(query, uriBuilder.build());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}