List of usage examples for org.apache.http.client.fluent Request Get
public static Request Get(final String uri)
From source file:org.n52.youngs.test.ElasticsearchSinkTestmappingIT.java
@Test public void insertSchema() throws Exception { sink.prepare(mapping);//ww w . ja v a 2 s . c om IndicesAdminClient indicesClient = sink.getClient().admin().indices(); GetMappingsRequestBuilder builder = new GetMappingsRequestBuilder(indicesClient, GetMappingsAction.INSTANCE, mapping.getIndex()).addTypes(mapping.getType()); GetMappingsResponse response = indicesClient.getMappings(builder.request()).actionGet(); ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings = response.getMappings(); Map<String, Object> recordTypeMap = mappings.get(mapping.getIndex()).get(mapping.getType()) .getSourceAsMap(); assertThat("dynamic value is correct", Boolean.valueOf(recordTypeMap.get("dynamic").toString()), is(mapping.isDynamicMappingEnabled())); Thread.sleep(1000); // https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html String allMappingsResponse = Request.Get("http://localhost:9200/_mapping/_all?pretty").execute() .returnContent().asString(); assertThat("record type is provided (checking id property type", allMappingsResponse, hasJsonPath( mapping.getIndex() + ".mappings." + mapping.getType() + ".properties.id.type", is("string"))); assertThat("metadata type is provided (checking mt_update-time property type)", allMappingsResponse, hasJsonPath(mapping.getIndex() + ".mappings.mt.properties.mt-update-time.type", is("date"))); // https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-types-exists.html StatusLine recordsStatus = Request .Head("http://localhost:9200/" + mapping.getIndex() + "/" + mapping.getType()).execute() .returnResponse().getStatusLine(); assertThat("records type is available", recordsStatus.getStatusCode(), is(200)); StatusLine mtStatus = Request.Head("http://localhost:9200/" + mapping.getIndex() + "/mt").execute() .returnResponse().getStatusLine(); assertThat("metadata type is available", mtStatus.getStatusCode(), is(200)); }
From source file:io.coala.capability.online.FluentHCOnlineCapability.java
/** * @param method/* w w w . j a va 2s .c om*/ * @param uri * @return */ @SuppressWarnings("rawtypes") public static Request getFluentRequest(final HttpMethod method, final URI uri, final Map.Entry... formData) { final Request request; switch (method) { case GET: request = Request.Get(toFormDataURI(uri, formData)); break; case HEAD: request = Request.Head(toFormDataURI(uri, formData)); break; case POST: request = Request.Post(uri); break; case PUT: request = Request.Put(uri); break; case DELETE: request = Request.Delete(toFormDataURI(uri, formData)); break; case OPTIONS: request = Request.Options(toFormDataURI(uri, formData)); break; case TRACE: request = Request.Trace(toFormDataURI(uri, formData)); break; default: throw new IllegalStateException("UNSUPPORTED: " + method); } return request.useExpectContinue().version(HttpVersion.HTTP_1_1); }
From source file:org.mule.module.http.functional.proxy.HttpProxyTemplateErrorHandlingTestCase.java
@Test public void rollbackExceptionStrategy() throws Exception { HttpResponse response = Request.Get(getProxyUrl("rollbackExceptionStrategy")) .connectTimeout(RECEIVE_TIMEOUT).execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(500)); assertThat(IOUtils.toString(response.getEntity().getContent()), not(equalTo(SERVICE_DOWN_MESSAGE))); SensingNullMessageProcessor processor = muleContext.getRegistry() .lookupObject(ROLLBACK_SENSING_PROCESSOR_NAME); assertThat(processor.event, is(notNullValue())); }
From source file:com.qwazr.database.TableSingleClient.java
@Override public Map<String, ColumnDefinition> getColumns(String table_name) { UBuilder uriBuilder = new UBuilder("/table/", table_name, "/column"); Request request = Request.Get(uriBuilder.build()); return commonServiceRequest(request, null, null, ColumnDefinition.MapStringColumnTypeRef, 200); }
From source file:com.oneops.search.msg.processor.ReleaseMessageProcessor.java
private void indexSnapshot(CmsRelease release) { try {/* ww w . ja v a2 s .c om*/ if (!"closed".equalsIgnoreCase(release.getReleaseState())) { logger.info("Release is not closed. Won't do snapshot"); return; } if (release.getNsPath().endsWith("bom")) return; // ignore bom release Calendar cal = new GregorianCalendar(); cal.add(Calendar.WEEK_OF_YEAR, -2); long snapshotTimestamp = cal.getTime().getTime(); long hits = client.prepareSearch("cms-201*").setSearchType(SearchType.COUNT).setTypes(SNAPSHOT) .setQuery(boolQuery().must(QueryBuilders.rangeQuery("timestamp").from(snapshotTimestamp)) .must(QueryBuilders.termQuery("namespace.keyword", release.getNsPath()))) .execute().actionGet().getHits().getTotalHits(); logger.info("hits:" + hits); if (hits > 0) { logger.info("there was a snapshot done recently, so won'd do another one. "); return; } String url = (release.getNsPath().endsWith("manifest") ? manifestSnapshotURL : designSnapshotURL) + release.getNsPath(); // set snapshot URL based on release type logger.info("Retrieving snapshot for:" + url + " expected release:" + release.getReleaseId()); String message = Request.Get(url).addHeader("Content-Type", "application/json").execute() .returnContent().asString(); long releaseId = new JsonParser().parse(message).getAsJsonObject().get("release").getAsLong(); if (releaseId > release.getReleaseId()) { logger.warn("Snapshot is dirty, so discarding. Was expecting release:" + release.getReleaseId() + " snapshot has rfcs from release:" + releaseId); } else { indexer.index(String.valueOf(release.getReleaseId()), SNAPSHOT, message); logger.info("Snapshot indexed for release ID: " + release.getReleaseId()); } } catch (Exception e) { logger.error("Error while retrieving snapshot" + e.getMessage(), e); } }
From source file:org.obm.locator.LocatorClientImpl.java
@Override public String getServiceLocation(String serviceSlashProperty, String loginAtDomain) throws LocatorClientException { try {/* w w w . jav a 2 s . c o m*/ String responseBody = Request.Get(buildFullServiceUrl(serviceSlashProperty, loginAtDomain)) .connectTimeout(timeoutInMS).socketTimeout(timeoutInMS).execute().returnContent().asString(); return Iterables.get(Splitter.on(RESPONSE_SEPARATOR).split(responseBody), 0); } catch (HttpResponseException e) { if (e.getStatusCode() == HTTP_CODE_NOT_FOUND) { throw new ServiceNotFoundException( String.format("Service %s for %s not found", serviceSlashProperty, loginAtDomain)); } else { throw new LocatorClientException( String.format("HTTP error %d: %s", e.getStatusCode(), e.getMessage()), e); } } catch (MalformedURLException e) { throw new LocatorClientException(e.getMessage(), e); } catch (SocketTimeoutException e) { throw new LocatorClientException(e.getMessage(), e); } catch (IOException e) { throw new LocatorClientException(e.getMessage(), e); } }
From source file:aiai.ai.station.actors.DownloadSnippetActor.java
public void fixedDelay() { if (globals.isUnitTesting) { return;//www . java 2 s. co m } if (!globals.isStationEnabled) { return; } DownloadSnippetTask task; while ((task = poll()) != null) { if (Boolean.TRUE.equals(preparedMap.get(task.getSnippetCode()))) { continue; } final String snippetCode = task.snippetCode; AssetFile assetFile = StationResourceUtils.prepareResourceFile(globals.stationResourcesDir, Enums.BinaryDataType.SNIPPET, task.snippetCode, task.filename); if (assetFile.isError) { log.warn("Resource can't be downloaded. Asset file initialization was failed, {}", assetFile); continue; } if (assetFile.isContent) { log.info("Snippet was already downloaded. Snippet file: {}", assetFile.file.getPath()); preparedMap.put(snippetCode, true); continue; } Checksum checksum = null; if (globals.isAcceptOnlySignedSnippets) { try { Request request = Request.Get(snippetChecksumUrl + '/' + snippetCode).connectTimeout(5000) .socketTimeout(5000); Response response; if (globals.isSecureRestUrl) { response = executor.executor.execute(request); } else { response = request.execute(); } String checksumStr = response.returnContent().asString(StandardCharsets.UTF_8); checksum = Checksum.fromJson(checksumStr); } catch (HttpResponseException e) { logError(snippetCode, e); break; } catch (SocketTimeoutException e) { log.error("SocketTimeoutException", e); break; } catch (IOException e) { log.error("IOException", e); break; } catch (Throwable th) { log.error("Throwable", th); return; } } try { File snippetTempFile = new File(assetFile.file.getAbsolutePath() + ".tmp"); // @GetMapping("/rest-anon/payload/resource/{type}/{code}") Request request = Request.Get(targetUrl + '/' + snippetCode).connectTimeout(5000) .socketTimeout(5000); Response response; if (globals.isSecureRestUrl) { response = executor.executor.execute(request); } else { response = request.execute(); } response.saveContent(snippetTempFile); boolean isOk = true; if (globals.isAcceptOnlySignedSnippets) { CheckSumAndSignatureStatus status; try (FileInputStream fis = new FileInputStream(snippetTempFile)) { status = checksumWithSignatureService.verifyChecksumAndSignature(checksum, snippetCode, fis, true); } if (status.isSignatureOk == null) { log.warn( "globals.isAcceptOnlySignedSnippets is {} but snippet with code {} doesn't have signature", globals.isAcceptOnlySignedSnippets, snippetCode); continue; } if (Boolean.FALSE.equals(status.isSignatureOk)) { log.warn( "globals.isAcceptOnlySignedSnippets is {} but snippet with code {} has the broken signature", globals.isAcceptOnlySignedSnippets, snippetCode); continue; } isOk = (status.isOk && !Boolean.FALSE.equals(status.isSignatureOk)); } if (isOk) { //noinspection ResultOfMethodCallIgnored snippetTempFile.renameTo(assetFile.file); preparedMap.put(snippetCode, true); } else { //noinspection ResultOfMethodCallIgnored snippetTempFile.delete(); } } catch (HttpResponseException e) { logError(snippetCode, e); } catch (SocketTimeoutException e) { log.error("SocketTimeoutException", e.toString()); } catch (IOException e) { log.error("IOException", e); } } }
From source file:photosharing.api.conx.RecommendationDefinition.java
/** * get nonce as described with nonce <a href="http://ibm.co/1fG83gY">Get a * Cryptographic Key</a>/* ww w . j av a 2 s .c om*/ * * @param bearer */ private String getNonce(String bearer, HttpServletResponse response) { String nonce = ""; // Build the Request Request get = Request.Get(getNonceUrl()); get.addHeader("Authorization", "Bearer " + bearer); try { Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes and if SC_OK (200), convert to String */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); nonce = IOUtils.toString(in); } else { //Given a bad proxied request response.setStatus(HttpStatus.SC_BAD_GATEWAY); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); } return nonce; }
From source file:com.amazonaws.sample.entitlement.authorization.LoginWithAmazonOAuth2AuthorizationHandler.java
/** * Exchange an access token for a map of user profile information. * @param accessToken//ww w.j a v a 2 s. c o m * @return an Identity object containing the user's email * @throws AuthorizationException */ @Override Identity getIdentity(String accessToken) throws AuthorizationException { try { // exchange the access token for user profile ResponseContent r = Request.Get("https://api.amazon.com/user/profile") .addHeader("Authorization", "bearer " + accessToken).execute() .handleResponse(new AllStatusesContentResponseHandler()); int statusCode = r.getStatusCode(); Map<String, String> m = new ObjectMapper().readValue(r.getContent("{}"), new TypeReference<Object>() { }); if (statusCode == HttpStatus.SC_OK) { if (!m.containsKey("email")) { throw new RuntimeException("Expected response to include email but it does not."); } return new Identity(m.get("user_id"), m.get("email")); } if (statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new OAuthBadRequestException(buildErrorMessageFromResponse(m, statusCode), AUTHORIZATION_TYPE); } if (statusCode >= 500) { throw new RuntimeException(PROVIDER_NAME + " encountered an error. Status code: " + statusCode); } throw new RuntimeException( "Unanticipated response from " + PROVIDER_NAME + ". Status code: " + statusCode); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.yfiton.notifiers.slack.SlackNotifier.java
@Override protected AccessTokenData requestAccessTokenData(AuthorizationData authorizationData) throws NotificationException { try {// w ww. j ava 2s . c om String response = Request.Get(getAccessTokenUrl(authorizationData.getAuthorizationCode()).get()) .execute().returnContent().asString(); JsonParser jsonParser = new JsonParser(); JsonObject json = jsonParser.parse(response).getAsJsonObject(); ImmutableMap.Builder<String, String> result = ImmutableMap.builder(); if (!json.get("ok").getAsBoolean()) { throw new NotificationException(json.get("error").getAsString()); } result.put("teamId", json.get("team_id").getAsString()); result.put("teamName", json.get("team_name").getAsString()); return new AccessTokenData(json.get("access_token").getAsString(), result.build()); } catch (IOException e) { throw new NotificationException(e.getMessage(), e); } }