List of usage examples for javax.activation MimeType MimeType
public MimeType(String rawdata) throws MimeTypeParseException
From source file:ddf.catalog.resource.download.ReliableResourceDownloaderTest.java
private ResourceResponse getMockResourceResponse(InputStream stream) throws Exception { ResourceRequest resourceRequest = mock(ResourceRequest.class); Map<String, Serializable> requestProperties = new HashMap<String, Serializable>(); when(resourceRequest.getPropertyNames()).thenReturn(requestProperties.keySet()); mockResource = mock(Resource.class); when(mockResource.getInputStream()).thenReturn(stream); when(mockResource.getName()).thenReturn("test-resource"); when(mockResource.getMimeType()).thenReturn(new MimeType("text/plain")); mockResponse = mock(ResourceResponse.class); when(mockResponse.getRequest()).thenReturn(resourceRequest); when(mockResponse.getResource()).thenReturn(mockResource); Map<String, Serializable> responseProperties = new HashMap<String, Serializable>(); when(mockResponse.getProperties()).thenReturn(responseProperties); return mockResponse; }
From source file:mitm.common.pdf.MessagePDFBuilder.java
private void addAttachment(final Part part, PdfWriter pdfWriter) throws IOException, MessagingException { byte[] content = IOUtils.toByteArray(part.getInputStream()); String filename = StringUtils .defaultString(HeaderUtils.decodeTextQuietly(MimeUtils.getFilenameQuietly(part)), "attachment.bin"); String baseType;//www . j a va 2s . c om String contentType = null; try { contentType = part.getContentType(); MimeType mimeType = new MimeType(contentType); baseType = mimeType.getBaseType(); } catch (MimeTypeParseException e) { /* * Can happen when the content-type is not correct. Example with missing ; between charset and name: * * Content-Type: application/pdf; * charset="Windows-1252" name="postcard2010.pdf" */ logger.warn("Unable to infer MimeType from content type. Fallback to application/octet-stream. " + "Content-Type: " + contentType); baseType = MimeTypes.OCTET_STREAM; } PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(pdfWriter, null, filename, content, true /* compress */, baseType, null); pdfWriter.addFileAttachment(fileSpec); }
From source file:ddf.content.plugin.video.TestVideoThumbnailPlugin.java
@Test public void testUpdatedItemNotVideoFile() throws Exception { mockContentItem = mock(ContentItem.class); doReturn(new MimeType("application/pdf")).when(mockContentItem).getMimeType(); final UpdateResponse mockUpdateResponse = mock(UpdateResponse.class); doReturn(mockContentItem).when(mockUpdateResponse).getUpdatedContentItem(); final UpdateResponse processedUpdateResponse = videoThumbnailPlugin.process(mockUpdateResponse); assertThat(getAttributeMapFromResponse(processedUpdateResponse), not(hasKey(Metacard.THUMBNAIL))); }
From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductIndexes.java
public List<MetadataIndex> getIndexesFrom(URL url) { Collection<String> properties = null; DrbNode node = null;/* w w w . j av a2s . com*/ DrbCortexItemClass cl = null; // Prepare the index structure. List<MetadataIndex> indexes = new ArrayList<MetadataIndex>(); // Prepare the DRb node to be processed try { // First : force loading the model before accessing items. DrbCortexModel model = DrbCortexModel.getDefaultModel(); node = ProcessingUtils.getNodeFromPath(url.getPath()); if (node == null) { throw new IOException("Cannot Instantiate Drb with URI \"" + url.toExternalForm() + "\"."); } cl = model.getClassOf(node); if (cl == null) { throw new UnsupportedOperationException("Class cannot be retrieved for product " + node.getPath()); } logger.info("Class \"" + cl.getLabel() + "\" for product " + node.getName()); // Get all values of the metadata properties attached to the item // class or any of its super-classes properties = cl.listPropertyStrings(METADATA_NAMESPACE + PROPERTY, false); // Return immediately if no property value were found if (properties == null) { logger.warn("Item \"" + cl.getLabel() + "\" has no metadata defined."); return null; } } catch (IOException e) { throw new UnsupportedOperationException("Error While decoding drb node", e); } // Loop among retrieved property values for (String property : properties) { // Filter possible XML markup brackets that could have been encoded // in a CDATA section property = property.replaceAll("<", "<"); property = property.replaceAll(">", ">"); /* * property = property.replaceAll("\n", " "); // Replace eol by blank * space property = property.replaceAll(" +", " "); // Remove * contiguous blank spaces */ // Create a query for the current metadata extractor Query metadataQuery = new Query(property); // Evaluate the XQuery DrbSequence metadataSequence = metadataQuery.evaluate(node); // Check that something results from the evaluation: jump to next // value otherwise if ((metadataSequence == null) || (metadataSequence.getLength() < 1)) { continue; } // Loop among results for (int iitem = 0; iitem < metadataSequence.getLength(); iitem++) { // Get current metadata node DrbNode n = (DrbNode) metadataSequence.getItem(iitem); // Get name DrbAttribute name_att = n.getAttribute("name"); Value name_v = null; if (name_att != null) name_v = name_att.getValue(); String name = null; if (name_v != null) name = name_v.convertTo(Value.STRING_ID).toString(); // get type DrbAttribute type_att = n.getAttribute("type"); Value type_v = null; if (type_att != null) type_v = type_att.getValue(); else type_v = new fr.gael.drb.value.String(MIME_PLAIN_TEXT); String type = type_v.convertTo(Value.STRING_ID).toString(); // get category DrbAttribute cat_att = n.getAttribute("category"); Value cat_v = null; if (cat_att != null) cat_v = cat_att.getValue(); else cat_v = new fr.gael.drb.value.String("product"); String category = cat_v.convertTo(Value.STRING_ID).toString(); // get category DrbAttribute qry_att = n.getAttribute("queryable"); String queryable = null; if (qry_att != null) { Value qry_v = qry_att.getValue(); if (qry_v != null) queryable = qry_v.convertTo(Value.STRING_ID).toString(); } // Get value String value = null; if (MIME_APPLICATION_GML.equals(type) && n.hasChild()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); XmlWriter.writeXML(n.getFirstChild(), out); value = out.toString(); } else // Case of "text/plain" { Value value_v = n.getValue(); if (value_v != null) { value = value_v.convertTo(Value.STRING_ID).toString(); value = value.trim(); } } if ((name != null) && (value != null)) { MetadataIndex index = new MetadataIndex(); index.setName(name); try { index.setType(new MimeType(type).toString()); } catch (MimeTypeParseException e) { logger.warn("Wrong metatdata extractor mime type in class \"" + cl.getLabel() + "\" for metadata called \"" + name + "\".", e); } index.setCategory(category); index.setValue(value); index.setQueryable(queryable); indexes.add(index); } else { String field_name = ""; if (name != null) field_name = name; else if (queryable != null) field_name = queryable; else if (category != null) field_name = "of category " + category; logger.warn("Nothing extracted for field " + field_name); } } } return indexes; }
From source file:org.codice.ddf.catalog.content.plugin.video.TestVideoThumbnailPlugin.java
@Test public void testCreatedItemNotVideoFile() throws Exception { mockContentItem = mock(ContentItem.class); doReturn(new MimeType("image/jpeg")).when(mockContentItem).getMimeType(); Metacard mockMetacard = new MetacardImpl(); doReturn(mockMetacard).when(mockContentItem).getMetacard(); final CreateStorageResponse mockCreateResponse = mock(CreateStorageResponse.class); doReturn(Collections.singletonList(mockContentItem)).when(mockCreateResponse).getCreatedContentItems(); final CreateStorageResponse processedCreateResponse = videoThumbnailPlugin.process(mockCreateResponse); assertThat(processedCreateResponse.getCreatedContentItems().get(0).getMetacard() .getAttribute(Metacard.THUMBNAIL), CoreMatchers.is(nullValue())); }
From source file:eu.fusepool.p3.proxy.ProxyTest.java
@Test public void longRunningTransformer() throws Exception { TransformerServer transformerServer = new TransformerServer(transformerPort, false); final boolean[] transformerInvoked = new boolean[1]; transformerServer.start(new SyncTransformer() { @Override//from w ww. j a v a 2 s .c o m public Entity transform(HttpRequestEntity hre) throws IOException { transformerInvoked[0] = true; try { Thread.sleep(longRunningSeconds * 1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return new InputStreamEntity() { @Override public MimeType getType() { try { return new MimeType("text/plain"); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } } @Override public InputStream getData() throws IOException { return new ByteArrayInputStream("Tranformed".getBytes()); } }; } @Override public boolean isLongRunning() { return true; } @Override public Set<MimeType> getSupportedInputFormats() { try { return Collections.singleton(new MimeType("text/plain")); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } } @Override public Set<MimeType> getSupportedOutputFormats() { try { return Collections.singleton(new MimeType("text/plain")); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } } }); final String turtleLdpc = "@prefix dcterms: <http://purl.org/dc/terms/>.\n" + "@prefix ldp: <http://www.w3.org/ns/ldp#>.\n" + "@prefix eldp: <http://vocab.fusepool.info/eldp#>.\n" + "\n" + "<http://localhost:" + proxyPort + "/container2/>\n" + " a ldp:DirectContainer;\n" + " dcterms:title \"An extracting LDP Container using simple-transformer\";\n" + " ldp:membershipResource <http://localhost:" + proxyPort + "/container1/>;\n" + " ldp:hasMemberRelation ldp:member;\n" + " ldp:insertedContentRelation ldp:MemberSubject;\n" + " eldp:transformer <http://localhost:" + transformerPort + "/long-transformer>."; stubFor(get(urlEqualTo("/container2/")) //.withHeader("Accept", equalTo("text/turtle")) .willReturn(aResponse().withStatus(HttpStatus.SC_OK).withHeader("Content-Type", "text/turtle") .withBody(turtleLdpc))); stubFor(post(urlEqualTo("/container2/")) //.withHeader("Conetnt-Type", matching("text/plain*")) .willReturn(aResponse().withStatus(HttpStatus.SC_CREATED).withHeader("Location", "http://localhost:" + proxyPort + "/container2/new-resource"))); //A GET request returns the unmodified answer RestAssured.given().header("Accept", "text/turtle").expect().statusCode(HttpStatus.SC_OK) .header("Content-Type", "text/turtle").when().get("/container2/"); //Certainly the backend got the request verify(getRequestedFor(urlMatching("/container2/"))); //Let's post some content RestAssured.given().contentType("text/plain;charset=UTF-8").header("Authorization", "foobar") .content("hello").expect().statusCode(HttpStatus.SC_CREATED).when().post("/container2/"); //the backend got the post request aiaginst the LDPC verify(postRequestedFor(urlMatching("/container2/")).withHeader("Authorization", equalTo("foobar"))); //and after a while also against the Transformer //first the transformer whould be checcked if the format matches //wait and try: verify(getRequestedFor(urlMatching("/simple-transformer"))); //then we will get a POST (since media type is supported) int i = 0; while (true) { Thread.sleep(100); try { Assert.assertTrue(transformerInvoked[0]); break; } catch (Error e) { } if (i++ > 600) { //after one minute for real: Assert.assertTrue(transformerInvoked[0]); } } Thread.sleep(longRunningSeconds * 1000); i = 0; while (true) { try { verify(2, postRequestedFor(urlMatching("/container2/")).withHeader("Authorization", equalTo("foobar"))); break; } catch (Error e) { } Thread.sleep(100); if (i++ > 1200) { //after two minute for real (two minutes is the maximum polling interval of the transformer client) verify(2, postRequestedFor(urlMatching("/container2/")).withHeader("Authorization", equalTo("foobar"))); } } }
From source file:org.codice.ddf.spatial.ogc.catalog.resource.impl.TestResourceReader.java
/** * Tests the case in which the Resource in the ResourceResponse returned by the * URLResourceReader has an application/octet-stream mime type. *//*from www . j a v a 2s . c o m*/ @Test public void testRetrieveResourceApplicationOctetStreamResourceMimeType() throws Exception { // Setup String httpUriStr = HTTP_SCHEME_PLUS_SEP + MOCK_HTTP_SERVER_HOST + ":" + MOCK_HTTP_SERVER_PORT + MOCK_HTTP_SERVER_PATH; URI uri = new URI(httpUriStr); Response mockResponse = getMockResponse(); setupMockWebClient(mockResponse); ResourceResponse mockResourceResponse = getMockResourceResponse(new MimeType("application/octet-stream")); URLResourceReader mockUrlResourceReader = getMockUrlResourceReader(uri, mockResourceResponse); setupMockTika(MediaType.TEXT_HTML); OgcUrlResourceReader resourceReader = new OgcUrlResourceReader(mockUrlResourceReader, mockTika); HashMap<String, Serializable> arguments = new HashMap<String, Serializable>(); // Perform Test ResourceResponse resourceResponse = resourceReader.retrieveResource(uri, arguments); // Verify StringWriter writer = new StringWriter(); IOUtils.copy(resourceResponse.getResource().getInputStream(), writer, MOCK_HTTP_SERVER_ENCODING); String responseString = writer.toString(); LOGGER.info("Response " + responseString); assertThat(responseString, is("<html><script type=\"text/javascript\">window.location.replace(\"" + httpUriStr + "\");</script></html>")); }
From source file:org.codice.ddf.spatial.ogc.catalog.resource.impl.ResourceReaderTest.java
/** * Tests the case in which the Resource in the ResourceResponse returned by the URLResourceReader * has an application/octet-stream mime type. *//*from w w w. j av a 2 s. c o m*/ @Test public void testRetrieveResourceApplicationOctetStreamResourceMimeType() throws Exception { // Setup String httpUriStr = HTTP_SCHEME_PLUS_SEP + MOCK_HTTP_SERVER_HOST + ":" + MOCK_HTTP_SERVER_PORT + MOCK_HTTP_SERVER_PATH; URI uri = new URI(httpUriStr); Response mockResponse = getMockResponse(); setupMockWebClient(mockResponse); ResourceResponse mockResourceResponse = getMockResourceResponse(new MimeType("application/octet-stream")); URLResourceReader mockUrlResourceReader = getMockUrlResourceReader(uri, mockResourceResponse); setupMockTika(MediaType.TEXT_HTML); OgcUrlResourceReader resourceReader = new OgcUrlResourceReader(mockUrlResourceReader, mockTika); HashMap<String, Serializable> arguments = new HashMap<String, Serializable>(); // Perform Test ResourceResponse resourceResponse = resourceReader.retrieveResource(uri, arguments); // Verify StringWriter writer = new StringWriter(); IOUtils.copy(resourceResponse.getResource().getInputStream(), writer, MOCK_HTTP_SERVER_ENCODING); String responseString = writer.toString(); LOGGER.info("Response {}", responseString); assertThat(responseString, is("<html><script type=\"text/javascript\">window.location.replace(\"" + httpUriStr + "\");</script></html>")); }
From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java
private void extractBody(Part Mess, cfArrayData AD, String attachURI, String attachDIR) throws Exception { if (Mess.isMimeType("multipart/*")) { Multipart mp = (Multipart) Mess.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) extractBody(mp.getBodyPart(i), AD, attachURI, attachDIR); } else {/*from ww w. j a v a 2 s. co m*/ cfStructData sd = new cfStructData(); String tmp = Mess.getContentType(); if (tmp.indexOf(";") != -1) tmp = tmp.substring(0, tmp.indexOf(";")); sd.setData("mimetype", new cfStringData(tmp)); String filename = getFilename(Mess); String dispos = getDisposition(Mess); MimeType messtype = new MimeType(tmp); // Note that we can't use Mess.isMimeType() here due to bug #2080 if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && messtype.match("text/*")) { Object content; String contentType = Mess.getContentType().toLowerCase(); // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7 if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) { InputStream ins = Mess.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(ins, bos); content = new String(UTF7Converter.convert(bos.toByteArray())); } else { try { content = Mess.getContent(); } catch (UnsupportedEncodingException e) { content = Mess.getInputStream(); } catch (IOException ioe) { // This will happen on BD/Java when the attachment has no content // NOTE: this is the fix for bug NA#3198. content = ""; } } if (content instanceof InputStream) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy((InputStream) content, bos); sd.setData("content", new cfStringData(new String(bos.toByteArray()))); } else { sd.setData("content", new cfStringData(content.toString())); } sd.setData("file", cfBooleanData.FALSE); sd.setData("filename", new cfStringData(filename == null ? "" : filename)); } else if (attachDIR != null) { sd.setData("content", new cfStringData("")); if (filename == null || filename.length() == 0) filename = "unknownfile"; filename = getAttachedFilename(attachDIR, filename); //--[ An attachment, save it out to disk try { BufferedInputStream in = new BufferedInputStream(Mess.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( cfEngine.thisPlatform.getFileIO().getFileOutputStream(new File(attachDIR + filename))); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); sd.setData("file", cfBooleanData.TRUE); sd.setData("filename", new cfStringData(filename)); if (attachURI.charAt(attachURI.length() - 1) != '/') sd.setData("url", new cfStringData(attachURI + '/' + filename)); else sd.setData("url", new cfStringData(attachURI + filename)); sd.setData("size", new cfNumberData((int) new File(attachDIR + filename).length())); } catch (Exception ignoreException) { // NOTE: this could happen when we don't have permission to write to the specified directory // so let's log an error message to make this easier to debug. cfEngine.log("-] Failed to save attachment to " + attachDIR + filename + ", exception=[" + ignoreException.toString() + "]"); } } else { sd.setData("file", cfBooleanData.FALSE); sd.setData("content", new cfStringData("")); } AD.addElement(sd); } }
From source file:org.codice.ddf.catalog.content.plugin.video.TestVideoThumbnailPlugin.java
@Test public void testUpdatedItemNotVideoFile() throws Exception { mockContentItem = mock(ContentItem.class); doReturn(new MimeType("application/pdf")).when(mockContentItem).getMimeType(); Metacard mockMetacard = new MetacardImpl(); doReturn(mockMetacard).when(mockContentItem).getMetacard(); final UpdateStorageResponse mockUpdateResponse = mock(UpdateStorageResponse.class); doReturn(Collections.singletonList(mockContentItem)).when(mockUpdateResponse).getUpdatedContentItems(); final UpdateStorageResponse processedUpdateResponse = videoThumbnailPlugin.process(mockUpdateResponse); assertThat(processedUpdateResponse.getUpdatedContentItems().get(0).getMetacard() .getAttribute(Metacard.THUMBNAIL), CoreMatchers.is(nullValue())); }