@Override public void handle(Request request, Response response) { String dbName = (String) request.getAttributes().get("dbname"); String collection = (String) request.getAttributes().get("collection"); if (request.getMethod() == Method.POST) { try { String query = request.getEntityAsText(); System.out.println(query); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; Map<String, Object> map = null; try { map = om.readValue(query, typeRef); } catch (Exception e) { Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e); return; } ObjectMapper om = new ObjectMapper(); String r = null; try { r = om.writeValueAsString(map); } catch (IOException e) { e.printStackTrace(); } storageInstance.insert(dbName, collection, (Map<String, Object>) map); response.setEntity(r, MediaType.APPLICATION_JSON); } catch (StorageException e) { Logger.stderr(INSERTING_ERROR_MESSAGE + e); } } }
@Override protected int doHandle(Request request, Response response) { super.doHandle(request, response); if (response.getStatus().isSuccess() && request.getMethod().equals(Method.GET)) { boolean isHtml = false; for (Preference<MediaType> mt : request.getClientInfo().getAcceptedMediaTypes()) { if (mt.getMetadata().includes(MediaType.APPLICATION_XHTML) || mt.getMetadata().includes(MediaType.TEXT_HTML)) { isHtml = true; break; } } if (isHtml) { try { response.setEntity(toHtml(request, response)); } catch (SlipStreamException e) { // ok it failed generating html... do we care? } } } return CONTINUE; }
@Override public void handle(Request request, Response response) { String dbName = (String) request.getAttributes().get("dbname"); String collection = (String) request.getAttributes().get("collection"); if (request.getMethod() == Method.POST) { try { String query = request.getEntityAsText(); System.out.println(query); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; Map<String, Object> map = null; try { map = om.readValue(query, typeRef); } catch (Exception e) { Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e); return; } storageInstance.dropIndex(dbName, collection, map); response.setEntity(query, MediaType.APPLICATION_JSON); } catch (StorageException e) { Logger.stderr(DROP_INDEX_ERROR_MESSAGE + e); } } }
/** * Allows filtering before its handling by the target Restlet. By default it parses the template * variable, adjust the base reference, then extracts the attributes from form parameters (query, * cookies, entity) and finally tries to validate the variables as indicated by the {@link * #validate(String, boolean, String)} method. * * @param request The request to filter. * @param response The response to filter. * @return The {@link Filter#CONTINUE} status. */ @Override protected int beforeHandle(Request request, Response response) { if (this.validations != null) { for (ValidateInfo validate : getValidations()) { if (validate.required && !request.getAttributes().containsKey(validate.attribute)) { response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to find the \"" + validate.attribute + "\" attribute in the request. Please check your request."); } else if (validate.format != null) { Object value = request.getAttributes().get(validate.attribute); if ((value != null) && !Pattern.matches(validate.format, value.toString())) { response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Unable to validate the value of the \"" + validate.attribute + "\" attribute. The expected format is: " + validate.format + " (Java Regex). Please check your request."); } } } } return CONTINUE; }
public String authenticate(Request request, Response response) { if (!request.getClientInfo().isAuthenticated()) { authenticator.challenge(response, false); return null; } return request.getClientInfo().getUser().getIdentifier(); }
/** 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()); }
@Override protected int beforeHandle(Request request, Response response) { if (Method.OPTIONS.equals(request.getMethod())) { Series<Header> requestHeaders = (Series<Header>) request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); String origin = requestHeaders.getFirstValue("Origin", false, "*"); String rh = requestHeaders.getFirstValue("Access-Control-Request-Headers", false, "*"); Series<Header> responseHeaders = (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); if (responseHeaders == null) { responseHeaders = new Series<Header>(Header.class); } responseHeaders.add("Access-Control-Allow-Origin", origin); responseHeaders.set("Access-Control-Expose-Headers", "Authorization, Link"); responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); responseHeaders.add("Access-Control-Allow-Headers", rh); responseHeaders.add("Access-Control-Allow-Credentials", "true"); responseHeaders.add("Access-Control-Max-Age", "60"); response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders); response.setEntity(new EmptyRepresentation()); return SKIP; } return super.beforeHandle(request, response); }
/** * Tests partial Get requests. * * @throws IOException * @throws NoSuchAlgorithmException */ @Test public void testGet() throws IOException, NoSuchAlgorithmException { Client client = new Client(Protocol.HTTP); // Test partial Get. Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/"); StringRepresentation rep = new StringRepresentation("0123456789"); try { DigesterRepresentation digester = new DigesterRepresentation(rep); // Such representation computes the digest while // consuming the wrapped representation. digester.exhaust(); // Set the digest with the computed one digester.setDigest(digester.computeDigest()); request.setEntity(digester); Response response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); digester = new DigesterRepresentation(response.getEntity()); digester.exhaust(); assertTrue(digester.checkDigest()); client.stop(); } catch (Exception e) { fail(e.getMessage()); } }
/** Tests method getting/setting. */ public void testMethod() throws Exception { final Request request = getRequest(); request.setMethod(Method.GET); assertEquals(Method.GET, request.getMethod()); request.setMethod(Method.POST); assertEquals(Method.POST, request.getMethod()); }
/** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String propertyFilePath = args.length > 0 ? args[0] : "jeevlet.properties"; // Get configuration int listenPort = Integer.parseInt(ConfigUtils.getProps(propertyFilePath).getProperty(Config.LISTEN_PORT)); String hostDomain = ConfigUtils.getProps(propertyFilePath).getProperty(Config.HOST_DOMAIN); // Prepare the request String url = "http://" + hostDomain + ":" + listenPort + "/"; Request request = new Request(Method.GET, url); request.setEntity(Config.STOP_GEONETWORK, MediaType.TEXT_PLAIN); // Handle it using an HTTP client connector Client client = new Client(Protocol.HTTP); try { client.start(); Response response = client.handle(request); } catch (Exception e) { System.err.println("ERROR: Not running!"); e.printStackTrace(); } finally { client.stop(); System.out.println("GeoNetwork shutdown ..."); System.exit(0); } }
@Before public void setUp() throws Exception { contactsRepository = ContactsRepository.getInstance(); contactsRepository.setDbService(dbService); attributes = new ConcurrentHashMap<String, Object>(); Subject subjectUnderTest = Mockito.mock(Subject.class); setSubject(subjectUnderTest); request = Mockito.mock(Request.class); Mockito.when(request.getClientInfo()).thenReturn(new ClientInfo()); Mockito.when(request.getAttributes()).thenReturn(attributes); Reference targetRef = Mockito.mock(Reference.class); Reference resourceRef = Mockito.mock(Reference.class); Mockito.when(request.getResourceRef()).thenReturn(resourceRef); Mockito.when(resourceRef.getTargetRef()).thenReturn(targetRef); response = new Response(request); ValidatorService validatorService = Mockito.mock(ValidatorService.class); Validator validator = Mockito.mock(Validator.class); Mockito.when(validatorService.getValidator()).thenReturn(validator); Mockito.when(clipboardApplication.getValidatorService()).thenReturn(validatorService); RouteBuilder routeBuilder = Mockito.mock(RouteBuilder.class); Mockito.when(clipboardApplication.getRouteBuilders(Mockito.any())) .thenReturn(Arrays.asList(routeBuilder)); }
/* * POST request to webServiceURL/version/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber} */ @Post("json") public final void registerDeviceRequest(final Representation entity) { Request request = getRequest(); Map<String, Object> requestAttributes = request.getAttributes(); String deviceLibraryIdentifier = (String) requestAttributes.get("deviceLibraryIdentifier"); String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier"); String serialNumber = (String) requestAttributes.get("serialNumber"); String authString = request.getChallengeResponse().getRawValue(); Status responseStatus; try { String jsonPushToken = entity.getText(); PKPushToken pkPushToken = jsonObjectMapper.readValue(jsonPushToken, PKPushToken.class); LOGGER.debug("registerDeviceRequest - deviceLibraryIdentifier: {}", deviceLibraryIdentifier); LOGGER.debug("registerDeviceRequest - passTypeIdentifier: {}", passTypeIdentifier); LOGGER.debug("registerDeviceRequest - serialNumber: {}", serialNumber); LOGGER.debug("registerDeviceRequest - authString: {}", authString); LOGGER.debug("registerDeviceRequest - jsonPushToken: {}", jsonPushToken); LOGGER.debug("registerDeviceRequest - pkPushToken: {}", pkPushToken); responseStatus = handleRegisterDeviceRequest( deviceLibraryIdentifier, passTypeIdentifier, serialNumber, authString, pkPushToken); } catch (PKAuthTokenNotValidException e) { responseStatus = Status.CLIENT_ERROR_UNAUTHORIZED; } catch (IOException e) { responseStatus = Status.SERVER_ERROR_INTERNAL; } setStatusIntoResponse(responseStatus, getResponse()); }
/* * DELETE request to webServiceURL/version/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber} */ @Delete("json") public final void deleteDeviceRegistrationRequest(final Representation entity) { Request request = getRequest(); Map<String, Object> requestAttributes = request.getAttributes(); String deviceLibraryIdentifier = (String) requestAttributes.get("deviceLibraryIdentifier"); String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier"); String serialNumber = (String) requestAttributes.get("serialNumber"); ChallengeResponse authString = request.getChallengeResponse(); LOGGER.debug( "deleteDeviceRegistrationRequest - deviceLibraryIdentifier: {}", deviceLibraryIdentifier); LOGGER.debug("deleteDeviceRegistrationRequest - passTypeIdentifier: {}", passTypeIdentifier); LOGGER.debug("deleteDeviceRegistrationRequest - serialNumber: {}", serialNumber); LOGGER.debug("deleteDeviceRegistrationRequest - authString: {}", authString); Status responseStatus; try { responseStatus = handleUnregisterDeviceRequest( deviceLibraryIdentifier, passTypeIdentifier, serialNumber, authString); } catch (PKAuthTokenNotValidException e) { responseStatus = Status.CLIENT_ERROR_UNAUTHORIZED; } setStatusIntoResponse(responseStatus, getResponse()); }
/** * Tests conditional ranges requests. * * @throws Exception */ public void testConditionalRanges() throws Exception { Client client = new Client(Protocol.HTTP); // Test partial Get. Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet"); Response response = client.handle(request); Tag entityTag = response.getEntity().getTag(); request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX))); request.getConditions().setRangeTag(entityTag); response = client.handle(request); assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("234567890", response.getEntity().getText()); assertEquals(10, response.getEntity().getSize()); assertEquals(9, response.getEntity().getAvailableSize()); assertEquals(1, response.getEntity().getRange().getIndex()); assertEquals(9, response.getEntity().getRange().getSize()); entityTag = new Tag(entityTag.getName() + "-test"); request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX))); request.getConditions().setRangeTag(entityTag); response = client.handle(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); client.stop(); }
/** * Handles a call for a local entity. By default, only GET and HEAD methods are implemented. * * @param request The request to handle. * @param response The response to update. * @param decodedPath The URL decoded entity path. */ @Override protected void handleLocal(Request request, Response response, String decodedPath) { int spi = decodedPath.indexOf("!/"); String fileUri; String entryName; if (spi != -1) { fileUri = decodedPath.substring(0, spi); entryName = decodedPath.substring(spi + 2); } else { fileUri = decodedPath; entryName = ""; } LocalReference fileRef = new LocalReference(fileUri); if (Protocol.FILE.equals(fileRef.getSchemeProtocol())) { final File file = fileRef.getFile(); if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) { handleGet(request, response, file, entryName, getMetadataService()); } else if (Method.PUT.equals(request.getMethod())) { handlePut(request, response, file, entryName); } else { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); response.getAllowedMethods().add(Method.GET); response.getAllowedMethods().add(Method.HEAD); response.getAllowedMethods().add(Method.PUT); } } else { response.setStatus(Status.SERVER_ERROR_NOT_IMPLEMENTED, "Only works on local files."); } }
/* * GET request to webServiceURL/version/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}?passesUpdatedSince=tag */ @Get("json") public final Representation getSerialNumbersForPasses(final Representation entity) { Request request = getRequest(); Map<String, Object> requestAttributes = request.getAttributes(); String deviceLibraryIdentifier = (String) requestAttributes.get("deviceLibraryIdentifier"); String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier"); String passesUpdatedSince = (String) requestAttributes.get("passesUpdatedSince"); LOGGER.debug( "getSerialNumbersForPasses - deviceLibraryIdentifier: {}", deviceLibraryIdentifier); LOGGER.debug("getSerialNumbersForPasses - passTypeIdentifier: {}", passTypeIdentifier); LOGGER.debug("getSerialNumbersForPasses - passesUpdatedSince: {}", passesUpdatedSince); PKSerialNumbersOfPassesForDeviceResponse serialNumbersOfPassesForDevice = getSerialNumberOfPassesForDevice( deviceLibraryIdentifier, passTypeIdentifier, passesUpdatedSince); if (serialNumbersOfPassesForDevice == null || serialNumbersOfPassesForDevice.getSerialNumbers() == null) { setStatusIntoResponse(Status.SUCCESS_NO_CONTENT, getResponse()); return null; } String responseJSONString; try { responseJSONString = jsonObjectMapper.writeValueAsString(serialNumbersOfPassesForDevice); return new StringRepresentation(responseJSONString, MediaType.APPLICATION_JSON); } catch (Exception e) { LOGGER.error("Error when parsing response to JSON:", e); } setStatusIntoResponse(Status.SERVER_ERROR_INTERNAL, getResponse()); return null; }
public void testCookies() throws IOException { final Request request = createGetRequest("cookies/cookieName"); request.getCookies().add(new Cookie("cookieName", "cookie-value")); final Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("cookieName=cookie-value", response.getEntity().getText()); }
@Override protected IQueryRetrieval<IStructureRecord> createQuery( Context context, Request request, Response response) throws ResourceException { Form form = getParams(); setTemplate(createTemplate(form)); setGroupProperties(context, request, response); STRUCTURE_RELATION relation = null; try { Object cmp = request.getAttributes().get(compositionType); relation = STRUCTURE_RELATION.valueOf(cmp.toString().toUpperCase()); } catch (Exception x) { } Object key = request.getAttributes().get(SubstanceResource.idsubstance); if (key == null) return new ReadSubstanceRelation(relation, null); try { return new ReadSubstanceRelation( relation, new SubstanceRecord(Integer.parseInt(key.toString()))); } catch (Exception x) { int len = key.toString().trim().length(); if ((len > 40) && (len <= 45)) { return new ReadSubstanceRelation(relation, new SubstanceRecord(key.toString())); } throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST); } }
/** * Returns the list of identifiers for the mails in the inbox * * @return The list of identifiers. * @throws ResourceException */ protected List<String> getMailIdentifiers() throws ResourceException { final List<String> result = new ArrayList<String>(); // 1 - Get to mailbox content final Request request = new Request(Method.GET, getMailboxUri()); if (getMailboxChallengeScheme() != null) { final ChallengeResponse challengeResponse = new ChallengeResponse( getMailboxChallengeScheme(), getMailboxLogin(), getMailboxPassword()); request.setChallengeResponse(challengeResponse); } final Response response = getContext().getClientDispatcher().handle(request); if (!response.getStatus().isSuccess()) { throw new ResourceException(response.getStatus(), "Cannot get the mail iddentifiers."); } // 2 - Parse the list of mails if (response.isEntityAvailable()) { final DomRepresentation rep = new DomRepresentation(response.getEntity()); for (final Node node : rep.getNodes("/emails/email/@href")) { final String href = node.getNodeValue(); if (href.startsWith("/")) { result.add(href.substring(1)); } else { result.add(href); } } } return result; }
public Response deleteJson(Reference reference, Representation representation) throws IOException { Request deleteRequest = createJsonRequest(reference, representation); deleteRequest.setMethod(Method.DELETE); return sendRequest(deleteRequest); }
/** * Creates an uniform call. * * @param jdbcURI The database's JDBC URI (ex: jdbc:mysql://[hostname]/[database]). * @param request The request to send (valid XML request). */ public static Request create(String jdbcURI, Representation request) { Request result = new Request(); result.getClientInfo().setAgent(Engine.VERSION_HEADER); result.setMethod(Method.POST); result.setResourceRef(jdbcURI); result.setEntity(request); return result; }
/** * Allows filtering before its handling by the target Restlet. Does nothing by default. * * @param request The request to filter. * @param response The response to filter. * @return The continuation status. */ @Override public int beforeHandle(Request request, Response response) { // Check if encoding of the request entity is needed if (isEncodingRequest() && canEncode(request.getEntity())) { request.setEntity(encode(request.getClientInfo(), request.getEntity())); } return CONTINUE; }
private Request createXmlRequest(Reference reference, Representation representation) { Request xmlRequest = createRequest(reference, representation); xmlRequest .getClientInfo() .getAcceptedMediaTypes() .add(new Preference<MediaType>(MediaType.APPLICATION_XML)); return xmlRequest; }
private Request createJsonRequest(Reference reference, Representation representation) { Request jsonRequest = createRequest(reference, representation); jsonRequest .getClientInfo() .getAcceptedMediaTypes() .add(new Preference<MediaType>(MediaType.APPLICATION_JSON)); return jsonRequest; }
/** * Handles a GET call. * * @param request The request to answer. * @param response The response to update. * @param file The Zip archive file. * @param entryName The Zip archive entry name. * @param metadataService The metadata service. */ protected void handleGet( Request request, Response response, File file, String entryName, final MetadataService metadataService) { if (!file.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { ZipFile zipFile; try { zipFile = new ZipFile(file); } catch (Exception e) { response.setStatus(Status.SERVER_ERROR_INTERNAL, e); return; } Entity entity = new ZipEntryEntity(zipFile, entryName, metadataService); if (!entity.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { final Representation output; if (entity.isDirectory()) { // Return the directory listing final Collection<Entity> children = entity.getChildren(); final ReferenceList rl = new ReferenceList(children.size()); String fileUri = LocalReference.createFileReference(file).toString(); String scheme = request.getResourceRef().getScheme(); String baseUri = scheme + ":" + fileUri + "!/"; for (final Entity entry : children) { rl.add(baseUri + entry.getName()); } output = rl.getTextRepresentation(); try { zipFile.close(); } catch (IOException e) { // Do something ??? } } else { // Return the file content output = entity.getRepresentation(metadataService.getDefaultMediaType(), getTimeToLive()); output.setLocationRef(request.getResourceRef()); Entity.updateMetadata(entity.getName(), output, true, getMetadataService()); } response.setStatus(Status.SUCCESS_OK); response.setEntity(output); } } }
protected AccessToken getAuthorisationApiToken() throws ServerException { Request req = getRequest(); ChallengeResponse challengeResponse = req.getChallengeResponse(); try { return oauth2TokenStore.readAccessToken( requestFactory.create(req), challengeResponse.getRawValue()); } catch (InvalidGrantException e) { throw new ServerException("Unable to verify client identity."); } }
@Override protected void addHeaders(Series<Header> headers) { Request request = getMessage().getRequest(); addGeneralHeaders(headers); addEntityHeaders(request.getEntity(), headers); // NOTE: This must stay at the end because the AWS challenge // scheme requires access to all HTTP headers addRequestHeaders(headers); }
public void handle(Request request, Response response) { if (request.getProtocol().equals(Protocol.HTTP)) { List<Protocol> protocols = Arrays.asList(Protocol.HTTP); String helperClass = HttpClientHelper.class.getName(); Client client = new Client(null, protocols, helperClass); client.handle(request, response); } else { new Client(request.getProtocol()).handle(request, response); } };
/** Tests resource reference getting/setting. */ public void testResourceRef() throws Exception { final Request request = getRequest(); String uri = "http://www.restlet.org/"; Reference reference = getReference(uri); request.setResourceRef(uri); assertEquals(reference, request.getResourceRef()); uri = "http://www.restlet.org/something"; reference = getReference(uri); request.setResourceRef(reference); assertEquals(reference, request.getResourceRef()); }
@Override protected void writeStartLine() throws IOException { Request request = getMessage().getRequest(); getLineBuilder().append(request.getMethod().getName()); getLineBuilder().append(' '); getLineBuilder() .append(ReferenceUtils.format(request.getResourceRef(), getHelper().isProxying(), request)); getLineBuilder().append(' '); getLineBuilder().append(getVersion(request)); getLineBuilder().append("\r\n"); }