@Post public Representation requestToken(Representation input) throws JSONException { Form response = new Form(); response.add(ERROR, OAuthError.invalid_client.name()); response.add(ERROR_DESC, "Invalid Client"); return response.getWebRepresentation(); }
public void testMatrix() { final Reference ref1 = new Reference("http://domain.tld/whatever/a=1;b=2;c=4?x=a&y=b"); final Reference ref2 = new Reference("http://domain.tld/whatever/a=1/foo;b=2;c=4;d?x=a&y=b"); final Reference ref3 = new Reference("http://domain.tld/whatever/a=1;b=2;c=4/foo?x=a&y=b"); assertTrue(ref1.hasMatrix()); assertTrue(ref2.hasMatrix()); assertFalse(ref3.hasMatrix()); assertEquals("b=2;c=4", ref1.getMatrix()); assertEquals("b=2;c=4;d", ref2.getMatrix()); final Form form1 = ref1.getMatrixAsForm(); assertEquals("2", form1.getFirstValue("b")); assertEquals("4", form1.getFirstValue("c")); final Form form2 = ref1.getMatrixAsForm(); assertEquals("2", form2.getFirstValue("b")); assertEquals("4", form2.getFirstValue("c")); assertNull(form2.getFirstValue("d")); final Form newForm = new Form(); newForm.add("a", "1"); newForm.add("b", "2"); newForm.add("c", "4"); assertEquals("a=1;b=2;c=4", newForm.getMatrixString()); }
/** Test Amazon S3 authentication. */ public void testAwsS3() { HttpAwsS3Helper helper = new HttpAwsS3Helper(); // Example Object GET ChallengeWriter cw = new ChallengeWriter(); ChallengeResponse challenge = new ChallengeResponse( ChallengeScheme.HTTP_AWS_S3, "0PN5J17HBGZHT7JJ3X82", "uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o"); Request request = new Request(Method.GET, "http://johnsmith.s3.amazonaws.com/photos/puppy.jpg"); Form httpHeaders = new Form(); httpHeaders.add(HeaderConstants.HEADER_DATE, "Tue, 27 Mar 2007 19:36:42 +0000"); helper.formatRawResponse(cw, challenge, request, httpHeaders); assertEquals("0PN5J17HBGZHT7JJ3X82:xXjDGYUmKxnwqr5KXNPGldn5LbA=", cw.toString()); // Example Object PUT cw = new ChallengeWriter(); request.setMethod(Method.PUT); httpHeaders.set(HeaderConstants.HEADER_DATE, "Tue, 27 Mar 2007 21:15:45 +0000", true); httpHeaders.add(HeaderConstants.HEADER_CONTENT_LENGTH, "94328"); httpHeaders.add(HeaderConstants.HEADER_CONTENT_TYPE, "image/jpeg"); helper.formatRawResponse(cw, challenge, request, httpHeaders); assertEquals("0PN5J17HBGZHT7JJ3X82:hcicpDDvL9SsO6AkvxqmIWkmOuQ=", cw.toString()); }
@GET @Path("form") @Produces("application/x-www-form-urlencoded") public Form formGet() { final Form form = new Form(); form.add("firstname", "Angela"); form.add("lastname", "Merkel"); return form; }
@Post public Representation requestToken(Representation input) throws JSONException { Form form = new Form(input); assertThat(form.getFirstValue(CLIENT_ID), is(STUB_CLIENT_ID)); assertThat(form.getFirstValue(CLIENT_SECRET), is(STUB_CLIENT_SECRET)); Form response = new Form(); response.add(ACCESS_TOKEN, "foo"); response.add("expires", "3600"); return response.getWebRepresentation(); }
@Options public void doOptions(Representation entity) { Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers"); if (responseHeaders == null) { responseHeaders = new Form(); getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders); } responseHeaders.add("Access-Control-Allow-Origin", "*"); responseHeaders.add("Access-Control-Allow-Methods", "POST,OPTIONS"); responseHeaders.add("Access-Control-Allow-Headers", "Content-Type"); responseHeaders.add("Access-Control-Allow-Credentials", "false"); responseHeaders.add("Access-Control-Max-Age", "60"); }
@Override protected void afterHandle(Request request, Response response) { Form headers = (Form) response.getAttributes().get("org.restlet.http.headers"); if (headers == null) { response.getAttributes().put("org.restlet.http.headers", headers = new Form()); } Long start = (Long) request.getAttributes().get("start.request.time"); long processTime = System.currentTimeMillis() - start; headers.add("CacheMiss", start + " " + processTime); headers = (Form) request.getAttributes().get("org.restlet.http.headers"); /* headers.add("Cache-Control", "max-age=3600"); long time = new Date().getTime() + 3600000; if (response.getEntity() != null) { if (response.getEntity().getModificationDate() == null) { response.getEntity().setModificationDate(new Date(time - 7200000)); } if (response.getEntity().getExpirationDate() == null) { response.getEntity().setExpirationDate(new Date(time)); } } */ }
@Test public void peutAjouterUneRéponse() { DetailsQuestion detailsQuestion = laRechercheRetourne(); initialiseRessource(detailsQuestion); Form formulaire = new Form(); formulaire.add("libelle", "Une réponse"); formulaire.add("correcte", "checked"); questionRessource.ajouteRéponse(formulaire); ArgumentCaptor<AjoutReponseMessage> captor = ArgumentCaptor.forClass(AjoutReponseMessage.class); verify(busCommande).envoie(captor.capture()); AjoutReponseMessage message = captor.getValue(); assertThat(message.idQuestion).isEqualTo(UUID.fromString(detailsQuestion.getId())); assertThat(message.correcte).isTrue(); assertThat(message.libellé).isEqualTo("Une réponse"); }
@Test @Ignore public void returns_bad_request_for_contact_with_too_short_name() { resource.init(null, request, response); Form form = new Form(); form.add("name", "A"); resource.post(form); assertThat(response.getStatus().getCode(), is(400)); }
/** * * * * @author suryo_p handle "create" and "edit" account request * @param entity * @return response JSONObject in String */ @Post("json") public String accountService(String entity) { Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers"); if (responseHeaders == null) { responseHeaders = new Form(); getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders); } responseHeaders.add("Access-Control-Allow-Origin", "*"); responseHeaders.add("Access-Control-Allow-Methods", "POST"); responseHeaders.add("Access-Control-Max-Age", "1728000"); responseHeaders.add("Access-Control-Allow-Headers", "Content-Type"); responseHeaders.add("Access-Control-Allow-Credentials", "false"); String response = null; JSONObject jsonObject = new JSONObject(); CreateAndEditAccountManager createAndEditAccountManager = new CreateAndEditAccountManager(); try { JSONObject request = new JSONObject(entity); String statusAccount = request.getString(STATUS); if (statusAccount.equals("create")) { jsonObject = createAndEditAccountManager.createAccount(request); } else if (statusAccount.equals("update")) { jsonObject = createAndEditAccountManager.editAccount(request); } else if (statusAccount.equals("delete")) { String employeeId = request.getString(EMPLOYEE_ID); jsonObject = createAndEditAccountManager.deactivateAccount(employeeId); } else { jsonObject.put("status", "Error"); jsonObject.put("message", "Bad Request"); } response = jsonObject.toString(); } catch (JSONException e) { throw new AttendanceException(e); } return response; }
public void testPost2() throws Exception { String aparam = "{'aradon':" + "[{'name':'employee','section':'system','path':'/lore/test/ion.dev.floor4/3477','param':{'empno':'3477','ename':'ddd','address':'ddd','sal':'20','dept':'ddd','memo':'222','aradon.result.method':'post', 'aradon.result.format':'json'}}, " + " {'name':'indexer','section':'system','path':'/index/ion.dev.floor4/3477','param':{'empno':'3477','ename':'ddd','address':'ddd','sal':'20','dept':'ddd','memo':'222','aradon.result.method':'post', 'aradon.result.format':'json'}}" + "]}"; Request request = new Request(Method.POST, prefixURL); Form form = new Form(); form.add("aradon.parameter", aparam); request.setEntity(form.getWebRepresentation()); handle("resource/config/aradon-config.xml", request); }
@SuppressWarnings("unchecked") public void testUnmodifiable() { Form form = new Form(); form.add("name1", "value1"); try { Series<Parameter> unmodifiableForm = (Series<Parameter>) Series.unmodifiableSeries(form); unmodifiableForm.add("name2", "value2"); fail("The series should be unmodifiable now"); } catch (UnsupportedOperationException uoe) { // As expected } }
public void testPutGet() { Form myForm = myResource.represent(); assertNull(myForm); myForm = new Form(); myForm.add("param1", "value1"); myForm.add("param2", "value2"); myResource.store(myForm); myForm = myResource.represent(); assertNotNull(myForm); assertEquals("value1", myForm.getFirstValue("param1")); assertEquals("value2", myForm.getFirstValue("param2")); }
public void testLetsGet() throws Exception { String aparam = "{aradon:" + "[{name:'abcd', section:'system', path:'/repository/bulletin.bleujin', param:{p1:'abc', p2:'${sequence.result.nodes[0].currval}', p3:['red','green','white'], modified:'${currdate.result.nodes[0].now}', 'aradon.result.format':'json', 'aradon.result.method':'get'}, page:{pageNo:1, listNum:10, screenCount:1}}, " + " {name:'sequence', section:'system', path:'/sequence/myseq', param:{'aradon.result.format':'json', 'aradon.result.method':'put'}}, " + " {name:'currdate', section:'system', path:'/utils/datetime', param:{'aradon.result.format':'json', 'aradon.result.method':'get'}}" + "]}"; Request request = new Request(Method.POST, prefixURL); Form form = new Form(); form.add("aradon.parameter", aparam); request.setEntity(form.getWebRepresentation()); handle("resource/config/aradon-config.xml", request); }
/** * 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(); }
public void testLetsPost() throws Exception { String aparam = "{aradon:" + "[{name:'board', section:'system', path:'/repository/bulletin.bleujin', param:{subject:'HiHi This is Let', content:'11월엔 투피어', boardid:'board1', reguserid:'bleujin', no:'${sequence.result.nodes[0].currval}', modified:'${currdate.result.nodes[0].now}', 'aradon.result.format':'json', 'aradon.result.method':'post', 'aradon.page.pageNo':1, 'aradon.page.listNum':10, 'aradon.page.screenCount':10}}, " + " {name:'sequence', section:'system', path:'/sequence/bulletin.bleujin', param:{'aradon.result.format':'json', 'aradon.result.method':'put'}}, " + " {name:'currdate', section:'system', path:'/utils/datetime', param:{'aradon.result.format':'json', 'aradon.result.method':'get'}}" + "]}"; Request request = new Request(Method.POST, prefixURL); Form form = new Form(); form.add("aradon.parameter", aparam); request.setEntity(form.getWebRepresentation()); handle("resource/config/aradon-config.xml", request); }
@Test public void peutModifierLUtilisateur() throws IOException { DetailsUtilisateur details = laRechercheRetourne(); details.setNom("Levacher"); details.setMotDePasse(MD5.crypteAvecCle("Motdepasse1=")); initialiseRessource(details); Form formulaire = new Form(); formulaire.add("nom", details.getNom()); formulaire.add("nouveauMotDePasse", "Azerty1="); formulaire.add("telephone", "0607080910"); Representation represente = ressource.modifie(formulaire); ArgumentCaptor<ModificationUtilisateurMessage> capteur = ArgumentCaptor.forClass(ModificationUtilisateurMessage.class); verify(busCommande).envoie(capteur.capture()); ModificationUtilisateurMessage commande = capteur.getValue(); assertThat(commande.id).isEqualTo(UUID.fromString(details.getId())); assertThat(commande.nom).isEqualTo(details.getNom()); assertThat(commande.motDePasse).isEqualTo(MD5.crypteAvecCle("Azerty1=")); assertThat(commande.telephone).isEqualTo("0607080910"); assertThat(ressource.getStatus()).isEqualTo(Status.SUCCESS_ACCEPTED); assertThat(represente.getText()).isEqualTo(ReponseRessource.OK.toString()); }
private static Representation getComparisonRepresentation(Comparison comparison) { Form form = new Form(); form.add("id", comparison.getId()); form.add("dataset1", comparison.getFirstDataset()); form.add("dataset2", comparison.getSecondDataset()); form.add("adapter", comparison.getAdapterId()); form.add("extractor", comparison.getExtractorId()); form.add("measure", comparison.getMeasureId()); return form.getWebRepresentation(); }
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(); } }
// 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--------------------------------"); }
/** * Decodes form parameters that are sent double encoded by performing one decode step on their * values, if their restlet framework decoded value starts with an "%". * * @param request a restlet request * @throws IOException did not occur during tests but may. * @throws IllegalArgumentException if an Encode representation is received. */ void decodeFormParamsIfDoubleEncoded(Request request) throws IOException { Representation r = request.getEntity(); if (r instanceof EncodeRepresentation) throw new IllegalArgumentException( "Received an Encode representation." + " This filter must be after the Encoder filter. please check your filter chain order."); if (!(r instanceof EmptyRepresentation)) { ContentType c = new ContentType(r); if (MediaType.APPLICATION_WWW_FORM.equals(c.getMediaType(), true)) { Form form = new Form(r); Form newform = new Form(r); Map<String, String> valuesMap = form.getValuesMap(); for (Map.Entry<String, String> e : valuesMap.entrySet()) { if (DBG) ThreadLocalStopwatch.now("" + e.getKey() + " - " + e.getValue()); String shouldBeDecodedValue = e.getValue(); if (shouldBeDecodedValue.startsWith("%")) { shouldBeDecodedValue = URLDecoder.decode(e.getValue(), DECODER_CHAR_SET); totalDecodings.incrementAndGet(); if (DBG) { ThreadLocalStopwatch.now("DECODED " + request.getResourceRef()); ThreadLocalStopwatch.now( "DECODED " + totalDecodings.get() + " : " + e.getKey() + " - " + shouldBeDecodedValue); } } newform.add(e.getKey(), shouldBeDecodedValue); } // we must always set the entity, because above getEntitiy call causes // NPEs later if repeated by the framework. request.setEntity(newform.encode(), c.getMediaType()); } } }
private static Form createForm() { Form form = new Form(); form.add("firstname", "Angela"); form.add("lastname", "Merkel"); return form; }
private Representation handle(ParameterList request) { Logger log = getLogger(); log.info("Handle on OP"); ConcurrentMap<String, Object> attribs = getContext().getAttributes(); ServerManager manager = (ServerManager) attribs.get("openid_manager"); log.info("OP endpoint = " + manager.getOPEndpointUrl()); String mode = request.hasParameter("openid.mode") ? request.getParameterValue("openid.mode") : null; Message response; String responseText; if ("associate".equals(mode)) { // --- process an association request --- response = manager.associationResponse(request); responseText = response.keyValueFormEncoding(); } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) { // interact with the user and obtain data needed to continue List<?> userData = userInteraction(request, manager.getOPEndpointUrl()); String userSelectedId = (String) userData.get(0); String userSelectedClaimedId = (String) userData.get(1); Boolean authenticatedAndApproved = (Boolean) userData.get(2); // --- process an authentication request --- response = manager.authResponse( request, userSelectedId, userSelectedClaimedId, authenticatedAndApproved.booleanValue()); if (response instanceof DirectError) { Form f = new Form(); @SuppressWarnings("unchecked") Map<String, String> m = (Map<String, String>) response.getParameterMap(); for (String key : m.keySet()) { f.add(key, m.get(key)); } return f.getWebRepresentation(); } else { // caller will need to decide which of the following to use: // option1: GET HTTP-redirect to the return_to URL // return new // StringRepresentation(response.getDestinationUrl(true)); redirectSeeOther(response.getDestinationUrl(true)); return new EmptyRepresentation(); // option2: HTML FORM Redirection // RequestDispatcher dispatcher = // getServletContext().getRequestDispatcher("formredirection.jsp"); // httpReq.setAttribute("prameterMap", // response.getParameterMap()); // httpReq.setAttribute("destinationUrl", // response.getDestinationUrl(false)); // dispatcher.forward(request, response); // return null; } } else if ("check_authentication".equals(mode)) { // --- processing a verification request --- response = manager.verify(request); log.info("OpenID : " + response.keyValueFormEncoding()); responseText = response.keyValueFormEncoding(); } else if (Method.GET.equals(getMethod())) { // Could be a discovery request sendXRDSLocation(); return new StringRepresentation("XRDS Discovery Information"); } else { // --- error response --- response = DirectError.createDirectError("Unknown request"); responseText = response.keyValueFormEncoding(); } // return the result to the user return new StringRepresentation(responseText); }