@Test(dependsOnMethods = "testSubmitEntity") public void testAddProperty() throws Exception { final String guid = tableId._getId(); // add property String description = "bar table - new desc"; ClientResponse clientResponse = addProperty(guid, "description", description); Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); String entityRef = getEntityDefinition(getEntityDefinition(guid)); Assert.assertNotNull(entityRef); tableInstance.set("description", description); // invalid property for the type clientResponse = addProperty(guid, "invalid_property", "bar table"); Assert.assertEquals(clientResponse.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); // non-string property, update String currentTime = String.valueOf(System.currentTimeMillis()); clientResponse = addProperty(guid, "createTime", currentTime); Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); entityRef = getEntityDefinition(getEntityDefinition(guid)); Assert.assertNotNull(entityRef); tableInstance.set("createTime", currentTime); }
public <T> T putWor( String url, String resourcePath, Object object, Class<T> responseClass, Map<String, Object> queryParams, String worToken) { WebTarget target = client.target("https://" + url).path(resourcePath); if (queryParams != null) { for (Map.Entry<String, Object> entry : queryParams.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } } Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); setHeaders(invocationBuilder, worToken); Response putResponse = invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE)); if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) { Logger.error( "PUT call to " + url + "/" + resourcePath + " returned status of " + putResponse.getStatus()); return null; } if (responseClass != null && putResponse.hasEntity() && putResponse.getStatus() == Response.Status.OK.getStatusCode()) return putResponse.readEntity(responseClass); return null; }
@Test( groups = {"wso2.greg", "wso2.greg.es"}, description = "Adding subscription to a policy LC state change", dependsOnMethods = {"createPolicyAssetWithLC"}) public void addSubscriptionForLCStateChange() throws JSONException, IOException { JSONObject dataObject = new JSONObject(); dataObject.put("notificationType", "PublisherLifeCycleStateChanged"); dataObject.put("notificationMethod", "work"); ClientResponse response = genericRestClient.geneticRestRequestPost( publisherUrl + "/subscriptions/policy/" + assetId, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, dataObject.toString(), queryParamMap, headerMap, cookieHeader); assertTrue( (response.getStatusCode() == Response.Status.OK.getStatusCode()), "Wrong status code ,Expected" + Response.Status.OK.getStatusCode() + "Created ,Received " + response.getStatusCode()); }
@Test public void shouldFilterLogEntriesOnEventId() throws Exception { DocumentModel doc = RestServerInit.getFile(1, session); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.putSingle("eventId", "documentModified"); ClientResponse response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); List<JsonNode> nodes = getLogEntries(node); assertEquals(1, nodes.size()); assertEquals("documentModified", nodes.get(0).get("eventId").getValueAsText()); queryParams.putSingle("principalName", "bender"); response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); node = mapper.readTree(response.getEntityInputStream()); nodes = getLogEntries(node); assertEquals(0, nodes.size()); }
public String getSting(String uri) throws BeeterClientException { WebTarget target = client.target(uri); Response response = target.request().get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) return response.readEntity(String.class); else throw new BeeterClientException(response.readEntity(String.class)); }
public String uploadImage(Part file) throws IOException { String imageURL = null; final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); final StreamDataBodyPart stream = new StreamDataBodyPart("file", file.getInputStream()); FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); final MultiPart multiPart = formDataMultiPart.field("fileName", file.getSubmittedFileName()).bodyPart(stream); if (multiPart instanceof FormDataMultiPart) { final FormDataMultiPart dataMultiPart = (FormDataMultiPart) multiPart; final WebTarget target = client.target(configuration.getFileUploadServiceEP()); LOGGER.info("Connecting to file service on " + configuration.getFileUploadServiceEP()); final Response response = target .request() .header(LoginBean.X_JWT_ASSERTION, getJWTToken()) .post(Entity.entity(dataMultiPart, dataMultiPart.getMediaType())); LOGGER.info("Returned from file service " + configuration.getFileUploadServiceEP()); if (Response.Status.OK.getStatusCode() == response.getStatus()) { imageURL = response.readEntity(String.class); } else { LOGGER.log( Level.SEVERE, "TXN service return code is " + response.getStatus() + " , " + "hence can't proceed with the response"); } formDataMultiPart.close(); dataMultiPart.close(); return imageURL; } return imageURL; }
@Test public void testGetDownloadsShouldReturnOkResponse() throws Exception { doReturn("id").when(mockFacade).getDownloadIdInProgress(); Response response = service.getDownloads(); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); }
@Test public void testGetStoragePropertiesShouldReturnOkResponse() throws Exception { doReturn(Collections.emptyMap()).when(mockFacade).loadStorageProperties(); Response response = service.getArtifactProperties("codenvy", "3.1.0"); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); }
@Test public void testGetNodeConfigForMultiNode() throws IOException { Config testConfig = new Config( new LinkedHashMap<>( ImmutableMap.of( "builder_host_name", "builder1.dev.com", "additional_runners", "http://runner1.dev.com:8080/runner/internal/runner,http://runner2.dev.com:8080/runner/internal/runner", "analytics_host_name", "analytics.dev.com", "additional_builders", "", "host_url", "local.dev.com"))); doReturn(testConfig).when(configManager).loadInstalledCodenvyConfig(InstallType.MULTI_SERVER); doReturn(InstallType.MULTI_SERVER).when(configManager).detectInstallationType(); Response result = service.getNodesList(); assertEquals(result.getStatus(), Response.Status.OK.getStatusCode()); assertEquals( result.getEntity(), "{\n" + " \"host_url\" : \"local.dev.com\",\n" + " \"builder_host_name\" : \"builder1.dev.com\",\n" + " \"additional_builders\" : [ ],\n" + " \"analytics_host_name\" : \"analytics.dev.com\",\n" + " \"additional_runners\" : [ \"runner1.dev.com\", \"runner2.dev.com\" ]\n" + "}"); }
@Test public void testGetConfig() throws Exception { doReturn(Collections.emptyMap()).when(mockFacade).getInstallationManagerProperties(); Response response = service.getInstallationManagerServerConfig(); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); }
@Test public void testGetUpdatesShouldReturnOkStatus() throws Exception { doReturn(Collections.emptyList()).when(mockFacade).getAllUpdates(any(Artifact.class)); Response result = service.getUpdates(); assertEquals(result.getStatus(), Response.Status.OK.getStatusCode()); }
/** * Send an HTTP message to a worker and get the result * * <p>Note: expects the worker to respond with OK (200) status code. * * @param uriRequest The request to make * @return An InputStream of the response content */ private InputStream askWorker(HttpUriRequest uriRequest) { try { HttpResponse response = httpClient.execute(uriRequest); if (response.getStatusLine().getStatusCode() != Response.Status.OK.getStatusCode()) { StatusLine statusLine = response.getStatusLine(); EntityUtils.consume(response.getEntity()); logger.warn( "Problem asking worker <" + metadata.getWorkerId() + "> " + "(" + uriRequest.getURI() + "), " + "reason [" + statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "]"); } return response.getEntity().getContent(); } catch (IOException e) { logger.warn("Unable to communicated with worker " + metadata.toString()); throw Throwables.propagate(e); } }
@Test public void testMetadataImportExport() throws PlatformInitializationException, IOException, PlatformImportException { List<MimeType> mimeTypeList = new ArrayList<MimeType>(); mimeTypeList.add(new MimeType("Metadata", ".xmi")); File metadata = new File("test-res/dsw/testData/metadata.xmi"); RepositoryFile repoMetadataFile = new RepositoryFile.Builder(metadata.getName()).folder(false).hidden(false).build(); MetadataImportHandler metadataImportHandler = new MetadataImportHandler( mimeTypeList, (IPentahoMetadataDomainRepositoryImporter) PentahoSystem.get(IMetadataDomainRepository.class)); RepositoryFileImportBundle bundle1 = new RepositoryFileImportBundle.Builder() .file(repoMetadataFile) .charSet("UTF-8") .input(new FileInputStream(metadata)) .mime(".xmi") .withParam("domain-id", "SalesData") .build(); metadataImportHandler.importFile(bundle1); final Response salesData = new DatasourceResource().doGetDSWFilesAsDownload("SalesData"); Assert.assertEquals(salesData.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertNotNull(salesData.getMetadata()); Assert.assertNotNull(salesData.getMetadata().getFirst("Content-Disposition")); Assert.assertEquals( salesData.getMetadata().getFirst("Content-Disposition").getClass(), String.class); Assert.assertTrue( ((String) salesData.getMetadata().getFirst("Content-Disposition")).endsWith(".xmi\"")); }
private void testPredictDiabetes(boolean skipDecoding) throws MLHttpClientException, JSONException { String payload = "[[1,89,66,23,94,28.1,0.167,21],[2,197,70,45,543,30.5,0.158,53]]"; String url = skipDecoding ? "/api/models/" + modelId + "/predict?skipDecoding=true" : "/api/models/" + modelId + "/predict"; response = mlHttpclient.doHttpPost(url, payload); assertEquals( "Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); String reply = mlHttpclient.getResponseAsString(response); JSONArray predictions = new JSONArray(reply); assertEquals( "Expected 2 predictions but received only " + predictions.length(), 2, predictions.length()); if (skipDecoding) { assertEquals( "Expected a double value but found " + predictions.get(0), true, predictions.get(0) instanceof Double); assertEquals( "Expected a double value but found " + predictions.get(1), true, predictions.get(1) instanceof Double); } }
@Test public void callToTestResourceShouldReturnOK() { Response result = target.path("test").request().get(); assertThat(result).isNotNull(); assertThat(result.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); assertThat(result.readEntity(String.class)).isEqualTo("Got it!"); }
/** * A test case for building a model with the given learning algorithm * * @param algorithmName Name of the learning algorithm * @param algorithmType Type of the learning algorithm * @throws MLHttpClientException * @throws IOException * @throws JSONException * @throws InterruptedException */ private void buildModelWithLearningAlgorithm(String algorithmName, String algorithmType) throws MLHttpClientException, IOException, JSONException, InterruptedException { modelName = MLTestUtils.createModelWithConfigurations( algorithmName, algorithmType, MLIntegrationTestConstants.RESPONSE_ATTRIBUTE_DIABETES, MLIntegrationTestConstants.TRAIN_DATA_FRACTION, projectId, versionSetId, mlHttpclient); modelId = mlHttpclient.getModelId(modelName); response = mlHttpclient.doHttpPost("/api/models/" + modelId); assertEquals( "Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); // Waiting for model building to end boolean status = MLTestUtils.checkModelStatusCompleted( modelName, mlHttpclient, MLIntegrationTestConstants.THREAD_SLEEP_TIME_LARGE, 1000); // Checks whether model building completed successfully assertEquals("Model building did not complete successfully", true, status); }
@Test(dependsOnMethods = "testSubmit") public void testGetTypeNames() throws Exception { WebResource resource = service.path("api/atlas/types"); ClientResponse clientResponse = resource .accept(Servlets.JSON_MEDIA_TYPE) .type(Servlets.JSON_MEDIA_TYPE) .method(HttpMethod.GET, ClientResponse.class); assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); String responseAsString = clientResponse.getEntity(String.class); Assert.assertNotNull(responseAsString); JSONObject response = new JSONObject(responseAsString); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); final JSONArray list = response.getJSONArray(AtlasClient.RESULTS); Assert.assertNotNull(list); // Verify that primitive and core types are not returned String typesString = list.join(" "); Assert.assertFalse(typesString.contains(" \"__IdType\" ")); Assert.assertFalse(typesString.contains(" \"string\" ")); }
@WebMethod @GET @Produces("application/json") @Path("/reports") public Response getReports( @QueryParam("aggregatorId") String aggregatorId, @QueryParam("providerId") String providerId, @QueryParam("productClass") String productClass) throws Exception { // Check basic permissions RSUser user = this.userManager.getCurrentUser(); String effectiveAggregator; if (userManager.isAdmin()) { effectiveAggregator = aggregatorId; } else if (null == aggregatorId || aggregatorId.equals(user.getEmail())) { effectiveAggregator = user.getEmail(); } else { String[] args = {"You are not allowed to retrieve report files for the given parameters"}; throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args); } List<RSSReport> files = settlementManager.getSharingReports(effectiveAggregator, providerId, productClass); Response.ResponseBuilder rb = Response.status(Response.Status.OK.getStatusCode()); rb.entity(files); return rb.build(); }
@Test(dependsOnMethods = "testSubmit") public void testGetDefinition() throws Exception { for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) { System.out.println("typeName = " + typeDefinition.typeName); WebResource resource = service.path("api/atlas/types").path(typeDefinition.typeName); ClientResponse clientResponse = resource .accept(Servlets.JSON_MEDIA_TYPE) .type(Servlets.JSON_MEDIA_TYPE) .method(HttpMethod.GET, ClientResponse.class); assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); String responseAsString = clientResponse.getEntity(String.class); Assert.assertNotNull(responseAsString); JSONObject response = new JSONObject(responseAsString); Assert.assertNotNull(response.get(AtlasClient.DEFINITION)); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); String typesJson = response.getString(AtlasClient.DEFINITION); final TypesDef typesDef = TypesSerialization.fromJson(typesJson); List<HierarchicalTypeDefinition<ClassType>> hierarchicalTypeDefinitions = typesDef.classTypesAsJavaList(); for (HierarchicalTypeDefinition<ClassType> classType : hierarchicalTypeDefinitions) { for (AttributeDefinition attrDef : classType.attributeDefinitions) { if ("name".equals(attrDef.name)) { assertEquals(attrDef.isIndexable, true); assertEquals(attrDef.isUnique, true); } } } } }
public String execute( HttpServletRequest request, HttpServletResponse response, WebClient client) { log.debug("Update person"); String result = "/searchPerson.jsp"; String firstName = (String) request.getParameter("name"); String lastName = (String) request.getParameter("surname"); String date = (String) request.getParameter("date"); String login = (String) request.getParameter("log"); String email = (String) request.getParameter("mail"); Person person = new Person(firstName, lastName, date); person.setLogin(login); person.setEmail(email); int i = client.path("/PersonService/updatePerson").put(person).getStatus(); client.reset(); if (i == Response.Status.OK.getStatusCode()) { request.setAttribute("person", person); return result; } if (i == Response.Status.NOT_FOUND.getStatusCode()) { log.debug("Person with login " + person.getLogin() + " not found"); request.setAttribute("error", "Person with login " + person.getLogin() + " not found"); result = "/error.jsp"; } if (i == Response.Status.CONFLICT.getStatusCode()) { log.debug("Error occured while updating person"); request.setAttribute("error", "Error occured while updating person"); result = "/error.jsp"; } return result; }
public boolean delete(String token, String url, String resourcePath) { WebTarget target = client.target("https://" + url).path(resourcePath); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); setHeaders(invocationBuilder, token); Response response = invocationBuilder.delete(); return response.getStatus() == Response.Status.OK.getStatusCode(); }
@Test( groups = {"wso2.greg", "wso2.greg.es"}, description = "Adding ratings added using rest api") public void addRatings() throws JSONException, IOException, InterruptedException { queryParamMap.clear(); queryParamMap.put("path", path); queryParamMap.put("value", "4"); ClientResponse response = genericRestClient.geneticRestRequestPost( registryAPIUrl + generalPath + "rate", MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, null, queryParamMap, headerMap, sessionCookie); assertTrue( (response.getStatusCode() == Response.Status.OK.getStatusCode()), "Wrong status code ,Expected 200 OK ,Received " + response.getStatusCode()); assertTrue(response.getEntity(String.class).equals("4.0")); }
@Test public void succeedsToListByName() throws Throwable { VirtualSubnet expectedVirtualSubnet = new VirtualSubnet(); expectedVirtualSubnet.setId(UUID.randomUUID().toString()); expectedVirtualSubnet.setName("virtualNetwork"); when(frontendClient.list( projectId, Project.KIND, Optional.of("virtualNetwork"), Optional.of(1))) .thenReturn(new ResourceList<>(ImmutableList.of(expectedVirtualSubnet))); Response response = listNetworks(Optional.of("virtualNetwork"), Optional.of(1), Optional.absent()); assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode())); ResourceList<VirtualSubnet> virtualNetworks = response.readEntity(new GenericType<ResourceList<VirtualSubnet>>() {}); assertThat(virtualNetworks.getItems().size(), is(1)); VirtualSubnet actualVirtualSubnet = virtualNetworks.getItems().get(0); assertThat(actualVirtualSubnet, is(expectedVirtualSubnet)); String apiRoutePath = UriBuilder.fromPath(SubnetResourceRoutes.SUBNET_PATH) .build(expectedVirtualSubnet.getId()) .toString(); assertThat(actualVirtualSubnet.getSelfLink().endsWith(apiRoutePath), is(true)); assertThat(new URI(actualVirtualSubnet.getSelfLink()).isAbsolute(), is(true)); }
@Test public void testGetCommand_ReturnsResponseContainingCommandStateDtoOfSpecifiedJob() { // Setup Integer jobId = 1; CommandJob job = createCommandJob(jobId, createImportCommand(), new Date(1l)); CommandJobService mockCommandJobService = createMock(CommandJobService.class); expect(mockCommandJobService.getCommand(jobId)).andReturn(job).atLeastOnce(); WebShellResource sut = new WebShellResource(); sut.setCommandJobService(mockCommandJobService); replay(mockCommandJobService); // Exercise Response response = sut.getCommand(jobId); // Verify mocks verify(mockCommandJobService); // Verify that the HTTP response code was OK (200) and that the body contains // the CommandStateDto of the specified task. assertThat(response).isNotNull(); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); assertThat(response.getEntity()).isNotNull(); assertThat(containsDtoForJob(response, job)).isTrue(); }
@Test public void testPing() throws Exception { WebClient client = WebClient.create(endpointUrl + "/hello/echo/SierraTangoNevada"); Response r = client.accept("text/plain").get(); assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); String value = IOUtils.toString((InputStream) r.getEntity()); assertEquals("SierraTangoNevada", value); }
@Test public void testGetAccount() { Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://localhost:8080/employee-manager-container/rest/account/"); Response response = target.request(MediaType.APPLICATION_JSON).get(); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); }
@Test public void shouldFilterLogEntriesOnEventCategories() throws Exception { DocumentModel doc = RestServerInit.getFile(1, session); List<LogEntry> logEntries = new ArrayList<>(); LogEntry logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("One"); logEntry.setEventId("firstEvent"); logEntries.add(logEntry); logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("One"); logEntry.setEventId("secondEvent"); logEntries.add(logEntry); logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("Two"); logEntry.setEventId("firstEvent"); logEntries.add(logEntry); auditLogger.addLogEntries(logEntries); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("category", "One"); queryParams.add("category", "Two"); ClientResponse response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); List<JsonNode> nodes = getLogEntries(node); assertEquals(3, nodes.size()); queryParams = new MultivaluedMapImpl(); queryParams.add("category", "Two"); response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); node = mapper.readTree(response.getEntityInputStream()); nodes = getLogEntries(node); assertEquals(1, nodes.size()); }
private String getEntityDefinition(ClientResponse clientResponse) throws Exception { Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); JSONObject response = new JSONObject(clientResponse.getEntity(String.class)); final String definition = response.getString(AtlasClient.DEFINITION); Assert.assertNotNull(definition); return definition; }
@Test public void testDeleteDomainFile() { WebResource resource = resource(); ClientResponse response = resource.path("testClientId").path("target").path("problem").delete(ClientResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); }
private void resetRepo() { Client client = ClientBuilder.newClient(); WebTarget target = client.target(rootURI + "/airplanes/default"); Response response = target.request(MediaType.APPLICATION_JSON).get(); Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); response.close(); }