/** * Gets a client web resource builder. * * @param localUrl the URL to access remote resource * @return web resource builder */ public Invocation.Builder getClientBuilder(String localUrl) { log.info("URL: {}", localUrl); Client client = ClientBuilder.newClient(); WebTarget wt = client.target(localUrl); return wt.request(UTF_8); }
@Test @RunAsClient public void testAbort() throws Exception { logger.info("Registering Client Abort Filters"); Client client = newClient(); client.register(new MyClientResponseFilter()); client.register(new MyClientRequestFilter()); client.register(new BlockChainFilter()); WebTarget target = client.target(url + "myjaxrs/simple/"); WebTarget resourceTarget = target.path("/valuesget"); resourceTarget = resourceTarget.queryParam("OrderID", "111").queryParam("UserName", "Luke"); logger.info("Invoking REST Service: " + resourceTarget.getUri().toString()); Invocation invocation = resourceTarget.request().buildGet(); Response response = invocation.invoke(); assertEquals( "MyClientRequestFilter is not executed because BlockChainFilter blocks it. So no header is saved: ", "", response.getHeaderString(CONTENT_TYPE_STRING)); }
/** * Returns port information stored in Neutron. * * @return List of OpenstackPort */ public Collection<OpenstackPort> getPorts() { Invocation.Builder builder = getClientBuilder(neutronUrl + URI_PORTS); String response = builder.accept(MediaType.APPLICATION_JSON_TYPE). header(HEADER_AUTH_TOKEN, getToken()).get(String.class); ObjectMapper mapper = new ObjectMapper(); List<OpenstackPort> openstackPorts = Lists.newArrayList(); try { ObjectNode node = (ObjectNode) mapper.readTree(response); ArrayNode portList = (ArrayNode) node.path(PATH_PORTS); OpenstackPortCodec portCodec = new OpenstackPortCodec(); portList.forEach(p -> openstackPorts.add(portCodec.decode((ObjectNode) p, null))); } catch (IOException e) { log.warn("getPorts()", e); } log.debug("port response:" + response); openstackPorts.forEach(n -> log.debug("port ID: {}", n.id())); return openstackPorts; }
public Collection<OpenstackRouter> getRouters() { Invocation.Builder builder = getClientBuilder(neutronUrl + PATH_ROUTERS); String response = builder.accept(MediaType.APPLICATION_JSON_TYPE). header(HEADER_AUTH_TOKEN, getToken()).get(String.class); ObjectMapper mapper = new ObjectMapper(); List<OpenstackRouter> openstackRouters = Lists.newArrayList(); try { ObjectNode node = (ObjectNode) mapper.readTree(response); ArrayNode routerList = (ArrayNode) node.path(PATH_ROUTERS); OpenstackRouterCodec openstackRouterCodec = new OpenstackRouterCodec(); routerList.forEach(r -> openstackRouters .add(openstackRouterCodec.decode((ObjectNode) r, null))); } catch (IOException e) { log.warn("getRouters()", e); } log.debug("router response:" + response); openstackRouters.forEach(r -> log.debug("router ID: {}", r.id())); return openstackRouters; }
/** * Returns network information stored in Neutron. * * @return List of OpenstackNetwork */ public Collection<OpenstackNetwork> getNetworks() { Invocation.Builder builder = getClientBuilder(neutronUrl + URI_NETWORKS); String response = builder.accept(MediaType.APPLICATION_JSON_TYPE). header(HEADER_AUTH_TOKEN, getToken()).get(String.class); log.debug("networks response:" + response); ObjectMapper mapper = new ObjectMapper(); List<OpenstackNetwork> openstackNetworks = Lists.newArrayList(); try { ObjectNode node = (ObjectNode) mapper.readTree(response); ArrayNode networkList = (ArrayNode) node.path(PATH_NETWORKS); OpenstackNetworkCodec networkCodec = new OpenstackNetworkCodec(); networkList.forEach(n -> openstackNetworks.add(networkCodec.decode((ObjectNode) n, null))); } catch (IOException e) { log.warn("getNetworks()", e); } openstackNetworks.removeAll(Collections.singleton(null)); openstackNetworks.forEach(n -> log.debug("network ID: {}", n.id())); return openstackNetworks; }
/** * Return the concept with the supplied URI with pref label, uri and type fields populated * @param conceptUri - the concept to be returned * @return - the requested concept * @throws OEClientException - an error has occurred contacting the server */ public Concept getConcept(String conceptUri) throws OEClientException { logger.info("getConcept entry: {}", conceptUri); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("properties", basicProperties); queryParameters.put("path", getPathParameter(conceptUri)); Invocation.Builder invocationBuilder = getInvocationBuilder(getApiURL(), queryParameters); Date startDate = new Date(); logger.info("getConcept making call : {}", startDate.getTime()); Response response = invocationBuilder.get(); logger.info("getConcept call complete: {}", startDate.getTime()); logger.info("getConceptDetails - status: {}", response.getStatus()); if (response.getStatus() == 200) { String stringResponse = response.readEntity(String.class); if (logger.isDebugEnabled()) logger.debug("getConceptDetails: jsonResponse {}", stringResponse); JsonObject jsonResponse = JSON.parse(stringResponse); return new Concept(this, jsonResponse.get("@graph").getAsArray().get(0).getAsObject()); } else { throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString())); } }
/** * Return the concept with the supplied identifier * @param identifier - the unique identifier for the concept (not the URI) * @return - the requested concept * @throws OEClientException - an error has occurred contacting the server */ public Concept getConceptByIdentifier(Identifier identifier) throws OEClientException { logger.info("getConceptByIdentifier entry: {}", identifier); String url = getModelURL() + "/skos:Concept/meta:transitiveInstance"; Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("properties", basicProperties); queryParameters.put("filters", String.format("subject(exists %s \"%s\")", getWrappedUri(identifier.getUri()), identifier.getValue())); Invocation.Builder invocationBuilder = getInvocationBuilder(url, queryParameters); Date startDate = new Date(); logger.info("getConceptByIdentifier making call : {}", startDate.getTime()); Response response = invocationBuilder.get(); logger.info("getConceptByIdentifier call complete: {}", startDate.getTime()); logger.info("getConceptByIdentifier - status: {}", response.getStatus()); if (response.getStatus() == 200) { String stringResponse = response.readEntity(String.class); if (logger.isDebugEnabled()) logger.debug("getConceptByIdentifier: jsonResponse {}", stringResponse); JsonObject jsonResponse = JSON.parse(stringResponse); return new Concept(this, jsonResponse.get("@graph").getAsArray().get(0).getAsObject()); } else { throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString())); } }
public void populateMetadata(String metadataUri, Concept concept) throws OEClientException { logger.info("populateMetadata entry: {}", concept.getUri()); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("properties", getWrappedUri(metadataUri)); Invocation.Builder invocationBuilder = getInvocationBuilder(getResourceURL(concept.getUri()), queryParameters); Date startDate = new Date(); logger.info("populateMetadata making call : {}", startDate.getTime()); Response response = invocationBuilder.get(); logger.info("populateMetadata call complete: {}", startDate.getTime()); logger.info("populateMetadata - status: {}", response.getStatus()); if (response.getStatus() == 200) { String stringResponse = response.readEntity(String.class); if (logger.isDebugEnabled()) logger.debug("populateNarrowerConceptURIs: jsonResponse {}", stringResponse); JsonObject jsonResponse = JSON.parse(stringResponse); concept.populateMetadata(metadataUri, jsonResponse.get("@graph").getAsArray().get(0).getAsObject()); } else { throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString())); } }
/** * Delete model * @param model - the model to be deleted * @throws OEClientException - an error has occurred contacting the server */ public void deleteModel(Model model) throws OEClientException { logger.info("deleteModel entry: {}", model.getLabel()); String url = getApiURL() + "/sys/" + model.getUri(); logger.info("deleteModel URL: {}", url); Invocation.Builder invocationBuilder = getInvocationBuilder(url); logger.info("deleteModel - about to call"); Response response = invocationBuilder.delete(); logger.info("deleteModel - call returned"); int status = response.getStatus(); logger.info("deleteModel response status: {}", status); if (status != 200) { throw new OEClientException("Status: %d return deleting model at URL: %s. \n%s", status, url, response.readEntity(String.class)); } }
public void commitTask(Task task) { logger.info("commitTask entry: {}", task); String url = getTaskSysURL(task) + "/teamwork:Change/rdf:instance"; Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("action", "commit"); queryParameters.put("filter", "subject(teamwork:status = teamwork:Uncommitted)"); Invocation.Builder invocationBuilder = getInvocationBuilder(url, queryParameters); Date startDate = new Date(); logger.info("commitTask making call : {}", startDate.getTime()); Response response = invocationBuilder.post(null); logger.info("commitTask call complete: {}", startDate.getTime()); /* * Possible response codes are: - 204 in case of success - 409 in case * of constraint violation (if e. g. concept scheme already exists) */ logger.info("commitTask status: {}", response.getStatus()); if (logger.isDebugEnabled()) { logger.debug("commitTask response: {}", response.readEntity(String.class)); } }
/** * Extracts OpenstackSecurityGroup information for the ID. * * @param id Security Group ID * @return OpenstackSecurityGroup object or null if fails */ public OpenstackSecurityGroup getSecurityGroup(String id) { Invocation.Builder builder = getClientBuilder(neutronUrl + URI_SECURITY_GROUPS + "/" + id); String response = builder.accept(MediaType.APPLICATION_JSON_TYPE). header(HEADER_AUTH_TOKEN, getToken()).get(String.class); ObjectMapper mapper = new ObjectMapper(); OpenstackSecurityGroup securityGroup = null; try { ObjectNode node = (ObjectNode) mapper.readTree(response); OpenstackSecurityGroupCodec sgCodec = new OpenstackSecurityGroupCodec(); securityGroup = sgCodec.decode(node, null); } catch (IOException e) { log.warn("getSecurityGroup()", e); } return securityGroup; }
public void deleteConcept(Concept concept) throws OEClientException { logger.info("deleteConcept entry: {} {} {}", concept.getUri()); String url = getResourceURL(concept.getUri()); logger.info("deleteConcept - URL: {}", url); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("mode", "empty"); Invocation.Builder invocationBuilder = getInvocationBuilder(url, queryParameters); Response response = invocationBuilder.delete(); if (response.getStatus() == 204) { return; } logger.warn(response.readEntity(String.class)); throw new OEClientException( String.format("%s Response received\n%s", response.getStatus(), response.getEntity().toString())); }
@Test public void testCanGETJobSummaries() throws IOException { final Invocation.Builder builder = generateAuthenticatedRequest(RULE, HTTP_JOBS_PATH); for (int i = 0; i < 10; i++) { builder.post(json(REQUEST_AGAINST_SECOND_SPEC), APIJobCreatedResponse.class); } final Response jobSummariesResponse = generateAuthenticatedRequest(RULE, HTTP_JOBS_PATH).get(); assertThat(jobSummariesResponse.getStatus()).isEqualTo(OK); final APIJobDetailsCollection jobSummaries = readJSON(jobSummariesResponse.readEntity(String.class), APIJobDetailsCollection.class); assertThat(jobSummaries.getEntries().isEmpty()).isFalse(); }
@Test public void testOidcResource() { Assert.assertNotNull(resource); final Client client = mock(Client.class); final WebTarget webTarget = mock(WebTarget.class); when(client.target(any(URI.class))).thenReturn(webTarget); when(webTarget.path(anyString())).thenReturn(webTarget); final Invocation.Builder builder = mock(Invocation.Builder.class); when(webTarget.request(anyString())).thenReturn(builder); when(builder.header(anyString(), anyString())).thenReturn(builder); when(builder.get(String.class)).thenReturn("http://callback.trajano.net"); resource.setClient(client); final Response auth = resource.auth("abc", "issuer", "jdk"); assertEquals("example.trajano.net", URI.create(auth.getHeaderString("Location")).getHost()); final JsonObject authUriJson = resource.authUriJson("abc", "issuer", "jdk"); assertEquals("example.trajano.net", URI.create(authUriJson.get("uri").getAsString()).getHost()); }
public <I> void putResource(String resourcePath, final I input, Cookie cookie) throws Exception { Response response = null; try { final Invocation.Builder requestBuilder = getRequestBuilder(resourcePath); response = requestBuilder.async().put(Entity.entity(input, this.mediaType), new InvocationLogCallback()) .get(REQUEST_THREAD_TIMEOUT, TimeUnit.MILLISECONDS); Response.Status status = Response.Status.fromStatusCode(response.getStatus()); if (status == Response.Status.OK || status == Response.Status.NO_CONTENT) { this.lastRequestHeaders = response.getHeaders(); } else { throw new ClientResponseNotOkException(); } } catch (Exception ex) { RestClientException restClientException = createRestClientException("PUT", this.webTarget.getUri() + "/" + resourcePath, input, response, ex); log.debug("Error invoking putResource", restClientException); throw restClientException; } }
private String getToken() { if (!isTokenValid()) { String request = "{\"auth\": {\"tenantName\": \"admin\", " + "\"passwordCredentials\": {\"username\": \"" + userName + "\",\"password\": \"" + pass + "\"}}}"; Invocation.Builder builder = getClientBuilder(keystoneUrl + URI_TOKENS); String response = builder.accept(MediaType.APPLICATION_JSON).post(Entity.json(request), String.class); ObjectMapper mapper = new ObjectMapper(); try { ObjectNode node = (ObjectNode) mapper.readTree(response); tokenId = node.path(PATH_ACCESS).path(PATH_TOKEN).path(PATH_ID).asText(); tokenExpires = node.path(PATH_ACCESS).path(PATH_TOKEN).path(PATH_EXPIRES).asText(); } catch (IOException e) { log.warn("getToken()", e); } log.debug("token response:" + response); } return tokenId; }
@Test(expected = IllegalStateException.class) public void shouldThrowAnExceptionIfMethodTypeIsNotSupported() { final RestClientMetadata metadataMock = mock(RestClientMetadata.class); final RestRequest restRequestMock = mock(RestRequest.class); final Client clientMock = mock(Client.class); final WebTarget webTargetMock = mock(WebTarget.class); final Invocation.Builder builderMock = mock(Invocation.Builder.class); when(webTargetMock.request(anyString())).thenReturn(builderMock); when(clientMock.target(anyString())).thenReturn(webTargetMock); when(restClientMock.getClient()).thenReturn(clientMock); when(restClientMock.getRestClientMetadata()).thenReturn(metadataMock); when(restRequestMock.getMethodType()).thenReturn(MethodType.POST); when(restRequestMock.getPath()).thenReturn("/test"); when(metadataMock.getUrl()).thenReturn("http://localhost:8080"); restManager.executeRequest(restRequestMock); }
@Test public void testRunNewUntitledFromSql() throws IOException, InterruptedException { final String query = "select * from sys.version"; final Invocation invocation = getBuilder( getAPIv2() .path("datasets/new_untitled_sql_and_run") .queryParam("newVersion", newVersion()) ).buildPost(Entity.entity(new CreateFromSQL(query, null), MediaType.APPLICATION_JSON_TYPE)); InitialRunResponse runResponse = expectSuccess(invocation, InitialRunResponse.class); socket.send(new SocketMessage.ListenProgress(runResponse.getJobId())); List<Payload> payloads = socket.awaitCompletion(2, 10); if (payloads.get(1) instanceof ErrorPayload) { Assert.fail(((ErrorPayload) payloads.get(1)).getMessage()); } JobProgressUpdate progressUpdate = (JobProgressUpdate) payloads.get(1); assertTrue(progressUpdate.getUpdate().isComplete()); }
public Evaluation evaluate(String agentId, boolean meta, Map<String, Integer> inputMap) { String url = String.format("%1$s/agent/%2$s", root, agentId); WebTarget webTarget = client.target(url); Invocation.Builder builder = webTarget .request(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .header("Authorization", String.format("Bearer %s", key)) .header("User-Agent", "fuzzy.ai-java/" + version); if (meta) { builder.header("meta", "true"); } Response response = builder.post(Entity.json(inputMap)); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } String evaluationId = response.getHeaderString("X-Evaluation-ID"); @SuppressWarnings("unchecked") Map<String, Double> map = response.readEntity(Map.class); return new Evaluation(evaluationId, map); }
private Invocation getExcelTestQueryInvocation(String filePath, String sheet, boolean extractHeader, boolean hasMergedCells) throws Exception { ExcelFileConfig fileConfig = new ExcelFileConfig(); fileConfig.setSheetName(sheet); if (extractHeader) { fileConfig.setExtractHeader(true); } // false is the default value if (hasMergedCells) { fileConfig.setHasMergedCells(true); } // false is the default value return getBuilder(getAPIv2().path("/source/dacfs_test/file_preview" + filePath)) .buildPost(Entity.json(fileConfig)); }
public static void main(String[] args) throws IOException, URISyntaxException { Client client = ClientBuilder.newClient(); // GET http://api.geonames.org/searchJSON?... WebTarget target = client.target("http://api.geonames.org/searchJSON") .queryParam("q", "kabupaten garut") .queryParam("username", "ceefour"); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); GeonamesSearchResult searchResult = invocationBuilder.get(GeonamesSearchResult.class); LOG.info("Body (GeonamesSearchResult): {}", searchResult); for (Geoname child : searchResult.getGeonames()) { LOG.info("Place: {} ({}, {})", child.getToponymName(), child.getLat(), child.getLng()); } }
public static void main(String[] args) throws IOException, URISyntaxException { Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://api.geonames.org/searchJSON") .queryParam("q", "kabupaten garut") .queryParam("username", "ceefour"); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON); JsonNode bodyNode = invocationBuilder.get(JsonNode.class); LOG.info("Body (JsonNode): {}", bodyNode); for (JsonNode child : bodyNode.get("geonames")) { LOG.info("Place: {} ({}, {})", child.get("toponymName"), child.get("lat"), child.get("lng")); } }
public Response sendRequest(String url, String requestType) { Client client = ClientBuilder.newClient(); System.out.println("Testing " + url); WebTarget target = client.target(url); Invocation.Builder invoBuild = target.request(); Response response = invoBuild.build(requestType).invoke(); return response; }
protected DatasetUIWithHistory save(DatasetUI datasetUI, Long saveVersion) { final Invocation invocation = getBuilder( getAPIv2() .path(versionedResourcePath(datasetUI) + "/save") .queryParam("savedVersion", saveVersion) ).buildPost(entity("", JSON)); return expectSuccess(invocation, DatasetUIWithHistory.class); }
@Override public Optional<User> getByEmail(String userEmail) { String userEmailEncoded = UriComponent.encode(userEmail, QUERY_PARAM_SPACE_ENCODED); Invocation.Builder builder = client .target(USERS_URL) .queryParam("filter[email]", userEmailEncoded) .request(APPLICATION_JSON_TYPE); return getPageable(builder, UserList.class) .filter(user -> user.getEmail().equals(userEmail)) .getSingle(); }
@Test public void testXlsNullSheetName() throws Exception { Invocation inv = getXlsTestQueryInvocation(getUrlPath("/testfiles/excel.xls"), null, false, false); JobDataFragment data = expectSuccess(inv, JobDataFragment.class); assertEquals(6, data.getReturnedRowCount()); assertEquals(5, data.getColumns().size()); }
@Before public void setUp() { NewRelicClient clientMock = mock(NewRelicClient.class); WebTarget webTargetMock = mock(WebTarget.class); Invocation.Builder builderMock = mock(Invocation.Builder.class); when(clientMock.target("/v2/alerts_policies.json")).thenReturn(webTargetMock); when(webTargetMock.queryParam("filter[name]", "policy")).thenReturn(webTargetMock); when(webTargetMock.request(APPLICATION_JSON_TYPE)).thenReturn(builderMock); when(builderMock.get()).thenReturn(responseMock); testee = new DefaultAlertsPoliciesApi(clientMock); }
@Before public void setUp() { NewRelicClient clientMock = mock(NewRelicClient.class); WebTarget webTargetMock = mock(WebTarget.class); Invocation.Builder builderMock = mock(Invocation.Builder.class); when(clientMock.target("/v2/applications.json")).thenReturn(webTargetMock); when(webTargetMock.queryParam("filter[name]", "app")).thenReturn(webTargetMock); when(webTargetMock.request(APPLICATION_JSON_TYPE)).thenReturn(builderMock); when(builderMock.get()).thenReturn(responseMock); testee = new DefaultApplicationsApi(clientMock); }
@Test public void testGet() throws Exception { WebTarget webTarget = client.target(server.getURI().toString()); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.get(); Map<String, String> entity = response.readEntity(new GenericType<Map<String, String>>() {}); assertThat(response.getStatus(), equalTo(OK.getStatusCode())); assertThat(entity.get("message"), equalTo("Hello.")); }
public void delete(String id) { log.debug("DELETE: {}", getEndpointUrl() + "/" + id); final Invocation.Builder invocation = client .target(getEndpointUrl() + "/" + id) .request(MediaType.APPLICATION_JSON) .header("X-Forwarded-User", "pista") .header("X-Forwarded-Access-Token", "kral"); final Response response = invocation.delete(); }
public T get(String id) { log.debug("GET : {}", getEndpointUrl() + "/" + id); final Invocation.Builder invocation = client .target(getEndpointUrl() + "/" + id) .request(MediaType.APPLICATION_JSON) .header("X-Forwarded-User", "pista") .header("X-Forwarded-Access-Token", "kral"); final JsonNode response = invocation.get(JsonNode.class); return transformJsonNode(response, type); }
/** * Resets Syndesis database. * * @return HTTP response code */ public int resetDbWithResponse() { log.info("Resetting syndesis DB."); final Invocation.Builder invocation = client .target(getEndpointUrl()) .request(MediaType.APPLICATION_JSON) .header("X-Forwarded-User", "pista") .header("X-Forwarded-Access-Token", "kral"); int responseCode = invocation.get().getStatus(); log.debug("Reset endpoint reponse: {}", responseCode); return responseCode; }
/** * Execute any HTTP method * * @param httpMethod the HTTP method name(for example GET or POST) * @param bodyContent the request body content(pass null if none) * @return the response */ @PublicAtsApi public RestResponse execute( String httpMethod, Object bodyContent ) { // execute HTTP method Invocation.Builder invocationBuilder = constructInvocationBuilder("execute " + httpMethod + " against"); RestResponse response; if (bodyContent != null) { if ( ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) && StringUtils.isNullOrEmpty(requestMediaType)) { throw new RestException("Content type is not set! Content type is mandatory for PUT and POST."); } response = new RestResponse(invocationBuilder.method(httpMethod, Entity.entity(getActualBodyObject(bodyContent), RestMediaType.toMediaType(requestMediaType, requestMediaCharset)), Response.class)); } else { response = new RestResponse(invocationBuilder.method(httpMethod, Response.class)); } logRESTResponse(response); initInternalVariables(); // return response return response; }
/** * Execute a GET REST method * * @return the response */ @PublicAtsApi public RestResponse get() { // execute GET Invocation.Builder invocationBuilder = constructInvocationBuilder("GET from"); RestResponse response = new RestResponse(invocationBuilder.get()); logRESTResponse(response); initInternalVariables(); // return response return response; }
protected DatasetUI rename(DatasetPath datasetPath, String newName) { final Invocation invocation = getBuilder( getAPIv2() .path("dataset/" + datasetPath.toString() + "/rename") .queryParam("renameTo", newName) ).buildPost(null); return expectSuccess(invocation, DatasetUI.class); }
/** * Performs a REST GET operation on the base XOS REST URI with * an optional additional URI. * * @return JSON string fetched by the GET operation * @deprecated in Cardinal Release */ @Deprecated private String getRest(String uri) { Invocation.Builder builder = getClientBuilder(uri); Response response = builder.get(); if (response.getStatus() != HTTP_OK) { log.info("REST GET request returned error code {}", response.getStatus()); } String jsonString = builder.get(String.class); log.info("JSON read:\n{}", jsonString); return jsonString; }
/** * Performs a REST DELETE operation on the base * XOS REST URI with an optional additional URI. * * @param uri optional additional URI * @deprecated in Cardinal Release */ @Deprecated private void deleteRest(String uri) { Invocation.Builder builder = getClientBuilder(uri); Response response = builder.delete(); if (response.getStatus() != HTTP_NO_CONTENT) { log.info("REST DELETE request returned error code {}", response.getStatus()); } }
protected JobDataFragment getData(String paginationUrl, long offset, long limit) { final Invocation invocation = getBuilder( getAPIv2() .path(paginationUrl) .queryParam("offset", offset) .queryParam("limit", limit) ).buildGet(); return expectSuccess(invocation, JobDataFragment.class); }
/** * Execute a DELETE method * * @return the response */ @PublicAtsApi public RestResponse delete() { // execute DELETE Invocation.Builder invocationBuilder = constructInvocationBuilder("DELETE from"); RestResponse response = new RestResponse(invocationBuilder.delete()); logRESTResponse(response); initInternalVariables(); // return response return response; }
public Collection<Model> getAllModels() throws OEClientException { logger.info("getAllModels entry"); String url = getApiURL() + "/sys/sys:Model/rdf:instance"; logger.info("getAllModels URL: {}", url); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("properties", "meta:displayName,meta:graphUri"); Invocation.Builder invocationBuilder = getInvocationBuilder(url, queryParameters); Date startDate = new Date(); logger.info("getAllModels making call : {}", startDate.getTime()); Response response = invocationBuilder.get(); logger.info("getAllModels call complete: {}", startDate.getTime()); logger.info("getAllModels - status: {}", response.getStatus()); if (response.getStatus() == 200) { String stringResponse = response.readEntity(String.class); if (logger.isInfoEnabled()) logger.info("getAllModels: jsonResponse {}", stringResponse); JsonObject jsonResponse = JSON.parse(stringResponse); JsonArray jsonArray = jsonResponse.get("@graph").getAsArray(); Collection<Model> models = new ArrayList<Model>(); Iterator<JsonValue> jsonValueIterator = jsonArray.iterator(); while (jsonValueIterator.hasNext()) { JsonObject modelObject = jsonValueIterator.next().getAsObject(); models.add(new Model(modelObject)); } return models; } else { throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString())); } }