public void testPost() throws IOException, ResourceException { Representation result = clientResource.post("[\"root\"]", MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("[\"root\"]2", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); result = clientResource.post("<root/>", MediaType.APPLICATION_XML); assertNotNull(result); assertEquals("<root/>1", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); }
@Test public void shouldPostWithSSL() throws ResourceException { // Given setSslConfiguration(); final String uri = "URI"; final Map<String, String> queryParameters = new HashMap<String, String>(); final Map<String, String> headers = new HashMap<String, String>(); final Context context = mock(Context.class); final ConcurrentHashMap<String, Object> requestAttributes = new ConcurrentHashMap<String, Object>(); final JSONObject restResponse = mock(JSONObject.class); given(resource.getContext()).willReturn(context); given(context.getAttributes()).willReturn(requestAttributes); given(resource.post(anyObject(), eq(JSONObject.class))).willReturn(restResponse); given(restResponse.toString()).willReturn("{}"); // When final JsonValue response = restClient.post(uri, queryParameters, headers); // Then verify(resource, never()).addQueryParameter(anyString(), anyString()); verify(requestHeaders, never()).set(anyString(), anyString()); verify(resource).getContext(); assertTrue(requestAttributes.containsKey("sslContextFactory")); assertEquals(response.size(), 0); }
public GetStreamKeyStreamServer getGetStreamKeyStreamServer( String songID, GetCountry country, String sesionID) { GetStreamKeyStreamServer res = null; String post = "{\"method\":\"getStreamKeyStreamServer\",\"header\":{\"wsKey\":\"" + KEY + "\",\"sessionID\":\"" + sesionID + "\"},\"parameters\":{\"songID\":\"" + songID + "\",\"country\":" + country.getResult() + ",\"lowBitrate\":\"\"}}"; ClientResource cr = new ClientResource(uri + getSignatures(post)); try { res = gson.fromJson(cr.post(post).getText(), GetStreamKeyStreamServer.class); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; }
/** * Invoke POST * * @param uri String * @param params String * @param object Representation * @param parameters Map<String, String> * @param uriTemplate String */ public void postDocAPI( String uri, String params, Representation object, Map<String, String> parameters, String uriTemplate) { ClientResource cr = new ClientResource(uri); System.out.println("URI: " + uriTemplate); docAPI.appendSection("Format"); // url type // request ClientResource crLocal = new ClientResource(uriTemplate); docAPI.appendRequest(Method.POST, crLocal); // parameters docAPI.appendParameters(parameters); docAPI.appendSection("Example"); docAPI.appendRequest(Method.POST, cr, object); Representation result = cr.post(object, docAPI.getMediaTest()); // response docAPI.appendResponse(result); RIAPUtils.exhaust(result); }
public void postContent(String content) { ClientResource cr = null; try { cr = new ClientResource(uriShare + "?access_token=" + access_token + "&message=" + content); cr.post(content); } catch (ResourceException re) { System.err.println("Error when retrieving friends: " + cr.getResponse().getStatus()); System.err.println(uri + "?access_token" + access_token); } }
@Override public String call() throws Exception { String url = buildUrl(); System.out.println("Sending ==>" + url); ClientResource client = new ClientResource(url); StringWriter writer = new StringWriter(); client.post(javascript, MediaType.APPLICATION_JSON).write(writer); return writer.toString(); }
/** * Tries to send a query to the PushEndpoint running on http://localhost:8183/pushendpoint. * * @throws Exception */ @Test public void sendQueryToPushEndpoint() throws Exception { // construct workflow ClientResource rdfResource = new ClientResource(Resources.MGMT_WORKFLOWS_URL); Form form = new Form(); form.add("workflow", SampleRdfWorkflows.getWorkflowWithPushEndpoint()); Representation rep = form.getWebRepresentation(); rep.setMediaType(MediaType.APPLICATION_RDF_XML); Representation rdfResponse = rdfResource.post(rep); Reference url = rdfResponse.getLocationRef(); // retrieve endpoint ClientResource endpointResource = new ClientResource(url + "/endpoint?urn=urn:eu.larkc.endpoint.push.ep1"); Representation endpointResponse = endpointResource.get(); Reference pushEndpointUrl = endpointResponse.getLocationRef(); logger.debug("PushEndpoint URL: {}", pushEndpointUrl); // execute query ClientResource pushEndpointResource = new ClientResource(pushEndpointUrl); Form queryForm = new Form(); queryForm.add("query", SampleQueries.WHO_KNOWS_FRANK); Representation queryRep = queryForm.getWebRepresentation(); pushEndpointResource.post(queryRep); Assert.assertEquals(200, pushEndpointResource.getResponse().getStatus().getCode()); // delete workflow ClientResource workflowResource = new ClientResource(url); workflowResource.delete(); }
// TODO Die Parameter beim Request werden nicht korrekt übergeben. Keine // Ahnung woran es liegt. @Test(enabled = false) public void testPostCompute() { // connect to api clientResource.setReference( OcciConfig.getInstance().config.getString("occi.server.location") + "compute"); // Tests if client resource is connected to api Assert.assertNotNull(clientResource); // try to create a compute resource String architecture = "x86"; String cores = "20"; String hostname = "Ubuntu"; String speed = "2000000"; String memory = "1024"; String category = "compute"; // create new request and add all attributes Form form = new Form(); form.add("occi.compute.architecture", architecture); form.add("occi.compute.cores", cores); form.add("occi.compute.hostname", hostname); form.add("occi.compute.speed", speed); form.add("occi.compute.memory", memory); form.add("category", category); System.out.println("\n FORM " + form.toString()); // create new representation Representation representation = null; try { // send post request representation = clientResource.post(form.toString(), MediaType.TEXT_PLAIN); } catch (Exception ex) { System.out.println("Failed to execute POST request " + ex.getMessage()); } Assert.assertNotNull(representation); // get request and print it in debugger Request request = Request.getCurrent(); System.out.println(request.toString() + "\n\n" + form.getMatrixString()); System.out.println("--------------------------------"); // get current response Response response = Response.getCurrent(); Assert.assertNotNull(response); System.out.println("Response: " + response.toString()); try { representation.write(System.out); } catch (IOException e) { System.out.println(e.getMessage()); } System.out.println("\n--------------------------------"); }
public GetCountry getCountry() { GetCountry res = null; String post = "{\"method\":\"getCountry\",\"header\":{\"wsKey\":\"" + KEY + "\"},\"parameters\":[]}"; ClientResource cr = new ClientResource(uri + getSignatures(post)); try { res = gson.fromJson(cr.post(post).getText(), GetCountry.class); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; }
public void doPost(String path, String fileToPost) { ClientResource cr = new ClientResource(testContext, BASE_URI + path); Form form = new Form(); InputStream in = getClass().getClassLoader().getResourceAsStream(fileToPost); try { Properties prop = new Properties(); prop.load(in); for (Entry<Object, Object> entry : prop.entrySet()) { form.add((String) entry.getKey(), (String) entry.getValue()); } cr.post(form.getWebRepresentation()); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } }
@Override protected JSONObject doInBackground(Object... params) { Address requestAddress = (Address) params[1]; ClientResource res = new ClientResource(params[0].toString()); res.setMethod(Method.POST); double latitude = 0; double longitude = 0; // Location returns null if no position is currently available. In this case, cancel the // request. if (requestAddress == null) { JSONObject o = new JSONObject(); try { o.put("ID", -1); } catch (JSONException e) { e.printStackTrace(); } return o; } else { latitude = requestAddress.getLatitude(); longitude = requestAddress.getLongitude(); } int bottomId = 10000; // Indicates that we want the latest. int sort = ((Integer) params[2]).intValue(); JSONObject obj = JSONMessage.getPosts( bottomId, "", Double.valueOf(latitude), Double.valueOf(longitude), sort); StringRepresentation stringRep = new StringRepresentation(obj.toString()); stringRep.setMediaType(MediaType.APPLICATION_JSON); JSONObject o = null; try { Representation r = res.post(stringRep); o = new JSONObject(r.getText()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return o; }
protected void assertResultsPresentInDataResponse( String url, ObjectNode body, int numberOfResultsExpected, String variableName, Object variableValue) throws JsonProcessingException, IOException { // Do the actual call ClientResource client = getAuthenticatedClient(url); Representation response = client.post(body); // Check status and size assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus()); JsonNode dataNode = objectMapper.readTree(response.getStream()).get("data"); assertEquals(numberOfResultsExpected, dataNode.size()); // Check presence of ID's if (variableName != null) { boolean variableFound = false; Iterator<JsonNode> it = dataNode.iterator(); while (it.hasNext()) { JsonNode variableNode = it.next(); String name = variableNode.get("variableName").getTextValue(); if (variableName.equals(name)) { variableFound = true; if (variableValue instanceof Boolean) { assertTrue( "Variable value is not equal", variableNode.get("value").asBoolean() == (Boolean) variableValue); } else if (variableValue instanceof Integer) { assertTrue( "Variable value is not equal", variableNode.get("value").asInt() == (Integer) variableValue); } else { assertTrue( "Variable value is not equal", variableNode.get("value").asText().equals((String) variableValue)); } } } assertTrue("Variable " + variableName + " is missing", variableFound); } client.release(); }
/** * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each * test results are documented and displayed in standard out with the following information: * * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The * start time of the last test run STOP - The stop time of the last test run THREAD - The thread * id handling this test case RESULT - The result of the test. Either the number of bytes returned * or an error message. */ private void doTest() { String result = ""; this.reqCount++; // Connect and run test steps Date startTime = new Date(); try { ClientResource client = new ClientResource(this.myURL); // place order JSONObject json = new JSONObject(); json.put("payment", "quarter"); json.put("action", "place-order"); client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON); // Get Gumball Count Representation result_string = client.get(); JSONObject json_count = new JSONObject(result_string.getText()); result = Integer.toString((int) json_count.get("count")); } catch (Exception e) { result = e.toString(); } finally { Date stopTime = new Date(); // Print Report of Result: System.out.println( "======================================\n" + "URL => " + this.myURL + "\n" + "REQ CNT => " + this.reqCount + "\n" + "START => " + startTime + "\n" + "STOP => " + stopTime + "\n" + "THREAD => " + Thread.currentThread().getName() + "\n" + "RESULT => " + result + "\n"); } }
/** * Invoke POST * * @param item DataSet */ public void create(DataSet item) { Representation rep = GetRepresentationUtils.getRepresentationDataset(item, MediaType.APPLICATION_JSON); ClientResource cr = new ClientResource(getBaseUrl()); Representation result = cr.post(rep, MediaType.APPLICATION_JSON); assertTrue(cr.getStatus().isSuccess()); assertNotNull(result); Response response = getResponse(MediaType.APPLICATION_JSON, result, DataSet.class); assertTrue(response.getSuccess()); assertNotNull(response.getItem()); DataSet rs = (DataSet) response.getItem(); assertEquals(rs, item); RIAPUtils.exhaust(result); cr.release(); }
public StartSession getStartSession() { StartSession res = null; String post = "{\"method\":\"startSession\",\"header\":{\"wsKey\":\"" + KEY + "\"},\"parameters\":[]}"; String sig = getSignatures(post); ClientResource cr = new ClientResource(uri + sig); try { res = gson.fromJson(cr.post(post).getText(), StartSession.class); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; }
/** * Invoke an order and return the status returned * * @param urlAttach2 the url attachment of the resource * @return the TaskModel returned representing the status of the Task resource */ protected TaskModel invokeOrder(String urlAttach2, String parameters) { String url = getHostUrl() + PROJECT_URL + urlAttach2 + parameters; Representation result = null; try { ClientResource cr = new ClientResource(url); ChallengeResponse chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); result = cr.post(null, getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); Response response = getResponse(getMediaTest(), result, TaskModel.class); assertTrue(response.getSuccess()); return (TaskModel) response.getItem(); } finally { RIAPUtils.exhaust(result); } }
public static void main(String[] args) throws ResourceException, IOException { if (args.length != 1) { System.err.println("Please specify name of file that includes the request."); } else { Properties properties = new Properties(); properties.load(new FileInputStream(args[0])); ClientResource comparisonsResource = new ClientResource(properties.getProperty("endpoint")); try { comparisonsResource.get().write(System.out); System.out.println("\n"); } catch (ResourceException e) { System.out.println(e); } try { // first comparison String firstComparisonId = UUID.randomUUID().toString(); Comparison comparison = new Comparison( firstComparisonId, properties.getProperty("dataset1"), properties.getProperty("dataset2"), properties.getProperty("adapter"), properties.getProperty("extractor"), properties.getProperty("measure")); Representation post = comparisonsResource.post(getComparisonRepresentation(comparison)); post.write(System.out); System.out.println("\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ResourceException e) { logger.log(Level.SEVERE, "Error connecting to server", e); } } }
@Test public void shouldPostWithEmptyQueryParameters() throws ResourceException { // Given final String uri = "URI"; final Map<String, String> queryParameters = new HashMap<String, String>(); final Map<String, String> headers = new HashMap<String, String>(); final JSONObject restResponse = mock(JSONObject.class); given(resource.post(anyObject(), eq(JSONObject.class))).willReturn(restResponse); given(restResponse.toString()).willReturn("{}"); // When final JsonValue response = restClient.post(uri, queryParameters, headers); // Then verify(resource, never()).addQueryParameter(anyString(), anyString()); verify(requestHeaders, never()).set(anyString(), anyString()); verify(resource, never()).getContext(); assertEquals(response.size(), 0); }
/** Post some JSON to the user userstorage */ private void postJSON() { // http://localhost:8182/sitools/userstorage/admin?filepath=%2Ftmp&filename=SvaRecordDefinitionFile.json StringRepresentation repr = new StringRepresentation(urlFileContent, MediaType.APPLICATION_JSON); Reference reference = new Reference( getBaseUrl() + settings .getString(Consts.APP_USERSTORAGE_USER_URL) .replace("{identifier}", userLogin) + "/files"); reference.addQueryParameter("filename", cartFileName); reference.addQueryParameter("filepath", cartFilePath); ClientResource cr = new ClientResource(reference); ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(challenge); Representation result = cr.post(repr, MediaType.APPLICATION_JSON); assertNotNull(result); RIAPUtils.exhaust(result); }
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String nom2 = request.getParameter("nom"); String prenom2 = request.getParameter("prenom"); String tel2 = request.getParameter("telephone"); String mail2 = request.getParameter("mail"); String adresse2 = request.getParameter("adresse"); String diplome2 = request.getParameter("diplome"); String competence2 = request.getParameter("competence"); String situationPro2 = request.getParameter("situationPro"); String url6 = CANDIDAT; ClientResource resource6 = new ClientResource(url6); Form form2 = new Form( "nom=" + nom2 + "&prenom=" + prenom2 + "&tel=" + tel2 + "&mail=" + mail2 + "&adresse=" + adresse2 + "&diplome=" + diplome2 + "&competence=" + competence2 + "&situationPro=" + situationPro2); form2.encode(CharacterSet.UTF_8); Representation rep2 = form2.getWebRepresentation(); resource6.post(rep2); }
public GetSongSearchResults getSongSearchResults( String query, Integer limit, Integer offset, GetCountry country) { GetSongSearchResults res = null; ClientResource cr = null; String post = "{\"method\":\"getSongSearchResults\",\"header\":{\"wsKey\":\"" + KEY + "\"},\"parameters\":{\"query\":\"" + query + "\",\"country\":" + country.getResult() + ",\"limit\":\"" + limit + "\",\"offset\":\"" + offset + "\"}}"; // String post = "{\"method\":\"getSongSearchResults\",\"header\":{\"wsKey\":\""+ KEY // + "\"},\"parameters\":{\"query\":\""+query // +"\",\"country\":\"\",\"limit\":\""+limit // +"\",\"offset\":\""+offset+"\"}}"; String sig = getSignatures(post); cr = new ClientResource(uri + sig); try { res = gson.fromJson(cr.post(post).getText(), GetSongSearchResults.class); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; }
@Deployment public void testSubmitFormData() throws Exception { Map<String, Object> variableMap = new HashMap<String, Object>(); variableMap.put("SpeakerName", "John Doe"); Address address = new Address(); variableMap.put("address", address); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variableMap); String processInstanceId = processInstance.getId(); String processDefinitionId = processInstance.getProcessDefinitionId(); Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_FORM_DATA)); ObjectNode requestNode = objectMapper.createObjectNode(); requestNode.put("taskId", task.getId()); ArrayNode propertyArray = objectMapper.createArrayNode(); requestNode.put("properties", propertyArray); ObjectNode propNode = objectMapper.createObjectNode(); propNode.put("id", "room"); propNode.put("value", 123l); propertyArray.add(propNode); try { client.post(requestNode); } catch (Exception e) { // expected assertEquals(Status.SERVER_ERROR_INTERNAL, client.getResponse().getStatus()); } propNode = objectMapper.createObjectNode(); propNode.put("id", "street"); propNode.put("value", "test"); propertyArray.add(propNode); client.release(); client.post(requestNode); assertEquals(Status.SUCCESS_NO_CONTENT, client.getResponse().getStatus()); task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); assertNull(task); processInstance = runtimeService .createProcessInstanceQuery() .processInstanceId(processInstanceId) .singleResult(); assertNull(processInstance); List<HistoricVariableInstance> variables = historyService .createHistoricVariableInstanceQuery() .processInstanceId(processInstanceId) .list(); Map<String, HistoricVariableInstance> historyMap = new HashMap<String, HistoricVariableInstance>(); for (HistoricVariableInstance historicVariableInstance : variables) { historyMap.put(historicVariableInstance.getVariableName(), historicVariableInstance); } assertEquals("123", historyMap.get("room").getValue()); assertEquals(processInstanceId, historyMap.get("room").getProcessInstanceId()); processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variableMap); processInstanceId = processInstance.getId(); task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); requestNode.put("taskId", task.getId()); propNode = objectMapper.createObjectNode(); propNode.put("id", "direction"); propNode.put("value", "nowhere"); propertyArray.add(propNode); try { client.release(); client.post(requestNode); } catch (Exception e) { // expected assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, client.getResponse().getStatus()); } propNode.put("value", "up"); client.release(); client.post(requestNode); assertEquals(Status.SUCCESS_NO_CONTENT, client.getResponse().getStatus()); task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); assertNull(task); processInstance = runtimeService .createProcessInstanceQuery() .processInstanceId(processInstanceId) .singleResult(); assertNull(processInstance); variables = historyService .createHistoricVariableInstanceQuery() .processInstanceId(processInstanceId) .list(); historyMap.clear(); for (HistoricVariableInstance historicVariableInstance : variables) { historyMap.put(historicVariableInstance.getVariableName(), historicVariableInstance); } assertEquals("123", historyMap.get("room").getValue()); assertEquals(processInstanceId, historyMap.get("room").getProcessInstanceId()); assertEquals("up", historyMap.get("direction").getValue()); requestNode = objectMapper.createObjectNode(); requestNode.put("processDefinitionId", processDefinitionId); propertyArray = objectMapper.createArrayNode(); requestNode.put("properties", propertyArray); propNode = objectMapper.createObjectNode(); propNode.put("id", "number"); propNode.put("value", 123); propertyArray.add(propNode); client.release(); Representation response = client.post(requestNode); assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus()); JsonNode responseNode = objectMapper.readTree(response.getStream()); assertNotNull(responseNode.get("id").asText()); assertEquals(processDefinitionId, responseNode.get("processDefinitionId").asText()); task = taskService .createTaskQuery() .processInstanceId(responseNode.get("id").asText()) .singleResult(); assertNotNull(task); }