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

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

Introduction

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

Prototype

public URIBuilder setScheme(final String scheme) 

Source Link

Document

Sets URI scheme.

Usage

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);//w w  w  .j a v a  2 s  .  c o 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.");
}

From source file:it.txt.ens.core.impl.test.BasicENSResourceTest.java

private void testURI(ENSResource resource) {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.addParameter(ENSResource.NAMESPACE_PARAMETER_NAME, resource.getNamespace());
    uriBuilder.addParameter(ENSResource.PATTERN_PARAMETER_NAME, resource.getPattern());
    uriBuilder.setHost(resource.getHost());
    uriBuilder.setPath(resource.getPath());
    uriBuilder.setScheme(ENSResource.URI_SCHEME);

    try {/*  w  w  w .  j  a v a  2  s. co m*/
        assertEquals("Unexpected resourceURI", uriBuilder.build(), resource.getURI());
    } catch (URISyntaxException e) {
        fail(e.getMessage());
        e.printStackTrace();
    }
}

From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java

public void execute() throws MojoExecutionException {
    this.getLog().info("Uploading project to BukkitDev");
    final String gameVersion = this.getGameVersion();
    final URIBuilder builder = new URIBuilder();
    final MultipartEntity entity = new MultipartEntity();
    HttpPost request;//from  w  w w  .  j av  a  2  s . c  o  m

    // create the request
    builder.setScheme("http");
    builder.setHost("dev.bukkit.org");
    builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json");
    try {
        entity.addPart("file_type", new StringBody(this.getFileType()));
        entity.addPart("name", new StringBody(this.project.getArtifact().getVersion()));
        entity.addPart("game_versions", new StringBody(gameVersion));
        entity.addPart("change_log", new StringBody(this.changeLog));
        entity.addPart("known_caveats", new StringBody(this.knownCaveats));
        entity.addPart("change_markup_type", new StringBody(this.markupType));
        entity.addPart("caveats_markup_type", new StringBody(this.markupType));
        entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact())));
    } catch (final UnsupportedEncodingException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    // create the actual request
    try {
        request = new HttpPost(builder.build());
        request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0");
        request.setHeader("X-API-Key", this.key);
        request.setEntity(entity);
    } catch (final URISyntaxException exception) {
        throw new MojoExecutionException(exception.getMessage());
    }

    this.getLog().debug(request.toString());

    // send the request and handle any replies
    try {
        final HttpClient client = new DefaultHttpClient();
        final HttpResponse response = client.execute(request);
        switch (response.getStatusLine().getStatusCode()) {
        case 201:
            this.getLog().info("File uploaded successfully.");
            break;
        case 403:
            this.getLog().error(
                    "You have not specifed your API key correctly or do not have permission to upload to that project.");
            break;
        case 404:
            this.getLog().error("Project was not found. Either it is specified wrong or been renamed.");
            break;
        case 422:
            this.getLog().error("There was an error in uploading the plugin");
            this.getLog().debug(request.toString());
            this.getLog().debug(EntityUtils.toString(response.getEntity()));
            break;
        default:
            this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode());
            break;
        }
    } catch (final ClientProtocolException exception) {
        throw new MojoExecutionException(exception.getMessage());
    } catch (final IOException exception) {
        throw new MojoExecutionException(exception.getMessage());
    }

}

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

/**
 * Fetch status update from the backend/*from   ww  w.  j av  a 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:fi.csc.shibboleth.mobileauth.impl.authn.AuthenticateMobile.java

/** {@inheritDoc} */
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
        @Nonnull final ProfileRequestContext profileRequestContext) {
    log.debug("{} Entering - doExecute", getLogPrefix());

    final MobileContext mobCtx = profileRequestContext.getSubcontext(AuthenticationContext.class)
            .getSubcontext(MobileContext.class);
    final String mobileNumber = StringSupport.trimOrNull(mobCtx.getMobileNumber());
    final String spamCode = StringSupport.trimOrNull(mobCtx.getSpamCode());

    final CloseableHttpClient httpClient;
    try {/*w  w w.jav  a  2 s .co  m*/
        log.debug("{} Trying to create httpClient", getLogPrefix());
        httpClient = createHttpClient();
    } catch (KeyStoreException | RuntimeException e) {
        log.error("{} Cannot create httpClient", getLogPrefix(), e);
        return Events.failure.event(this);
    }

    // TODO: entity initialization
    HttpEntity entity = null;
    try {
        final URIBuilder builder = new URIBuilder();
        // TODO: remove hard-codings
        builder.setScheme("https").setHost(authServer).setPort(authPort).setPath(authPath)
                .setParameter(REST_PARAM_MOBILENUMBER, mobileNumber);
        if (spamCode != null) {
            builder.setParameter(REST_PARAM_NO_SPAM_CODE, spamCode);
        }

        final URI url = builder.build();

        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);

        entity = response.getEntity();

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

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

        if (status.getErrorMessage() != null) {
            log.debug("{} Setting error message", getLogPrefix());
            mobCtx.setErrorMessage(status.getErrorMessage());
        }

        response.close();

        if (statusCode == HttpStatus.SC_OK) {

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

            mobCtx.setProcessState(ProcessState.IN_PROCESS);
            mobCtx.setConversationKey(status.getCommunicationDataKey());
            mobCtx.setEventId(status.getEventId());
            mobCtx.setErrorMessage(status.getErrorMessage());
        } else if (statusCode == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            mobCtx.setProcessState(ProcessState.ERROR);
            // TODO: multilingual error message
            log.warn("{} 405 - Status code {} from REST gateway", getLogPrefix(), statusCode);
            return Events.failure.event(this);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            mobCtx.setProcessState(ProcessState.ERROR);
            // TODO: multilingual error message
            log.error("{} 401 - Status code {} from REST gateway - Invalid client configuration?",
                    getLogPrefix(), statusCode);
            return Events.failure.event(this);
        } else {
            mobCtx.setProcessState(ProcessState.ERROR);
            // TODO: multilingual error message
            log.warn("{} Status code {} from REST gateway", getLogPrefix(), statusCode);
            return Events.gatewayError.event(this);
        }

    } catch (Exception e) {
        // TODO: better exception handling
        log.error("Exception: {}", e);
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.AUTHN_EXCEPTION);
        return Events.failure.event(this);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }

    return Events.success.event(this);
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private URI searchUri() throws URISyntaxException {
    URIBuilder builder = new URIBuilder();
    builder.setScheme(rootUrl.toURI().getScheme()).setHost(rootUrl.toURI().getHost())
            .setPort(rootUrl.toURI().getPort()).setPath(rootUrl.toURI().getPath() + "sharing/rest/search");
    return builder.build();
}

From source file:osh.busdriver.MieleGatewayBusDriver.java

public void onQueueEventReceived(EventExchange event) throws OSHException {
    if (event instanceof CommandExchange) {
        UUID devUUID = ((CommandExchange) event).getReceiver();
        Map<String, String> devProps = deviceProperties.get(devUUID);

        if (devProps != null) { // known device?
            if (devProps.containsKey("type") && devProps.containsKey("id")) {
                URIBuilder builder = new URIBuilder();
                if (event instanceof StartDeviceRequest) {
                    builder.setScheme("http").setHost(this.mieleGatewayHost).setPath("/homebus/device")
                            .setParameter("type", devProps.get("type")).setParameter("id", devProps.get("id"))
                            .setParameter("action", "start");
                    //                  .setParameter("actionId", "start")
                    //                  .setParameter("argumentCount", "0");
                } else {
                    if (event instanceof StopDeviceRequest) {
                        builder.setScheme("http").setHost(this.mieleGatewayHost).setPath("/homebus/device")
                                .setParameter("type", devProps.get("type"))
                                .setParameter("id", devProps.get("id")).setParameter("action", "stop");
                    } else {
                        if (event instanceof SwitchRequest) {
                            builder.setScheme("http").setHost(this.mieleGatewayHost).setPath("/homebus/device")
                                    .setParameter("type", devProps.get("type"))
                                    .setParameter("id", devProps.get("id")).setParameter("action",
                                            ((SwitchRequest) event).isTurnOn() ? "switchOn" : "switchOff");
                        } else {
                            return;
                        }//w w  w.j ava 2s. c  o m
                    }
                }

                try {
                    mieleGatewayDispatcher.sendCommand(builder.build().toString());
                } catch (URISyntaxException e) {
                    getGlobalLogger().logWarning("miele gateway disconnected?", e);
                }
            }
        }
    }
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private URI itemInfoUri(String itemId) throws URISyntaxException {
    URIBuilder builder = new URIBuilder();
    builder.setScheme(rootUrl.toURI().getScheme()).setHost(rootUrl.toURI().getHost())
            .setPort(rootUrl.toURI().getPort())
            .setPath(rootUrl.toURI().getPath() + "sharing/content/items/" + itemId);
    return builder.build();
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private URI userUri(String owner, String folderId) throws URISyntaxException {
    URIBuilder builder = new URIBuilder();
    builder.setScheme(rootUrl.toURI().getScheme()).setHost(rootUrl.toURI().getHost())
            .setPort(rootUrl.toURI().getPort()).setPath(rootUrl.toURI().getPath()
                    + "sharing/rest/content/users/" + owner + (folderId != null ? "/" + folderId : ""));
    return builder.build();
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private URI updateItemUri(String owner, String folderId, String itemId) throws URISyntaxException {
    URIBuilder builder = new URIBuilder();
    builder.setScheme(rootUrl.toURI().getScheme()).setHost(rootUrl.toURI().getHost())
            .setPort(rootUrl.toURI().getPort())
            .setPath(rootUrl.toURI().getPath() + "sharing/rest/content/users/" + owner
                    + (folderId != null ? "/" + folderId : "") + "/items/" + itemId + "/update");
    return builder.build();
}