/** * Indicates if the annotated method described is compatible with the given parameters. * * @param restletMethod The Restlet method to match. * @param requestEntity Optional request entity. * @param metadataService The metadata service to use. * @param converterService The converter service to use. * @return True if the annotated method is compatible. */ public boolean isCompatible( Method restletMethod, Form queryParams, Representation requestEntity, MetadataService metadataService, org.restlet.service.ConverterService converterService) { boolean result = true; // Verify query parameters if (getQuery() != null) { Form requiredParams = new Form(getQuery()); for (Iterator<Parameter> iter = requiredParams.iterator(); iter.hasNext() && result; ) { result = queryParams.contains(iter.next()); } } // Verify HTTP method if (result) { result = getRestletMethod().equals(restletMethod); } // Verify request entity if (result) { result = isCompatibleRequestEntity(requestEntity, metadataService, converterService); } return result; }
/** Accept the representation of a mail received from a sender, and create it. */ @Override public void acceptRepresentation(Representation entity) throws ResourceException { final Form form = new Form(entity); final Mail mail = new Mail(); mail.setStatus(Mail.STATUS_RECEIVED); // Look for an existing contact or create it. final String senderAddress = form.getFirstValue("senderAddress"); final String senderName = form.getFirstValue("senderName"); Contact contact = getObjectsFacade().lookForContact(senderAddress, this.mailbox); if (contact == null) { contact = new Contact(); contact.setMailAddress(senderAddress); contact.setName(senderName); } mail.setSender(contact); mail.setMessage(form.getFirstValue("message")); mail.setSubject(form.getFirstValue("subject")); // form2.add("sendingDate", mail.getSendingDate().toString()); final Series<Parameter> recipients = form.subList("recipient"); for (final Parameter recipient : recipients) { contact = getObjectsFacade().lookForContact(recipient.getValue(), this.mailbox); if (contact == null) { contact = new Contact(); final String[] recipientValues = recipient.getValue().split("\\$"); contact.setMailAddress(recipientValues[0]); contact.setName(recipientValues[1]); } mail.getRecipients().add(contact); } getObjectsFacade().createMail(this.mailbox, mail); }
@Override protected int beforeHandle(Request request, Response response) { Cookie cookie = request.getCookies().getFirst("Credentials"); if (cookie != null) { // Extract the challenge response from the cookie String[] credentials = cookie.getValue().split("="); if (credentials.length == 2) { String identifier = credentials[0]; String secret = credentials[1]; request.setChallengeResponse( new ChallengeResponse(ChallengeScheme.HTTP_COOKIE, identifier, secret)); } } else if (Method.POST.equals(request.getMethod()) && request.getResourceRef().getQueryAsForm().getFirst("login") != null) { // Intercepting a login form Form credentials = new Form(request.getEntity()); String identifier = credentials.getFirstValue("identifier"); String secret = credentials.getFirstValue("secret"); request.setChallengeResponse( new ChallengeResponse(ChallengeScheme.HTTP_COOKIE, identifier, secret)); // Continue call processing to return the target representation if // authentication is successful or a new login page request.setMethod(Method.GET); } return super.beforeHandle(request, response); }
public PointTileParameters(Path path, Form params) { super(path, params, 0.6); final String diameterString = params.getFirstValue("point_diameter"); double _diameter = 12.0; if (diameterString != null) try { _diameter = Double.parseDouble(diameterString); } catch (final NumberFormatException e) { } pointDiameter = _diameter; final String noFillString = params.getFirstValue("no_fill"); boolean _noFill = false; if (noFillString != null) _noFill = Boolean.parseBoolean(noFillString); noFill = _noFill; final String noColorString = params.getFirstValue("no_color"); boolean _noColor = false; if (noColorString != null) _noColor = Boolean.parseBoolean(noColorString); noColor = _noColor; String _highlight = params.getFirstValue("highlight"); if (Strings.isNullOrEmpty(_highlight) || "undefined".equals(_highlight)) _highlight = null; highlight = _highlight; }
@Override public void storeRepresentation(Representation entity) throws ResourceException { if (checkAuthorization() == 1) { if (entity.getMediaType().equals(MediaType.APPLICATION_WWW_FORM, true)) { // Parse the entity as a web form final Form form = new Form(entity); // If the bookmark doesn't exist, create it if (this.bookmark == null) { this.bookmark = new Bookmark(getUser(), this.uri); getUser().getBookmarks().add(this.bookmark); getResponse().setStatus(Status.SUCCESS_CREATED); } else { getResponse().setStatus(Status.SUCCESS_NO_CONTENT); } // Update the bookmark this.bookmark.setShortDescription(form.getFirstValue("bookmark[short_description]")); this.bookmark.setLongDescription(form.getFirstValue("bookmark[long_description]")); this.bookmark.setDateTime(new Date()); this.bookmark.setRestrict(new Boolean(form.getFirstValue("bookmark[restrict]"))); // Commit the changes getContainer().store(this.bookmark); getContainer().store(getUser()); getContainer().commit(); } } else { // Intentionnally hide the bookmark existence getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } }
public void acceptRepresentation(final Representation entity) throws ResourceException { final Form form = getRequest().getEntityAsForm(); final String serviceUrl = form.getFirstValue("serviceTicketUrl"); try { final Assertion authentication = this.centralAuthenticationService.validateServiceTicket( serviceTicketId, new SimpleWebApplicationServiceImpl(serviceUrl, this.httpClient)); if (authentication.getChainedAuthentications().size() > 0) { // Iterate through each of the ChainedAuthentications and put them into the JSonArray JSONArray jsonResult = new JSONArray(); for (Authentication auth : authentication.getChainedAuthentications()) { // Create the principle JSONObject principle = createJSONPrinciple(auth); JSONObject jsonAuth = new JSONObject(); jsonAuth.put("authenticated_date", auth.getAuthenticatedDate()); jsonAuth.put("attributes", principle); jsonResult.add(jsonAuth); } getResponse().setEntity(jsonResult.toJSONString(), MediaType.TEXT_PLAIN); } else { getResponse() .setEntity( java.lang.String.format("\"{\"authenticated\":\"false\"}\""), MediaType.TEXT_PLAIN); } } catch (final TicketException e) { log.error(e.getMessage(), e); getResponse() .setStatus(Status.CLIENT_ERROR_NOT_FOUND, "TicketGrantingTicket could not be found."); } catch (final Exception e) { log.error(e.getMessage(), e); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage()); } }
/** * Handle HTTP GET method / Json * * @return a JSON list of contacts. */ @Get("json") public Representation toJSON() { // System.out.println("Request Original Ref " + getOriginalRef()); // System.out.println("Request Entity " + getRequest().getEntityAsText() // + // " entity mediaType " + getRequest().getEntity().getMediaType()); try { JSONArray jcontacts = new JSONArray(); Reference ref = getRequest().getResourceRef(); final String baseURL = ref.getHierarchicalPart(); Form formQuery = ref.getQueryAsForm(); Iterator<Contact> it = getSortedContacts(formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME)).iterator(); while (it.hasNext()) { Contact contact = it.next(); JSONObject jcontact = new JSONObject(); jcontact.put(ID, String.format("%s", contact.getId())); jcontact.put(URL, String.format("%s/%s", baseURL, contact.getId())); jcontact.put(FIRST_NAME, contact.getFirstName()); jcontact.put(LAST_NAME, contact.getLastName()); jcontacts.put(jcontact); } JSONObject contacts = new JSONObject(); contacts.put(CONTACTS, jcontacts); return new JsonRepresentation(contacts); } catch (Exception e) { setStatus(Status.SERVER_ERROR_INTERNAL); return null; } }
@Override @SuppressWarnings({"rawtypes", "unchecked"}) @Post public Representation post(Representation entity) { Form form = new Form(entity); String operation = null; int start = 0; int limit = 50; try { operation = URLDecoder.decode(form.getQueryString(), "utf-8"); operation = new String(operation.getBytes("iso-8859-1"), "utf-8"); JSONObject json = JSONObject.fromObject(operation); start = json.containsKey("start") == false ? start : Integer.parseInt(json.getString("start")); limit = json.containsKey("limit") == false ? limit : Integer.parseInt(json.getString("limit")); } catch (Exception e) { // e.printStackTrace(); } List<Role> list = service.getAllRole(start, limit); Page page = new Page(list); page.setStart(start); page.setPageSize(limit); int totalCount = service.getCountRole(); page.setTotalCount(totalCount); return new JsonRepresentation(JSONObject.fromObject(page)); }
@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(); }
@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 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()); }
public Handler(Query query, Form form) throws ResourceException { this.query = query; this.queryString = form.getQueryString(); for (QueryParameter p : query.getParameters()) { String name = p.getName(); String svalue = form.getFirstValue(name, true); switch (p.getType()) { case DATE: parameters.put(p, readParameterValue(Date.class, p, svalue)); break; case NUMBER: parameters.put(p, readParameterValue(BigDecimal.class, p, svalue)); break; case STRING: parameters.put(p, readParameterValue(String.class, p, svalue)); break; case CLOB: case BLOB: throw new ClientErrorException( Status.CLIENT_ERROR_BAD_REQUEST, String.format("LOBs are not supported as parameters: %s", name)); } } if (log.isDebugEnabled()) { for (QueryParameter qp : parameters.keySet()) { log.debug(qp.toString(parameters.get(qp))); } } }
/** * Add Mixin definition. * * @param representation * @return added mixin definition and status */ @Put public String putOCCIRequest() { // set occi version info getServerInfo().setAgent(OcciConfig.getInstance().config.getString("occi.version")); LOGGER.debug("Analyzing header information"); StringBuffer buffer = new StringBuffer(); Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers"); LOGGER.info("Request header: " + requestHeaders); String categoryCase = OcciCheck.checkCaseSensitivity(requestHeaders.toString()).get("category"); String[] header; // if there is no category in header, its a bad request if (requestHeaders.getFirstValue(categoryCase) != null) { header = requestHeaders.getFirstValue(categoryCase).split(";"); } else { getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, buffer.toString()); return " "; } String scheme = ""; for (int i = 0; i < header.length; i++) { header[i] = header[i].trim(); if (header[i].contains("scheme=")) { if (header[i].contains("\"")) { scheme = header[i].substring(8, header[i].length() - 1); } else { scheme = header[i].substring(7, header[i].length()); } LOGGER.info("scheme: " + scheme); } } Set<Mixin> related = new HashSet<Mixin>(); try { // iterate through all mixins to find the related for (Mixin mixin : Mixin.getMixins()) { if (mixin.getScheme().toString() == requestHeaders.getFirstValue("rel")) { related.add(mixin); } } String term = header[0]; String title = header[0]; LOGGER.debug("term: " + term); LOGGER.debug("title: " + title); // create new mixin instance new Mixin(related, term, title, scheme, null); LOGGER.debug("Created mixin"); } catch (Exception e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE, buffer.toString()); return "Exception caught " + e.getMessage(); } // access the request headers and get the Accept attribute Representation representation = OcciCheck.checkContentType(requestHeaders, buffer.append(" "), getResponse()); getResponse().setEntity(representation); // getResponse().setStatus(Status.SUCCESS_OK); return " "; }
protected Model getPom(Variant variant, Request request, Response response) throws ResourceException { Form form = request.getResourceRef().getQueryAsForm(); // TODO: enable only one section retrieval of POM, ie. only mailing lists, or team members String groupId = form.getFirstValue("g"); String artifactId = form.getFirstValue("a"); String version = form.getFirstValue("v"); String repositoryId = form.getFirstValue("r"); if (groupId == null || artifactId == null || version == null || repositoryId == null) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST); } ArtifactStoreRequest gavRequest = getResourceStoreRequest( request, false, repositoryId, groupId, artifactId, version, null, null, "pom"); try { MavenRepository mavenRepository = getMavenRepository(repositoryId); ArtifactStoreHelper helper = mavenRepository.getArtifactStoreHelper(); InputStream pomContent = null; InputStreamReader ir = null; Model pom = null; try { StorageFileItem file = helper.retrieveArtifactPom(gavRequest); pomContent = file.getInputStream(); MavenXpp3Reader reader = new MavenXpp3Reader(); ir = new InputStreamReader(pomContent); pom = reader.read(ir); } finally { IOUtil.close(pomContent); IOUtil.close(ir); } return pom; } catch (Exception e) { handleException(request, response, e); } return null; }
@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)); }
@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; }
/** Update the underlying mailbox according to the given representation. */ @Override public void storeRepresentation(Representation entity) throws ResourceException { final Form form = new Form(entity); this.mailbox.setNickname(form.getFirstValue("nickname")); this.mailbox.setSenderName(form.getFirstValue("senderName")); getObjectsFacade().updateMailbox(this.mailbox); getResponse().redirectSeeOther(getRequest().getResourceRef()); }
public void acceptRepresentation(Representation representation) throws ResourceException { // Allow PUT to be tunnelled over POST (unless overridden by a subclass) Form f = getRequest().getResourceRef().getQueryAsForm(); if ("put".equalsIgnoreCase(f.getFirstValue("_method", "NOT-PUT"))) { storeRepresentation(representation); return; } throw new ResourceException(Status.SERVER_ERROR_INTERNAL); }
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()); }
/** * Returns the canonicalized resource name. * * @param resourceRef The resource reference. * @return The canonicalized resource name. */ private static String getCanonicalizedResourceName(Reference resourceRef) { Form form = resourceRef.getQueryAsForm(); Parameter param = form.getFirst("comp", true); if (param != null) { StringBuilder sb = new StringBuilder(resourceRef.getPath()); return sb.append("?").append("comp=").append(param.getValue()).toString(); } return resourceRef.getPath(); }
@Put public Representation editData(Representation entity) { Form form = new Form(entity); String password = form.getFirstValue("old_password"); if (password == null) { return editSimpleData(form); } else { return editPasswordData(form); } }
private boolean isAllTasks(Request request) { Form form = request.getResourceRef().getQueryAsForm(); if (form != null) { String result = form.getFirstValue("allTasks"); if (result != null) { return result.equalsIgnoreCase("true"); } } return false; }
@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"); }
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 } }
/** * Handle HTTP GET Metod / xml * * @return an XML list of contacts. */ @Get("xml") public Representation toXML() { // System.out.println("Request Original Ref " + getOriginalRef()); // System.out.println("Request Entity " + getRequest().getEntityAsText() // + // " entity mediaType " + getRequest().getEntity().getMediaType()); Reference ref = getRequest().getResourceRef(); final String baseURL = ref.getHierarchicalPart(); Form formQuery = ref.getQueryAsForm(); try { DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML); Document d = representation.getDocument(); Element elContacts = d.createElement(CONTACTS); d.appendChild(elContacts); Iterator<Contact> it = getSortedContacts(formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME)).iterator(); while (it.hasNext()) { Contact contact = it.next(); Element el = d.createElement(CONTACT); Element id = d.createElement(ID); id.appendChild(d.createTextNode(String.format("%s", contact.getId()))); el.appendChild(id); Element firstname = d.createElement(FIRST_NAME); firstname.appendChild(d.createTextNode(contact.getFirstName())); el.appendChild(firstname); Element lastname = d.createElement(LAST_NAME); lastname.appendChild(d.createTextNode(contact.getLastName())); el.appendChild(lastname); Element url = d.createElement(URL); url.appendChild(d.createTextNode(String.format("%s/%s", baseURL, contact.getId()))); el.appendChild(url); elContacts.appendChild(el); } d.normalizeDocument(); return representation; } catch (Exception e) { setStatus(Status.SERVER_ERROR_INTERNAL); return null; } }
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); }
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 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); }
private void setPostProcessingScript() throws ValidationException { Form form = getForm(); DeploymentModule module = castToModule(); Set<String> formitems = getForm().getNames(); // Look for the post-processing entry for (String item : formitems.toArray(new String[0])) { if (item.equals("post-processing")) { ModuleParameter parameter = new ModuleParameter(item, form.getFirstValue(item), "Post-Processing script"); module.setParameter(parameter); } } }