public void testSearchUsers() throws Exception { // now we should have two jcoders, one from the mock and one from the XML realm PlexusResource userSearchResource = this.lookup(PlexusResource.class, "UserSearchPlexusResource"); Request request = this.buildRequest(); request.getAttributes().put(UserSearchPlexusResource.USER_SOURCE_KEY, "all"); request.getAttributes().put(UserSearchPlexusResource.USER_ID_KEY, "jcoder"); List<PlexusUserResource> result = ((PlexusUserListResourceResponse) userSearchResource.get(null, request, null, null)) .getData(); // now make sure we have 2 jcoders PlexusUserResource jcoderXML = null; PlexusUserResource jcoderMock = null; for (PlexusUserResource plexusUserResource : result) { if (plexusUserResource.getUserId().equals("jcoder")) { if (plexusUserResource.getSource().endsWith(SecurityXmlUserManager.SOURCE)) { jcoderXML = plexusUserResource; } else if (plexusUserResource.getSource().endsWith(MockUserManager.SOURCE)) { jcoderMock = plexusUserResource; } else { Assert.fail( "found a jcoder with an unknown source of: " + plexusUserResource.getSource()); } } } Assert.assertNotNull("jcoderXML is null", jcoderXML); Assert.assertNotNull("jcoderMock is null", jcoderMock); }
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 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)); } } */ }
public void doGet(Request req, Response resp) throws RestletException { String taskIds = null; try { taskIds = URLDecoder.decode((String) req.getAttributes().get("taskids"), "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Exception type = " + uee.getClass().getName() + " msg = " + uee.getMessage()); throw new RestletException(uee.getMessage(), Status.SERVER_ERROR_INTERNAL); } ArrayList<GWCTaskStatus> taskList = new ArrayList<GWCTaskStatus>(); seeder.getStorageBroker().getTasks(taskIds, taskList); List<String> segments = req.getResourceRef().getSegments(); String reqAction = segments.get(segments.size() - 2); if (reqAction.equalsIgnoreCase("seedprogress")) { handleProgress(req, resp, taskList); } else if (reqAction.equalsIgnoreCase("seedcancel")) { handleCancel(req, resp, taskList); } else { String msg = "Unsupported action: " + reqAction; log.error(msg); throw new RestletException(msg, Status.CLIENT_ERROR_NOT_FOUND); } }
private Request buildRequest() { Request request = new Request(); Reference ref = new Reference("http://localhost:12345/"); request.setRootRef(ref); request.setResourceRef(new Reference(ref, "users")); return request; }
@Override public Resource findTarget(Request request, Response response) { String layer = (String) request.getAttributes().get("layer"); if (layer != null && request.getMethod() == Method.GET) { return new ListAttributesResource(getContext(), request, response, catalog); } throw new RestletException("No such layer: " + layer, Status.CLIENT_ERROR_NOT_FOUND); }
public void updateUserRoleTest() throws Exception { // first get the list of the previous users roles so we can make sure they change User jcoderXML = securitySystem.getUser("jcoder", SecurityXmlUserManager.SOURCE); User jcoderMock = securitySystem.getUser("jcoder", MockUserManager.SOURCE); List<String> jcoderXMLOriginalRoles = new ArrayList<String>(); for (RoleIdentifier role : jcoderXML.getRoles()) { jcoderXMLOriginalRoles.add(role.getRoleId()); } List<String> jcoderMockOriginalRoles = new ArrayList<String>(); for (RoleIdentifier role : jcoderMock.getRoles()) { jcoderMockOriginalRoles.add(role.getRoleId()); } // now update one... and check the other Request request = this.buildRequest(); Response response = new Response(request); request.getAttributes().put(UserToRolePlexusResource.USER_ID_KEY, "jcoder"); request.getAttributes().put(UserToRolePlexusResource.SOURCE_ID_KEY, MockUserManager.SOURCE); PlexusResource userToRoleResource = this.lookup(PlexusResource.class, "UserSearchPlexusResource"); UserToRoleResourceRequest payload = new UserToRoleResourceRequest(); payload.setData(new UserToRoleResource()); payload.getData().setUserId("jcoder"); payload.getData().setSource(MockUserManager.SOURCE); payload.getData().getRoles().add("admin"); userToRoleResource.put(null, request, response, null); // the xml user should have the original roles the mock users should only have admin. jcoderXML = securitySystem.getUser("jcoder", SecurityXmlUserManager.SOURCE); jcoderMock = securitySystem.getUser("jcoder", MockUserManager.SOURCE); List<String> jcoderXMLNewRoles = new ArrayList<String>(); for (RoleIdentifier role : jcoderXML.getRoles()) { jcoderXMLNewRoles.add(role.getRoleId()); } List<String> jcoderMockNewRoles = new ArrayList<String>(); for (RoleIdentifier role : jcoderMock.getRoles()) { jcoderMockNewRoles.add(role.getRoleId()); } Assert.assertEquals(jcoderXMLOriginalRoles, jcoderXMLNewRoles); Assert.assertEquals(1, jcoderMockNewRoles.size()); Assert.assertTrue(jcoderMockNewRoles.contains("admin")); }
/** * Format of a proper get request: <uid>(assessmentUID)</uid> * * <p>or * * <p><taxon>(taxonID)</taxon> * * <p>If the type parameter is null for the latter format, all . * * @param getEntity * @param type * @return */ private String getAssessments(Request request, String user) throws IOException { String type = (String) request.getAttributes().get("type"); Document doc = new DomRepresentation(request.getEntity()).getDocument(); StringBuilder ret = new StringBuilder("<assessments>"); NodeCollection uidNodes = new NodeCollection(doc.getElementsByTagName("uid")); if (uidNodes.size() > 0) { Map<String, List<String>> typeToIDs = new HashMap<String, List<String>>(); for (Node curNode : uidNodes) { String uid = curNode.getTextContent(); int splitIndex = uid.lastIndexOf("_", uid.lastIndexOf("_") - 1); if (splitIndex > 0) { String curType = uid.substring(splitIndex + 1); List<String> typeList = typeToIDs.get(curType); if (typeList == null) { typeList = new ArrayList<String>(); typeToIDs.put(uid.substring(splitIndex + 1), typeList); } typeList.add(uid.substring(0, splitIndex)); } else { System.out.println("Split index for UID " + uid + " is obviously s***e."); } } for (Entry<String, List<String>> curEntry : typeToIDs.entrySet()) for (String curID : curEntry.getValue()) ret.append(AssessmentIO.readAssessmentAsString(vfs, curID, curEntry.getKey(), user)); } NodeCollection taxaNodes = new NodeCollection(doc.getElementsByTagName("taxon")); if (taxaNodes.size() > 0) { for (Node curNode : taxaNodes) { String taxonID = curNode.getTextContent(); if (type == null) for (String cur : AssessmentIO.readAllAssessmentsForTaxonAsStrings(vfs, taxonID, user)) ret.append(cur); else if (type.equals(BaseAssessment.DRAFT_ASSESSMENT_STATUS)) for (String cur : AssessmentIO.readAllDraftAssessmentsAsStrings(vfs, taxonID)) ret.append(cur); else if (type.equals(BaseAssessment.PUBLISHED_ASSESSMENT_STATUS)) for (String cur : AssessmentIO.readPublishedAssessmentsForTaxonAsStrings(vfs, taxonID)) ret.append(cur); } } ret.append("</assessments>"); return ret.toString(); }
/** * Initialize the resource. * * @param request the request. */ @Override protected void initParams(final Request request) { log.debug("Initializing params for Recommendation"); openSocialId = (String) request.getAttributes().get("openSocialId"); if (request.getAttributes().containsKey("maxResults")) { try { String tempMaxResults = (String) request.getAttributes().get("maxResults"); log.debug("Retreived maxResults from querystring: " + tempMaxResults); maxResults = Integer.parseInt(tempMaxResults); } catch (Exception ex) { maxResults = 0; } } }
public void init(Request request, Response response) { RequestData data = monitor.current(); if (data == null) { // will happen in cases where the filter is not active return; } data.setCategory(Category.REST); if (request.getResourceRef() != null) { String resource = request.getResourceRef().getLastSegment(); resource = FilenameUtils.getBaseName(resource); data.getResources().add(resource); } monitor.update(); }
/** @see HttpHeaderTestService#getLanguage(javax.ws.rs.core.HttpHeaders) */ public void testLanguage() throws IOException { final List<Preference<Language>> acceptedLanguages = new ArrayList<Preference<Language>>(); acceptedLanguages.add(new Preference<Language>(Language.ENGLISH)); final ClientInfo clientInfo = new ClientInfo(); clientInfo.setAcceptedLanguages(acceptedLanguages); final Request request = new Request(Method.POST, createReference(HttpHeaderTestService.class, "language")); request.setClientInfo(clientInfo); request.setEntity(new StringRepresentation("entity", Language.ENGLISH)); final Response response = accessServer(request); assertEquals(Status.SUCCESS_OK, response.getStatus()); assertEquals("en", response.getEntity().getText()); }
public Response sendRequest(Method method, String url, Representation representation) { this.logger.debug("Method: " + method.getName() + " url: " + url); Request request = new Request(); request.setResourceRef(url); request.setMethod(method); if (!Method.GET.equals(method) && !Method.DELETE.equals(method)) { request.setEntity(representation); } request.setChallengeResponse(this.challenge); return this.restClient.handle(request); }
protected String buildUploadFailedHtmlResponse(Throwable t, Request request, Response response) { try { handleException(request, response, t); } catch (ResourceException e) { getLogger().debug("Got error while uploading artifact", t); StringBuffer resp = new StringBuffer(); resp.append("<html>"); resp.append("<body>"); resp.append("<error>" + e.getMessage() + "</error>"); resp.append("</body>"); resp.append("</html>"); String forceSuccess = request.getResourceRef().getQueryAsForm().getFirstValue("forceSuccess"); if (!"true".equals(forceSuccess)) { response.setStatus(e.getStatus()); } return resp.toString(); } // We have an error at this point, can't get here return null; }
/** * Looks up a {@link LayerInfo} or {@link LayerGroupInfo} named after the {@code <layer>} in the * requested resource {@code <layer>.kml} name * * @see org.restlet.Finder#findTarget(org.restlet.data.Request, org.restlet.data.Response) */ @Override public Resource findTarget(final Request request, Response response) { if (!Method.GET.equals(request.getMethod())) { response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); return null; } final String name = RESTUtils.getAttribute(request, "layer"); if (name == null) { throw new RestletException("No layer name specified", Status.CLIENT_ERROR_BAD_REQUEST); } final Catalog catalog = geoserver.getCatalog(); CatalogInfo layer = catalog.getLayerByName(name); MetadataMap mdmap; if (layer == null) { layer = catalog.getLayerGroupByName(name); if (layer == null) { throw new RestletException("Layer " + name + " not found", Status.CLIENT_ERROR_NOT_FOUND); } mdmap = ((LayerGroupInfo) layer).getMetadata(); } else { mdmap = ((LayerInfo) layer).getMetadata(); } Boolean enabled = mdmap.get(Properties.INDEXING_ENABLED, Boolean.class); if (enabled == null || !enabled.booleanValue()) { throw new RestletException("Layer " + name + " not found", Status.CLIENT_ERROR_NOT_FOUND); } final Context context = getContext(); return new GeoSearchLayer(context, request, response, layer, geoserver); }
@Override protected void afterHandle(Request request, Response response) { String callback = request.getResourceRef().getQueryAsForm().getFirstValue("callback"); if (callback != null) { StringBuilder stringBuilder = new StringBuilder(callback); stringBuilder.append("("); Representation representation = response.getEntity(); if (representation != null) { try { InputStream inputStream = representation.getStream(); if (inputStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[0x10000]; int length; while ((length = inputStream.read(bytes)) > 0) { out.write(bytes, 0, length); } stringBuilder.append(out.toString("UTF-8")); } } catch (IOException e) { List<String> details = new ArrayList<String>(); details.add(e.getMessage()); ServiceException serviceException = new ServiceException( new ServiceError( (Status.SERVER_ERROR_INTERNAL.getCode()), "Internal Server Error", details)); response.setEntity(serviceException); } } stringBuilder.append(")"); response.setEntity(new StringRepresentation(stringBuilder.toString(), MediaType.TEXT_PLAIN)); } }
public void writeRawData(String path, byte[] data) throws IOException { while (path.startsWith("/")) { path = path.substring(1); } Request rr = createRequest(Method.PUT, path); ByteArrayRepresentation entity = new ByteArrayRepresentation(MediaType.APPLICATION_XML, data); rr.setEntity(entity); Response response = client.handle(rr); if (!response.getStatus().isSuccess()) { throw new IOException("The response was not successful: " + response.getStatus()); } }
@Override public Resource findTarget(Request request, Response response) { if (request.getResourceRef().getLastSegment().endsWith(".ftl")) { return new FreemarkerTemplateResource(request, response, catalog); } else { return new FreemarkerTemplateListResource(getContext(), request, response, catalog); } }
public static String findIP(Request request) { Form form = (Form) request.getAttributes().get("org.restlet.http.headers"); String forwardedIP = getFirstForwardedIp(form.getFirstValue(FORWARD_HEADER)); if (forwardedIP != null) { return forwardedIP; } List<String> ipAddresses = request.getClientInfo().getAddresses(); if (ipAddresses.size() > 0) { return ipAddresses.get(0); } return null; }
public void handle(Request request, Response response) { String scriptName = (String) request.getAttributes().get("script"); if (scriptName == null) { File scriptDirectory = null; try { scriptDirectory = resourceLoader.find(scriptPath); } catch (IOException ioe) { // no, it's cool. we might have to handle a null return anyway. } if (scriptDirectory == null) throw new RestletException("No script directory", Status.CLIENT_ERROR_NOT_FOUND); StringBuilder out = new StringBuilder(); for (String script : scriptDirectory.list( new FilenameFilter() { public boolean accept(File f, String name) { return name.endsWith(".js"); } })) { out.append(script.substring(0, script.length() - 3)).append(", "); } response.setEntity(new StringRepresentation(out.toString())); } else { File script; try { script = resourceLoader.find(scriptPath, scriptName + ".js"); } catch (IOException ioe) { throw new RestletException( "Requested script [" + scriptName + "] does not exist", Status.CLIENT_ERROR_NOT_FOUND); } Context cx = Context.enter(); try { Scriptable scope = cx.initStandardObjects(); FileReader reader = new FileReader(script); Object wrappedRequest = Context.javaToJS(request, scope); Object wrappedResponse = Context.javaToJS(response, scope); Object wrappedCatalog = Context.javaToJS(catalog, scope); Object wrappedLoader = Context.javaToJS(resourceLoader, scope); ScriptableObject.putProperty(scope, "request", wrappedRequest); ScriptableObject.putProperty(scope, "response", wrappedResponse); ScriptableObject.putProperty(scope, "loader", wrappedLoader); ScriptableObject.putProperty(scope, "catalog", wrappedCatalog); cx.evaluateReader(scope, reader, script.getName(), 1, null); } catch (IOException e) { throw new RestletException( "I/O error while loading script...", Status.SERVER_ERROR_INTERNAL); } finally { Context.exit(); } } }
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; }
public TestResource(Context context, Request request, Response response) { super(context, request, response); patientId = request.getResourceRef().getQueryAsForm().getFirstValue("patientId"); // This representation has only one type of representation. getVariants().add(new Variant(MediaType.APPLICATION_JSON)); context.getClientDispatcher(); }
public void handle(Request request, Response response) { GEOSERVER_ROOT = getBaseURL(request); if (request.getMethod().equals(Method.GET)) { doGet(request, response); } else { response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } }
public PluginLogResource(Context context, Request request, Response response) { super(context, request, response); setModifiable(true); plugin = (String) request.getAttributes().get("plugin"); root = ((ManagerApplication) ManagerApplication.getCurrent()).getVMRoot(); getVariants().add(new Variant(MediaType.TEXT_XML)); }
public MailActionResource(Context context, Request request, Response response) { super(context, request, response); try { String query = request.getResourceRef().getQueryAsForm().getQueryString(); // System.out.println("query: "+query); if (checkApiCaller(query) != true) { getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return; } } catch (Exception e) { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return; } setModifiable(true); setAvailable(true); allowPut(); final Method httpMethod = request.getMethod(); Logger.getLogger(MailActionResource.class.getName()) .log(Level.INFO, "httpMethod: " + httpMethod); try { userId = request.getResourceRef().getQueryAsForm().getFirstValue("userId"); action = request.getResourceRef().getQueryAsForm().getFirstValue("action"); Logger.getLogger(MailActionResource.class.getName()).log(Level.INFO, userId); Logger.getLogger(MailActionResource.class.getName()).log(Level.INFO, action); // fromUser=request.getResourceRef().getQueryAsForm().getFirstValue("fromUser"); // // fromUserProvider=request.getResourceRef().getQueryAsForm().getFirstValue("fromUserProvider"); // toUser=request.getResourceRef().getQueryAsForm().getFirstValue("toUser"); // // toUserProvider=request.getResourceRef().getQueryAsForm().getFirstValue("toUserProvider"); // subject=request.getResourceRef().getQueryAsForm().getFirstValue("subject"); // message=request.getResourceRef().getQueryAsForm().getFirstValue("message"); } catch (Exception e) { // don't care } getVariants().add(new Variant(MediaType.APPLICATION_JSON)); }
/** * DUMMY IMPLEMENTATION, just to satisfy superclass (but why is this class expanding it at all?) * * @param request * @return * @throws NoSuchResourceStoreException * @throws ResourceException */ @Override protected ResourceStore getResourceStore(final Request request) throws NoSuchResourceStoreException, ResourceException { return getUnprotectedRepositoryRegistry() .getRepository( request .getAttributes() .get(AbstractRepositoryPlexusResource.REPOSITORY_ID_KEY) .toString()); }
/** * The default handler. It simply extracts the requested file name and gets the file's InputStream * from Nexus instance. If Nexus finds the file appropriate, the handler wraps it into InputStream * representation and ships it as "text/plain" media type, otherwise HTTP 404 is returned. * * @param fileName The file name to retrieve (as defined in the log list resource response). */ @Override @GET @ResourceMethodSignature( pathParams = {@PathParam(LogsPlexusResource.FILE_NAME_KEY)}, output = Object.class) public Object get(Context context, Request request, Response response, Variant variant) throws ResourceException { String logFile = request.getAttributes().get(FILE_NAME_KEY).toString(); Form params = request.getResourceRef().getQueryAsForm(); String fromStr = params.getFirstValue("from"); String countStr = params.getFirstValue("count"); long from = 0; long count = Long.MAX_VALUE; if (!StringUtils.isEmpty(fromStr)) { from = Long.valueOf(fromStr); } if (!StringUtils.isEmpty(countStr)) { count = Long.valueOf(countStr); } NexusStreamResponse result; try { result = logManager.getApplicationLogAsStream(logFile, from, count); } catch (IOException e) { throw new ResourceException(e); } if (result != null) { return new InputStreamRepresentation( MediaType.valueOf(result.getMimeType()), result.getInputStream()); } else { getLogger().warn("Log file not found, filename=" + logFile); throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Log file not found"); } }
protected Request createRequest(Method method, String path) { // TODO: in restlet 1.1.1 the Reference is broken, (it works great in 1.1.2, but that has other // problems) // so we need to a working solution String uri = repositoryRoot + (repositoryRoot.endsWith("/") ? "" : "/") + path; Reference reference = new Reference(uri); Request request = new Request(method, reference); ClientInfo ci = new ClientInfo(); ci.setAgent("NexusRM/1.0.0"); ci.setAcceptedMediaTypes( Collections.singletonList(new Preference<MediaType>(MediaType.APPLICATION_XML))); request.setClientInfo(ci); return request; }
public MedicationsResource(Context context, Request request, Response response) { super(context, request, response); try { String query = request.getResourceRef().getQueryAsForm().getQueryString(); // System.out.println("query: "+query); if (checkApiCaller(query) != true) { getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return; } } catch (Exception e) { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, e); return; } // This representation has only one type of representation. getVariants().add(new Variant(MediaType.APPLICATION_JSON)); String apikey = request.getResourceRef().getQueryAsForm().getFirstValue("apiKey"); if (apikey != null) { this.apiKey = apikey; } patientId = this.getParameter(request, "patientId", ""); fromDate = this.getDateParameter(request, "fromDate", "Patient", "Medications", "Begin"); toDate = this.getDateParameter(request, "toDate", "Patient", "Medications", "End"); jsonRequestString = "{getMedicationFacts:{criteria:{queryId:\"20100411011010\",\"senderId\":\"Adapter Assembly Service\",\"interactionId\":\"QUPC_IN043100UV\",\"triggerEventCode\":\"QUPC_TE043100UV0\",\"patientId\":\"" + patientId + "\",\"careProvisionCode\":\"HISTMEDLIST\",\"careRecordStartTimePeriod\":\"" + fromDate + "\",\"careRecordEndTimePeriod\":\"" + toDate + "\"}}}"; }
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; }
@Override public Resource findTarget(Request request, Response response) { if (request.getAttributes().containsKey("id")) { final Optional<GeoGIT> ggit = getGeogit(request); Preconditions.checkState(ggit.isPresent()); final String id = (String) request.getAttributes().get("id"); final ObjectId oid = ObjectId.valueOf(id); GeoGIT geogit = ggit.get(); Repository repository = geogit.getRepository(); boolean blobExists = repository.blobExists(oid); if (blobExists) { ObjectResource objectResource = new ObjectResource(oid, geogit); objectResource.init(getContext(), request, response); return objectResource; } } return super.findTarget(request, response); }