/** Makes sure concrete types are properly initialized. */ public void testParameters() { MediaType mt = MediaType.valueOf("application/atom+xml;type=entry"); assertEquals("entry", mt.getParameters().getFirstValue("type")); mt = MediaType.valueOf("multipart/x-mixed-replace; boundary=\"My boundary\""); assertEquals("\"My boundary\"", mt.getParameters().getFirstValue("boundary")); }
public void testDownload() throws Exception { final Long processId = issueProcessAndWaitForTermination(); // zip extension is not required but should be handled final String request = RESTLET_PATH + "/" + processId.longValue() + ".zip"; final MockHttpServletResponse response = getAsServletResponse(request); assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus())); assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType())); assertEquals( "attachment; filename=\"test map.zip\"", response.getHeader("Content-Disposition")); final ByteArrayInputStream responseStream = getBinaryInputStream(response); final ZipInputStream zipIn = new ZipInputStream(responseStream); Set<String> expectedFiles = new HashSet<String>(); expectedFiles.add("README.txt"); expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shp"); expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".cst"); expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".prj"); expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".dbf"); expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shx"); // TODO: change this expectation once we normalize the raster file name expectedFiles.add(RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff"); Set<String> archivedFiles = new HashSet<String>(); ZipEntry nextEntry; while ((nextEntry = zipIn.getNextEntry()) != null) { archivedFiles.add(nextEntry.getName()); } assertEquals(expectedFiles, archivedFiles); }
public void testCoverageContents() throws Exception { final Long processId = issueProcessAndWaitForTermination(); final String request = RESTLET_PATH + "/" + processId.longValue(); final MockHttpServletResponse response = getAsServletResponse(request); assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus())); assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType())); final ByteArrayInputStream responseStream = getBinaryInputStream(response); File dataDirectoryRoot = super.getTestData().getDataDirectoryRoot(); File file = new File(dataDirectoryRoot, "testCoverageContents.zip"); super.getTestData().copyTo(responseStream, file.getName()); ZipFile zipFile = new ZipFile(file); try { // TODO: change this expectation once we normalize the raster file name String rasterName = RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff"; ZipEntry nextEntry = zipFile.getEntry(rasterName); assertNotNull(nextEntry); InputStream coverageInputStream = zipFile.getInputStream(nextEntry); // Use a file, geotiffreader might not work well reading out of a plain input stream File covFile = new File(file.getParentFile(), "coverage.tiff"); IOUtils.copy(coverageInputStream, covFile); GeoTiffReader geoTiffReader = new GeoTiffReader(covFile); GridCoverage2D coverage = geoTiffReader.read(null); CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem(); assertEquals(CRS.decode("EPSG:4326", true), crs); } finally { zipFile.close(); } }
/** Testing {@link MediaType#valueOf(String)} and {@link MediaType#register(String, String)} */ public void testValueOf() { assertSame(MediaType.APPLICATION_XML, MediaType.valueOf("application/xml")); assertSame(MediaType.ALL, MediaType.valueOf("*/*")); final MediaType newType = MediaType.valueOf("application/x-restlet-test"); assertEquals("application", newType.getMainType()); assertEquals("x-restlet-test", newType.getSubType()); assertEquals("application/x-restlet-test", newType.getName()); // Should not have got registered by call to valueOf() alone assertNotSame(newType, MediaType.valueOf("application/x-restlet-test")); final MediaType registeredType = MediaType.register("application/x-restlet-test", "Restlet testcase"); assertNotSame(newType, registeredType); // didn't touch old value assertEquals("application/x-restlet-test", registeredType.getName()); assertEquals("Restlet testcase", registeredType.getDescription()); // Later valueOf calls always returns the registered type assertSame(registeredType, MediaType.valueOf("application/x-restlet-test")); assertSame(registeredType, MediaType.valueOf("application/x-restlet-test")); // Test toString() equivalence MediaType mediaType = MediaType.valueOf("application/atom+xml; name=value"); assertEquals("application/atom+xml; name=value", mediaType.toString()); assertEquals(MediaType.APPLICATION_ATOM, mediaType.getParent()); }
/** * Creates a new preference. * * @param metadata The metadata name. * @param parameters The parameters list. * @return The new preference. */ @SuppressWarnings("unchecked") protected Preference<T> createPreference(CharSequence metadata, Series<Parameter> parameters) { Preference<T> result; if (parameters == null) { result = new Preference<T>(); switch (this.type) { case TYPE_CHARACTER_SET: result.setMetadata((T) CharacterSet.valueOf(metadata.toString())); break; case TYPE_ENCODING: result.setMetadata((T) Encoding.valueOf(metadata.toString())); break; case TYPE_LANGUAGE: result.setMetadata((T) Language.valueOf(metadata.toString())); break; case TYPE_MEDIA_TYPE: result.setMetadata((T) MediaType.valueOf(metadata.toString())); break; } } else { final Series<Parameter> mediaParams = extractMediaParams(parameters); final float quality = extractQuality(parameters); result = new Preference<T>(null, quality, parameters); switch (this.type) { case TYPE_CHARACTER_SET: result.setMetadata((T) new CharacterSet(metadata.toString())); break; case TYPE_ENCODING: result.setMetadata((T) new Encoding(metadata.toString())); break; case TYPE_LANGUAGE: result.setMetadata((T) new Language(metadata.toString())); break; case TYPE_MEDIA_TYPE: result.setMetadata((T) new MediaType(metadata.toString(), mediaParams)); break; } } return result; }
@Override public void endElement(String uri, String localName, String qName) throws SAXException { if (uri.equalsIgnoreCase(Service.APP_NAMESPACE)) { if (localName.equalsIgnoreCase("service")) { this.state = IN_NONE; } else if (localName.equalsIgnoreCase("workspace")) { if (this.state == IN_WORKSPACE) { currentService.getWorkspaces().add(this.currentWorkspace); this.currentWorkspace = null; this.state = IN_SERVICE; } } else if (localName.equalsIgnoreCase("collection")) { if (this.state == IN_COLLECTION) { this.currentWorkspace.getCollections().add(this.currentCollection); this.currentCollection = null; this.state = IN_WORKSPACE; } } else if (localName.equalsIgnoreCase("accept")) { if (this.state == IN_ACCEPT) { List<MediaType> mediaTypes = null; String accept = this.contentBuffer.toString(); if ((accept != null) && (accept.length() > 0)) { String[] acceptTokens = accept.split(","); mediaTypes = new ArrayList<MediaType>(); for (String acceptToken : acceptTokens) { mediaTypes.add(MediaType.valueOf(acceptToken)); } } this.currentCollection.setAccept(mediaTypes); this.state = IN_COLLECTION; } } } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equalsIgnoreCase("title")) { if (this.state == IN_COLLECTION_TITLE) { String title = this.contentBuffer.toString(); this.currentCollection.setTitle(title); this.state = IN_COLLECTION; } else if (this.state == IN_WORKSPACE_TITLE) { String title = this.contentBuffer.toString(); this.currentWorkspace.setTitle(title); this.state = IN_WORKSPACE; } } } }
/** * 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"); } }
@Test public void testPostRdfBasic() throws Exception { // prepare: add an artifact final InferredOWLOntologyID testArtifact = this.loadTestArtifact( TestConstants.TEST_ARTIFACT_20130206, MediaType.APPLICATION_RDF_TURTLE); final ClientResource searchClientResource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SEARCH)); try { searchClientResource.addQueryParameter( PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, testArtifact.getOntologyIRI().toString()); // prepare: the test input final String[] objectUris = { "http://purl.org/podd/basic-1-20130206/object:2966", "http://purl.org/podd/basic-2-20130206/artifact:1#Demo-Genotype", "http://purl.org/podd/basic-2-20130206/artifact:1#SqueekeeMaterial", "http://purl.org/podd/ns/poddScience#WildType_NotApplicable", "http://purl.org/podd/ns/poddPlant#DeltaTporometer-63", "http://purl.org/podd/ns/poddBase#DisplayType_LongText" }; final String[] expectedLabels = { "Project#2012-0006_ Cotton Leaf Morphology", "Demo genotype", "Squeekee material", "Not Applicable", "Delta-T porometer", null }; final Model testModel = new LinkedHashModel(); for (final String s : objectUris) { testModel.add(PODD.VF.createURI(s), RDFS.LABEL, PODD.VF.createLiteral("?blank")); } final RDFFormat inputFormat = RDFFormat.RDFXML; final MediaType inputMediaType = MediaType.valueOf(inputFormat.getDefaultMIMEType()); // build input representation final ByteArrayOutputStream output = new ByteArrayOutputStream(8096); Rio.write(testModel, output, inputFormat); final Representation input = new StringRepresentation(output.toString(), inputMediaType); // invoke service final Representation results = this.doTestAuthenticatedRequest( searchClientResource, Method.POST, input, inputMediaType, Status.SUCCESS_OK, AbstractResourceImplTest.WITH_ADMIN); // verify: response final Model resultModel = this.assertRdf(results, RDFFormat.RDFXML, 5); // verify: each URI has the expected label for (int i = 0; i < objectUris.length; i++) { final String objectString = resultModel.filter(PODD.VF.createURI(objectUris[i]), RDFS.LABEL, null).objectString(); Assert.assertEquals("Not the expected label", expectedLabels[i], objectString); } } finally { this.releaseClient(searchClientResource); } }
/** * Get a media type by its MIME type name. * * @param name The MIME type name * @return The media type */ public MediaType getMediaTypeByName(String name) { return MediaType.valueOf(name); }
@Get public Representation get() { ResponsePojo rp = new ResponsePojo(); Date startTime = new Date(); cookieLookup = RESTTools.cookieLookup(cookie); // If JSON is != null, check that it is valid JSON boolean isValidJson = true; if (json != null) { try { JSON.parse(json); } catch (Exception e) { rp.setResponse( new ResponseObject( "Parsing JSON", false, "The value passed via the json parameter could not be" + " parsed as valid JSON.")); isValidJson = false; } } if (isValidJson) { if (cookieLookup == null) { // User is not logged in rp.setResponse( new ResponseObject( "Cookie Lookup", false, "Cookie session expired or never existed, please login first")); } else { // UserId which will serve as the OwnerId for transactions below that require it personId = cookieLookup; if (action.equals("saveJson")) { rp = this.shareController.saveJson(personId, id, type, title, description, json); } else if (action.equals("addBinaryGET")) { rp = new ResponsePojo( new ResponseObject( "addBinary", false, "Can only add binary in POST (do not use GET)")); } else if (action.equals("addBinaryPOST")) { rp = this.shareController.addBinary( personId, "binary", title, description, this.getRequest().getEntity().getMediaType().toString(), binaryData); } else if (action.equals("updateBinaryGET")) { rp = new ResponsePojo( new ResponseObject( "updateBinary", false, "Can only update binary in POST (do not use GET)")); } else if (action.equals("updateBinaryPOST")) { rp = this.shareController.updateBinary( personId, id, "binary", title, description, this.getRequest().getEntity().getMediaType().toString(), binaryData); } else if (action.equals("addRef")) { // Not currently supported // rp = this.shareController.addRef(personId, type, documentId, title, description); rp.setResponse(new ResponseObject("Cookie Lookup", false, "Not currently supported")); } else if (action.equals("updateRef")) { // Not currently supported // rp = this.shareController.updateRef(personId, id, type, documentId, title, // description); rp.setResponse(new ResponseObject("Cookie Lookup", false, "Not currently supported")); } else if (action.equals("removeShare")) { rp = this.shareController.removeShare(personId, shareId); } else if (action.equals("endorseShare")) { rp = this.shareController.endorseShare(personId, communityId, shareId, isEndorsed); } else if (action.equals("addCommunity")) { rp = this.shareController.addCommunity(personId, shareId, communityId, comment); } else if (action.equals("removeCommunity")) { rp = this.shareController.removeCommunity(personId, shareId, communityId); } else if (action.equals("getShare")) { rp = this.shareController.getShare(personId, shareId, returnContent); SharePojo share = (SharePojo) rp.getData(); if (null != share) { boolean bBinary = share.getType().equals("binary"); if (bBinary && returnContent) { try { ByteArrayOutputRepresentation rep = new ByteArrayOutputRepresentation(MediaType.valueOf(share.getMediaType())); rep.setOutputBytes(share.getBinaryData()); return rep; } catch (Exception ex) { rp = new ResponsePojo( new ResponseObject("get Share", false, "error converting bytes to output")); } } else if (!bBinary && jsonOnly) { try { BasicDBObject dbo = (BasicDBObject) com.mongodb.util.JSON.parse(share.getShare()); rp.setData(dbo, null); } catch (Exception e) { // Try a list instead BasicDBList dbo = (BasicDBList) com.mongodb.util.JSON.parse(share.getShare()); rp.setData(dbo, (BasePojoApiMap<BasicDBList>) null); } } } // (else error) } else if (action.equals("searchShares")) { rp = this.shareController.searchShares( personId, searchby, id, type, skip, limit, ignoreAdmin, returnContent); } } } Date endTime = new Date(); rp.getResponse().setTime(endTime.getTime() - startTime.getTime()); return new StringRepresentation(rp.toApi(), MediaType.APPLICATION_JSON); }