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:org.pentaho.reporting.libraries.pensol.vfs.LocalFileModel.java

/**
 * @noinspection ThrowCaughtLocally/*from   w ww.  jav a 2  s .c o  m*/
 */
protected byte[] getDataInternally(final FileInfo fileInfo) throws FileSystemException {
    URI uri;
    String baseUrl = fileInfo.getUrl();
    try {
        URIBuilder builder = new URIBuilder(baseUrl);
        logger.debug("Connecting to '" + baseUrl + '\'');
        if (username != null) {
            builder.setParameter("userid", username);
        }
        if (password != null) {
            builder.setParameter("password", password);
        }
        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new FileSystemException("Provided URL is invalid: " + baseUrl);
    }
    final HttpPost filePost = new HttpPost(uri);
    filePost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

    try {
        HttpResponse httpResponse = client.execute(filePost, context);
        final int lastStatus = httpResponse.getStatusLine().getStatusCode();
        if (lastStatus == HttpStatus.SC_UNAUTHORIZED) {
            throw new FileSystemException("401: User authentication failed.");
        } else if (lastStatus == HttpStatus.SC_NOT_FOUND) {
            throw new FileSystemException("404: Repository service not found on server.");
        } else if (lastStatus != HttpStatus.SC_OK) {
            throw new FileSystemException("Server error: HTTP lastStatus code " + lastStatus);
        }

        final InputStream postResult = httpResponse.getEntity().getContent();
        try {
            final MemoryByteArrayOutputStream bout = new MemoryByteArrayOutputStream();
            IOUtils.getInstance().copyStreams(postResult, bout);
            return bout.toByteArray();
        } finally {
            postResult.close();
        }
    } catch (FileSystemException ioe) {
        throw ioe;
    } catch (IOException ioe) {
        throw new FileSystemException("Failed", ioe);
    }
}

From source file:com.collective.celos.CelosClient.java

public List<RegisterKey> getRegisterKeys(BucketID bucket, String prefix) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + LIST_REGISTER_KEYS_PATH);
    uriBuilder.addParameter(BUCKET_PARAM, bucket.toString());
    if (!StringUtils.isEmpty(prefix)) {
        uriBuilder.addParameter(PREFIX_PARAM, prefix);
    }//from   ww w  .  ja  va2 s . c o  m
    InputStream contentStream = execute(new HttpGet(uriBuilder.build())).getEntity().getContent();
    return parseKeyList(contentStream);
}

From source file:com.ginger.Ginger4J.java

/**
 * Parse the given text and return the JSON object that contains the
 * result & the suggested corrections.
 *
 * @param text/*from www.  ja v  a 2  s  .co  m*/
 *            The text that should be corrected.
 *
 * @return JSONObject
 */
public JSONObject parse(String text) {
    String json = "";
    URIBuilder builder = null;

    try {
        // Build the Web Service URL
        builder = new URIBuilder(this.getBaseURL());
        builder.addParameters(parameters);
        builder.addParameter("text", text);

        // Create the HTTP client
        HttpClient client = HttpClientBuilder.create().build();
        // Create GET request
        HttpGet request = new HttpGet(builder.build());

        // Add request header
        request.addHeader("User-Agent", USER_AGENT);

        // Send request
        HttpResponse response = client.execute(request);

        // Get json response
        json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

        // Process the suggested corrections
        this.correction = this.processSuggestions(text, new JSONObject(json));
    } catch (URISyntaxException | IOException e) {
        System.out.println("Error: " + e.getMessage());
    } catch (JSONException e) {
        System.out.println("Error while parsing the json response: " + e.getMessage());
    }

    return this.correction;
}

From source file:fi.csc.shibboleth.mobileauth.impl.authn.ResolveAuthenticationStatus.java

/**
 * Fetch status update from the backend/* w  w  w  .  ja va  2  s. c o  m*/
 * 
 * @param conversationKey
 * @param profileCtx
 * @param mobCtx
 */
private void getStatusUpdate(String conversationKey, ProfileRequestContext profileCtx, MobileContext mobCtx) {
    log.debug("{} Getting statusUpdate for convKey {}", getLogPrefix(), conversationKey);

    final CloseableHttpClient httpClient;
    try {
        log.debug("{} Trying to create httpClient", getLogPrefix());
        httpClient = createHttpClient();
    } catch (KeyStoreException | RuntimeException e) {
        log.error("{} Cannot create httpClient", getLogPrefix(), e);
        ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
        return;
    }

    HttpEntity entity = null;

    try {
        final URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(authServer).setPort(authPort).setPath(statusPath)
                .setParameter("communicationDataKey", conversationKey);

        final URI url = builder.build();
        log.debug("{} getStatus URL: {}", getLogPrefix(), url.toURL());

        final HttpGet httpGet = new HttpGet(url);
        final Gson gson = new GsonBuilder().create();

        final CloseableHttpResponse response = httpClient.execute(httpGet);
        log.debug("{} Response: {}", getLogPrefix(), response);

        int statusCode = response.getStatusLine().getStatusCode();
        log.debug("{}HTTPStatusCode {}", getLogPrefix(), statusCode);

        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            log.error("{} Authentication failed for {} with error [{}]", getLogPrefix(),
                    mobCtx.getMobileNumber(), statusCode);
            mobCtx.setProcessState(ProcessState.ERROR);
            ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
            return;
        }

        if (statusCode == HttpStatus.SC_OK) {

            entity = response.getEntity();
            final String json = EntityUtils.toString(entity, "UTF-8");

            final StatusResponse status = gson.fromJson(json, StatusResponse.class);

            log.debug("{} Gson commKey: {}", getLogPrefix(), status.getCommunicationDataKey());
            log.debug("{} Gson EventID: {}", getLogPrefix(), status.getEventId());
            log.debug("{} Gson ErrorMessage: {}", getLogPrefix(), status.getErrorMessage());

            response.close();

            final Map<String, String> attributes = status.getAttributes();

            if (status.getErrorMessage() == null && !MapUtils.isEmpty(attributes)) {

                log.info("{} Authentication completed for {}", getLogPrefix(), mobCtx.getMobileNumber());
                mobCtx.setProcessState(ProcessState.COMPLETE);
                mobCtx.setAttributes(status.getAttributes());

                if (log.isDebugEnabled()) {
                    for (Map.Entry<String, String> attr : status.getAttributes().entrySet()) {
                        log.debug("Attr: {} - Value: {}", attr.getKey(), attr.getValue());
                    }
                }

            } else if (status.getErrorMessage() != null) {
                log.info("{} Authentication failed for {} with error [{}]", getLogPrefix(),
                        mobCtx.getMobileNumber(), status.getErrorMessage());
                mobCtx.setProcessState(ProcessState.ERROR);
                mobCtx.setErrorMessage(status.getErrorMessage());
            } else {
                log.info("{} Authentication in process for {}", getLogPrefix(), mobCtx.getMobileNumber());
                mobCtx.setProcessState(ProcessState.IN_PROCESS);
            }

        } else {
            mobCtx.setProcessState(ProcessState.ERROR);
            log.error("{} Unexpected status code {} from REST gateway", getLogPrefix(), statusCode);
            ActionSupport.buildEvent(profileCtx, EVENTID_GATEWAY_ERROR);
            return;
        }

    } catch (Exception e) {
        log.error("Exception: {}", e);
        ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
        return;
    } finally {
        EntityUtils.consumeQuietly(entity);
    }

}

From source file:com.github.tmyroadctfig.icloud4j.DriveNode.java

/**
 * Downloads the file data for the item into the given output stream.
 *
 * @param outputStream the output stream to write to.
 *//*from   ww  w. j  ava  2  s .  c  o  m*/
public void downloadFileData(OutputStream outputStream) {
    try {
        URIBuilder uriBuilder = new URIBuilder(
                String.format("%s/ws/%s/download/by_id", driveService.getDocsServiceUrl(), nodeDetails.zone));
        iCloudService.populateUriParameters(uriBuilder);
        uriBuilder.addParameter("clientMasteringNumber", iCloudService.getClientBuildNumber());
        uriBuilder.addParameter("document_id", Iterables.getLast(Splitter.on(":").splitToList(id)));
        uriBuilder.addParameter("token", downloadUrlToken);
        URI contentUrlLookupUrl = uriBuilder.build();

        // Get the download URL for the item
        HttpGet contentUrlGetRequest = new HttpGet(contentUrlLookupUrl);
        iCloudService.populateRequestHeadersParameters(contentUrlGetRequest);

        Map<String, Object> result = iCloudService.getHttpClient().execute(contentUrlGetRequest,
                new JsonToMapResponseHandler());
        @SuppressWarnings("unchecked")
        Map<String, Object> dataTokenMap = (Map<String, Object>) result.get("data_token");

        String contentUrl = (String) dataTokenMap.get("url");
        HttpGet contentRequest = new HttpGet(contentUrl);

        try (InputStream inputStream = iCloudService.getHttpClient().execute(contentRequest).getEntity()
                .getContent()) {
            IOUtils.copyLarge(inputStream, outputStream, new byte[0x10000]);
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.metaservice.manager.blazegraph.FastRangeCountRequestBuilder.java

public MutationResult execute() throws ManagerException {
    try {// w ww. j a v  a2s.co  m
        JAXBContext jaxbContext = JAXBContext.newInstance(MutationResult.class);

        URIBuilder uriBuilder = new URIBuilder(path);
        if (subject != null) {
            uriBuilder.setParameter("s", format(subject));
        }
        if (object != null) {
            uriBuilder.setParameter("o", format(object));
        }
        if (predicate != null) {
            uriBuilder.setParameter("p", format(predicate));
        }
        if (context != null) {
            uriBuilder.setParameter("c", format(context));
        }
        uriBuilder.addParameter("ESTCARD", null);
        URI uri = uriBuilder.build();
        LOGGER.debug("QUERY = " + uri.toString());
        String s = Request.Get(uri).connectTimeout(1000).socketTimeout(10000)
                .setHeader("Accept", "application/xml").execute().returnContent().asString();
        LOGGER.debug("RESULT = " + s);
        return (MutationResult) jaxbContext.createUnmarshaller().unmarshal(new StringReader(s));
    } catch (JAXBException | URISyntaxException | IOException e) {
        throw new ManagerException(e);
    }

}

From source file:org.jasig.portlet.proxy.service.web.HttpContentServiceImpl.java

protected HttpUriRequest getHttpRequest(HttpContentRequestImpl proxyRequest, PortletRequest request) {
    final HttpUriRequest httpRequest;

    // if this is a form request, we may need to use a POST or add form parameters
    if (proxyRequest.isForm()) {

        // handle POST form request
        final Map<String, IFormField> params = proxyRequest.getParameters();
        if ("POST".equalsIgnoreCase(proxyRequest.getMethod())) {

            final List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, IFormField> param : params.entrySet()) {
                for (String value : param.getValue().getValues()) {
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(param.getKey(), value));
                    }/*from   ww  w. j  a  va  2s . c  om*/
                }
            }

            // construct a new POST request and set the form data
            try {
                httpRequest = new HttpPost(proxyRequest.getProxiedLocation());
                if (pairs.size() > 0) {
                    ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                log.error("Failed to encode form parameters", e);
                throw new RuntimeException(e);
            }

        }

        // handle GET form requests
        else {

            try {

                // build a URL including any passed form parameters
                final URIBuilder builder = new URIBuilder(proxyRequest.getProxiedLocation());
                for (Map.Entry<String, IFormField> param : params.entrySet()) {
                    for (String value : param.getValue().getValues()) {
                        builder.addParameter(param.getKey(), value);
                    }
                }
                final URI uri = builder.build();
                httpRequest = new HttpGet(uri);

            } catch (URISyntaxException e) {
                log.error("Failed to build URI for proxying", e);
                throw new RuntimeException(e);
            }

        }

    }

    // not a form, simply a normal get request
    else {
        log.debug("Submitting a GET request to proxied location [{}]", proxyRequest.getProxiedLocation());
        httpRequest = new HttpGet(proxyRequest.getProxiedLocation());
    }

    // set any configured request headers
    for (Map.Entry<String, String> header : proxyRequest.getHeaders().entrySet()) {
        httpRequest.setHeader(header.getKey(), header.getValue());
    }

    return httpRequest;
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/*  ww  w.j ava2  s .  co  m*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}