/** 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")); }
/** * Makes sure that a {@link MediaType} instance initialized on the specified name has the expected * values. * * @param name type to analyze. * @param main expected main type. * @param sub expected subtype. * @param concrete expected 'concrete' flag. */ public void assertMediaType(String name, String main, String sub, boolean concrete) { MediaType type; type = new MediaType(name); assertEquals(main, type.getMainType()); assertEquals(sub, type.getSubType()); assertEquals(concrete, type.isConcrete()); }
@Override public Representation represent(Variant variant) throws ResourceException { final MediaType mediaType = variant.getMediaType(); if (mediaType.equals(MediaType.TEXT_XML)) { return new StringRepresentation("<a>b</a>", mediaType); } else if (mediaType.equals(MediaType.TEXT_HTML)) { return new StringRepresentation("<html><body>a</body></html>", mediaType); } return null; }
/** * Builds XML or JSON Representation of Project for Create and Update methods. * * @param item Project * @param media APPLICATION_XML or APPLICATION_JSON * @return XML or JSON Representation */ public static Representation getRepresentation(TaskModel item, MediaType media) { if (media.equals(MediaType.APPLICATION_JSON)) { return new JacksonRepresentation<TaskModel>(item); } else if (media.equals(MediaType.APPLICATION_XML)) { XStream xstream = XStreamFactory.getInstance().getXStream(media, false); XstreamRepresentation<TaskModel> rep = new XstreamRepresentation<TaskModel>(media, item); configure(xstream); rep.setXstream(xstream); return rep; } else { Engine.getLogger(AbstractSitoolsTestCase.class.getName()) .warning("Only JSON or XML supported in tests"); return null; // TODO complete test with ObjectRepresentation } }
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(); } }
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); }
/** Equality tests. */ public void testEquals() throws Exception { MediaType mt1 = new MediaType("application/xml"); MediaType mt2 = MediaType.APPLICATION_XML; assertTrue(mt1.equals(mt2)); assertEquals(mt1, mt2); final Series<Parameter> mediaParams1 = new Form(); mediaParams1.add(new Parameter("charset", "ISO-8859-1")); final MediaType mt1Bis = new MediaType("application/xml", mediaParams1); final Series<Parameter> mediaParams2 = new Form(); mediaParams2.add(new Parameter("charset", "ISO-8859-1")); final MediaType mt2Bis = new MediaType("application/xml", mediaParams2); final Series<Parameter> mediaParams3 = new Form(); mediaParams3.add(new Parameter("charset", "ISO-8859-15")); final MediaType mt3 = new MediaType("application/xml", mediaParams3); assertTrue(mt1Bis.equals(mt2Bis)); assertEquals(mt1, mt2); assertTrue(mt1Bis.equals(mt1, true)); assertTrue(mt1Bis.equals(mt2, true)); assertTrue(mt1Bis.equals(mt3, true)); mt1 = new MediaType("application/*"); mt2 = MediaType.APPLICATION_ALL; assertTrue(mt1.equals(mt2)); assertEquals(mt1, mt2); }
/** Test references that are unequal. */ public void testUnEquals() throws Exception { MediaType mt1 = new MediaType("application/xml"); MediaType mt2 = new MediaType("application/xml2"); assertFalse(mt1.equals(mt2)); final Series<Parameter> mediaParams1 = new Form(); mediaParams1.add(new Parameter("charset", "ISO-8859-1")); final MediaType mt1Bis = new MediaType("application/xml", mediaParams1); final Series<Parameter> mediaParams3 = new Form(); mediaParams3.add(new Parameter("charset", "ISO-8859-15")); final MediaType mt3 = new MediaType("application/xml", mediaParams3); assertFalse(mt1Bis.equals(mt1)); assertFalse(mt1Bis.equals(mt3)); mt1 = new MediaType("application/1"); mt2 = MediaType.APPLICATION_ALL; assertFalse(mt1.equals(mt2)); }
/** * 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; } } } }
/** * Writes the current object as an XML element using the given SAX writer. * * @param writer The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); if ((getHref() != null) && (getHref().toString() != null)) { attributes.addAttribute("", "href", null, "atomURI", getHref().toString()); } writer.startElement(APP_NAMESPACE, "collection", null, attributes); if (getTitle() != null) { writer.dataElement(ATOM_NAMESPACE, "title", getTitle()); } if (getAccept() != null) { StringBuilder sb = new StringBuilder(); for (MediaType mediaType : getAccept()) { if (sb.length() > 0) { sb.append(", "); } sb.append(mediaType.toString()); } writer.dataElement(APP_NAMESPACE, "accept", sb.toString()); } try { if (getCategories() != null) { getCategories().writeElement(writer); } } catch (Exception e) { e.printStackTrace(); } writer.endElement(APP_NAMESPACE, "collection"); }
/** * 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"); } }
/** A {@code ServiceEndpointApplication} for the /json services. */ public class XACMLServiceEndpointApplication extends ServiceEndpointApplication { public static final MediaType APPLICATION_XML_XACML3 = MediaType.register("application/xacml+xml; version=3.0", "XACML v3.0 XML"); /** {@inheritDoc} Sets the default media type as "application/json". */ public XACMLServiceEndpointApplication() { super(new XMLRestStatusService()); getMetadataService().setDefaultMediaType(APPLICATION_XML_XACML3); } /** * Returns the XACML router. * * @param restEndpoints Registry of routers. * @return */ protected Restlet getRouter(RestEndpoints restEndpoints) { return restEndpoints.getXACMLServiceRouter(); } }
public void testMostSpecificMediaType() { assertEquals(MediaType.TEXT_ALL, MediaType.getMostSpecific(MediaType.ALL, MediaType.TEXT_ALL)); assertEquals(MediaType.TEXT_ALL, MediaType.getMostSpecific(MediaType.TEXT_ALL, MediaType.ALL)); assertEquals( MediaType.TEXT_PLAIN, MediaType.getMostSpecific(MediaType.ALL, MediaType.TEXT_ALL, MediaType.TEXT_PLAIN)); assertEquals( MediaType.TEXT_PLAIN, MediaType.getMostSpecific(MediaType.ALL, MediaType.TEXT_PLAIN, MediaType.TEXT_ALL)); assertEquals( MediaType.TEXT_PLAIN, MediaType.getMostSpecific(MediaType.TEXT_ALL, MediaType.ALL, MediaType.TEXT_PLAIN)); assertEquals( MediaType.TEXT_PLAIN, MediaType.getMostSpecific(MediaType.TEXT_ALL, MediaType.TEXT_PLAIN, MediaType.ALL)); assertEquals( MediaType.TEXT_PLAIN, MediaType.getMostSpecific(MediaType.TEXT_PLAIN, MediaType.ALL, MediaType.TEXT_ALL)); assertEquals( MediaType.TEXT_PLAIN, MediaType.getMostSpecific(MediaType.TEXT_PLAIN, MediaType.TEXT_ALL, MediaType.ALL)); }
private Model internalTestSearchRdf( final String searchTerm, final String[] searchTypes, final MediaType requestMediaType, final String artifactUri) throws Exception { final ClientResource searchClientResource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SEARCH)); try { searchClientResource.addQueryParameter(PoddWebConstants.KEY_SEARCHTERM, searchTerm); if (artifactUri != null) { searchClientResource.addQueryParameter( PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri); } for (final String searchType : searchTypes) { searchClientResource.addQueryParameter(PoddWebConstants.KEY_SEARCH_TYPES, searchType); } // invoke the search resource final Representation results = this.doTestAuthenticatedRequest( searchClientResource, Method.GET, null, requestMediaType, Status.SUCCESS_OK, AbstractResourceImplTest.WITH_ADMIN); final RDFFormat format = Rio.getParserFormatForMIMEType(requestMediaType.getName(), RDFFormat.RDFXML); // construct a Model out of the result return Rio.parse(new StringReader(this.getText(results)), "", format); } finally { this.releaseClient(searchClientResource); } }
@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); }
/** Test inclusion. */ public void testIncludes() throws Exception { MediaType mt1 = MediaType.APPLICATION_ALL; MediaType mt2 = MediaType.APPLICATION_XML; assertTrue(mt1.includes(mt1)); assertTrue(mt2.includes(mt2)); assertTrue(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); mt1 = MediaType.APPLICATION_ALL_XML; mt2 = MediaType.APPLICATION_XML; assertTrue(mt1.includes(mt1)); assertTrue(mt2.includes(mt2)); assertTrue(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); mt1 = MediaType.APPLICATION_ALL_XML; mt2 = MediaType.APPLICATION_ATOMPUB_SERVICE; assertTrue(mt1.includes(mt1)); assertTrue(mt2.includes(mt2)); assertTrue(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); mt1 = MediaType.IMAGE_ALL; mt2 = MediaType.APPLICATION_OCTET_STREAM; assertFalse(mt1.includes(mt2)); assertFalse(mt2.includes(mt1)); assertFalse(mt1.includes(null)); }
@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); }
/** 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()); }
/** * Remove/undeploy an existing application. This process is asynchronous – the initial request will * start the removal process and the initial response will show information about the application * being removed – however the removal process will proceed after the response is returned. The user * is expected to continue checking the application status using the applicationGetStatus method * until the removal process is complete. Once applicationGetStatus contains no information about * the specific application, it has been completely removed. * * <p>Request Parameters: * * <table border="1"> * <tr> * <th>Parameter</th> * <th>Type</th> * <th>Required</th> * <th>Description</th> * </tr> * <tr> * <td>appId</td> * <td>Integer</td> * <td>Yes</td> * <td>Application ID to remove.</td> * </tr> * </table> * * @author Wojtek, 2011 */ public class ApplicationRemoveRequest extends AbstractRequest { public static final MediaType FORM = MediaType.register("application/x-www-form-urlencoded", "Form"); private static final ResponseCode[] RESPONSE_CODES = new ResponseCode[] {ResponseCode.ACCEPTED}; public ApplicationRemoveRequest( WebApiVersion version, Date date, String keyName, String userAgent, String host, String secretKey, ServerType type) { super(version, date, keyName, userAgent, host, secretKey, type); } /* * (non-Javadoc) * * @see org.zend.webapi.core.connection.request.IRequest#getMethod() */ public Method getMethod() { return Method.POST; } /** * Application ID to remove. * * @param appId */ public void setAppId(int appId) { addParameter("appId", appId); } /* * (non-Javadoc) * * @see org.zend.webapi.internal.core.connection.request.AbstractRequest# * getResponseCodeList() */ @Override protected ResponseCode[] getValidResponseCode() { return RESPONSE_CODES; } /* * (non-Javadoc) * * @see * org.zend.webapi.core.connection.request.IRequest#getExpectedResponseDataType * () */ public ResponseType getExpectedResponseDataType() { return ResponseType.APPLICATION_INFO; } @Override public void applyParameters(Request request) { Representation rep = new MultipartRepresentation(getParameters(), FORM); request.setEntity(rep); } /* * (non-Javadoc) * * @see org.zend.webapi.internal.core.connection.request.AbstractRequest# * getMethodName() */ protected String getRequestName() { return "applicationRemove"; } }
/** * REST API Response Representation wrapper for single or multiple items expexted * * @param media MediaType expected * @param representation service response representation * @param dataClass class expected for items of the Response object * @param isArray if true wrap the data property else wrap the item property * @return Response */ public static Response getResponseOrderandUserstorage( MediaType media, Representation representation, Class<?> dataClass, boolean isArray) { try { if (!media.isCompatible(MediaType.APPLICATION_JSON) && !media.isCompatible(MediaType.APPLICATION_XML)) { Engine.getLogger(AbstractSitoolsTestCase.class.getName()) .warning("Only JSON or XML supported in tests"); return null; } XStream xstream = XStreamFactory.getInstance().getXStreamReader(media); xstream.autodetectAnnotations(false); xstream.alias("response", Response.class); // for order xstream.alias("order", Order.class); // for userstorage xstream.alias("userstorage", UserStorage.class); xstream.alias("diskStorage", DiskStorage.class); if (isArray) { xstream.alias("item", dataClass); xstream.alias("item", Object.class, dataClass); // xstream.omitField(Response.class, "data"); if (media.isCompatible(MediaType.APPLICATION_JSON)) { xstream.addImplicitCollection(Response.class, "data", dataClass); xstream.addImplicitCollection(Order.class, "events", Event.class); xstream.addImplicitCollection(Order.class, "resourceCollection", String.class); } } else { xstream.alias("item", dataClass); xstream.alias("item", Object.class, dataClass); if (dataClass == Order.class) { xstream.aliasField("order", Response.class, "item"); if (media.isCompatible(MediaType.APPLICATION_JSON)) { xstream.addImplicitCollection(Order.class, "events", Event.class); xstream.addImplicitCollection(Order.class, "resourceCollection", String.class); } } if (dataClass == UserStorage.class) { xstream.aliasField("userstorage", Response.class, "item"); } } xstream.aliasField("data", Response.class, "data"); SitoolsXStreamRepresentation<Response> rep = new SitoolsXStreamRepresentation<Response>(representation); rep.setXstream(xstream); if (media.isCompatible(getMediaTest())) { Response response = rep.getObject("response"); return response; } else { Engine.getLogger(AbstractSitoolsTestCase.class.getName()) .warning("Only JSON or XML supported in tests"); return null; // TODO complete test with ObjectRepresentation } } finally { RIAPUtils.exhaust(representation); } }