List of usage examples for javax.activation MimeType MimeType
public MimeType(String rawdata) throws MimeTypeParseException
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
/** * Handles the HTTP 200 POST response (the MDN with status indications) * * @param transmissionId the transmissionId (used in HTTP headers as Message-ID) * @param outboundMic the calculated mic of the payload (should be verified against the one returned in MDN) * @param postResponse the http response to be decoded as MDN * @return// www . j a v a2 s . c o m */ MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic, CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) { try { HttpEntity entity = postResponse.getEntity(); // Any textual results? if (entity == null) { throw new IllegalStateException( "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode()); } String contents = EntityUtils.toString(entity); if (traceEnabled) { log.debug("HTTP-headers:"); Header[] allHeaders = postResponse.getAllHeaders(); for (Header header : allHeaders) { log.debug("" + header.getName() + ": " + header.getValue()); } log.debug("Contents:\n" + contents); log.debug("---------------------------"); } Header contentTypeHeader = postResponse.getFirstHeader("Content-Type"); if (contentTypeHeader == null) { throw new IllegalStateException("No Content-Type header in response, probably a server error"); } String contentType = contentTypeHeader.getValue(); MimeMessage mimeMessage = null; try { mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType)); try { mimeMessage.writeTo(System.out); } catch (MessagingException e) { throw new IllegalStateException("Unable to print mime message"); } } catch (MimeTypeParseException e) { throw new IllegalStateException("Invalid Content-Type header"); } // verify the signature of the MDN, we warn about dodgy signatures try { SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage); X509Certificate cert = signedMimeMessage.getSignersX509Certificate(); cert.checkValidity(); // Verify if the certificate used by the receiving Access Point in // the response message does not match its certificate published by the SMP if (peppolEndpointData.getCommonName() == null || !CommonName .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) { throw new CertificateException( "Common name in certificate from SMP does not match common name in AP certificate"); } log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString()); } catch (Exception ex) { log.warn("Exception when verifying MDN signature : " + ex.getMessage()); } // Verifies the actual MDN MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); String msg = mdnMimeMessageInspector.getPlainTextPartAsText(); if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) { return mimeMessage; } else { log.error("AS2 transmission failed with some error message, msg :" + msg); log.error(contents); throw new IllegalStateException("AS2 transmission failed : " + msg); } } catch (IOException e) { throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e); } finally { try { postResponse.close(); } catch (IOException e) { throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e); } } }
From source file:org.codice.ddf.catalog.content.plugin.video.VideoThumbnailPluginTest.java
private ContentItem createMockContentItemOfMimeType(String mimeType) throws MimeTypeParseException { final ContentItem mockContentItem = mock(ContentItem.class); doReturn(new MimeType(mimeType)).when(mockContentItem).getMimeType(); doReturn(new MetacardImpl()).when(mockContentItem).getMetacard(); doReturn(UUID.randomUUID().toString()).when(mockContentItem).getId(); return mockContentItem; }
From source file:net.di2e.ecdr.source.rest.CDROpenSearchSource.java
protected ResourceResponse doRetrieval(WebClient retrieveWebClient, Map<String, Serializable> requestProperties) throws ResourceNotFoundException, IOException { ResourceResponse resourceResponse = null; setSecurityCredentials(retrieveWebClient, requestProperties); URI uri = retrieveWebClient.getCurrentURI(); try {//ww w .j a va 2 s .co m Long bytesToSkip = null; // If a bytesToSkip property is present add range header if (requestProperties != null && requestProperties.containsKey(BYTES_TO_SKIP)) { bytesToSkip = (Long) requestProperties.get(BYTES_TO_SKIP); if (bytesToSkip != null) { LOGGER.debug( "Setting Range header on retrieve request from remote CDR Source [{}] with bytes to skip [{}]", localId, bytesToSkip); // This creates a Range header in the following manner if // 100 bytes were to be skipped. The end - means its open // ended // Range: bytes=100- retrieveWebClient.header(HEADER_RANGE, BYTES_EQUAL + bytesToSkip + "-"); } } Response clientResponse = retrieveWebClient.get(); MediaType mediaType = clientResponse.getMediaType(); MimeType mimeType = null; try { mimeType = (mediaType == null) ? new MimeType("application/octet-stream") : new MimeType(mediaType.toString()); LOGGER.debug( "Creating mime type from CDR Source named [{}] using uri [{}] with value [{}] defaulting to [{}]", localId, uri, mediaType); } catch (MimeTypeParseException e) { try { mimeType = new MimeType("application/octet-stream"); LOGGER.warn( "Creating mime type from CDR Source named [{}] using uri [{}] with value [{}] defaulting to [{}]", localId, uri, "application/octet-stream"); } catch (MimeTypeParseException e1) { LOGGER.error("Could not create MIMEType for resource being retrieved", e1); } } String dispositionString = clientResponse.getHeaderString(HEADER_CONTENT_DISPOSITION); String fileName = null; if (dispositionString != null) { ContentDisposition contentDisposition = new ContentDisposition(dispositionString); fileName = contentDisposition.getParameter("filename"); if (fileName == null) { fileName = contentDisposition.getParameter("\"filename\""); } if (fileName == null) { // ECDR-74 use MIMEType parser to get the file extension in fileName = getId() + "-" + System.currentTimeMillis(); } } else { // ECDR-74 use MIMEType parser to get the file extension in this // case fileName = getId() + "-" + System.currentTimeMillis(); } InputStream binaryStream = (InputStream) clientResponse.getEntity(); if (binaryStream != null) { Map<String, Serializable> responseProperties = new HashMap<String, Serializable>(); if (bytesToSkip != null) { // Since we sent a range header an accept-ranges header // should be returned if the // remote endpoint support it. If is not present, the // inputStream hasn't skipped ahead // by the given number of bytes, so we need to take care of // it here. String rangeHeader = clientResponse.getHeaderString(HEADER_ACCEPT_RANGES); if (rangeHeader == null || !rangeHeader.equals(BYTES)) { LOGGER.debug( "Skipping {} bytes in CDR Remote Source because endpoint didn't support Range Headers", bytesToSkip); try { // the Java inputStream.skip() method is not // guaranteed to skip all the bytes so we use a // utility method that is IOUtils.skipFully(binaryStream, bytesToSkip); } catch (EOFException e) { LOGGER.warn( "Skipping the requested number of bytes [{}] for URI [{}] resulted in an End of File, so re-retrieving the complete file without skipping bytes: {}", bytesToSkip, uri, e.getMessage()); try { binaryStream.close(); } catch (IOException e1) { LOGGER.debug("Error encountered while closing inputstream"); } return doRetrieval(retrieveWebClient, null); } } else if (rangeHeader != null && rangeHeader.equals(BYTES)) { LOGGER.debug( "CDR Remote source supports Range Headers, only retrieving part of file that has not been downloaded yet."); responseProperties.put(BYTES_SKIPPED_RESPONSE, Boolean.TRUE); } } resourceResponse = new ResourceResponseImpl(new ResourceRequestByProductUri(uri, requestProperties), responseProperties, new ResourceImpl(binaryStream, mimeType, fileName)); } } catch (RuntimeException e) { LOGGER.warn( "Expected exception encountered when trying to retrieve resource with URI [{}] from source [{}]", uri, localId); } return resourceResponse; }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.transformer.CswQueryResponseTransformerTest.java
@Test public void testMarshalAcknowledgementWithFailedTransforms() throws WebApplicationException, IOException, JAXBException, CatalogTransformerException { GetRecordsType query = new GetRecordsType(); query.setResultType(ResultType.RESULTS); query.setMaxRecords(BigInteger.valueOf(6)); query.setStartPosition(BigInteger.valueOf(0)); SourceResponse sourceResponse = createSourceResponse(query, 6); Map<String, Serializable> args = new HashMap<>(); args.put(CswConstants.RESULT_TYPE_PARAMETER, ResultType.RESULTS); args.put(CswConstants.GET_RECORDS, query); PrintWriter printWriter = getSimplePrintWriter(); MetacardTransformer mockMetacardTransformer = mock(MetacardTransformer.class); final AtomicLong atomicLong = new AtomicLong(0); when(mockMetacardTransformer.transform(any(Metacard.class), anyMap())).then(invocationOnMock -> { if (atomicLong.incrementAndGet() == 2) { throw new CatalogTransformerException(""); }/*from w w w .j a v a2s.c om*/ Metacard metacard = (Metacard) invocationOnMock.getArguments()[0]; BinaryContentImpl bci = new BinaryContentImpl(IOUtils.toInputStream(metacard.getId() + ","), new MimeType("application/xml")); return bci; }); when(mockPrintWriterProvider.build((Class<Metacard>) notNull())).thenReturn(printWriter); when(mockTransformerManager.getTransformerBySchema(anyString())).thenReturn(mockMetacardTransformer); CswQueryResponseTransformer cswQueryResponseTransformer = new CswQueryResponseTransformer( mockTransformerManager, mockPrintWriterProvider); cswQueryResponseTransformer.init(); BinaryContent content = cswQueryResponseTransformer.transform(sourceResponse, args); cswQueryResponseTransformer.destroy(); String xml = new String(content.getByteArray()); assertThat(xml, containsString(CswQueryResponseTransformer.NUMBER_OF_RECORDS_MATCHED_ATTRIBUTE + " 6")); assertThat(xml, containsString(CswQueryResponseTransformer.NUMBER_OF_RECORDS_RETURNED_ATTRIBUTE + " 5")); assertThat(xml, containsString(CswQueryResponseTransformer.NEXT_RECORD_ATTRIBUTE + " 0")); }
From source file:org.mulgara.resolver.http.HttpContent.java
/** * Read the mime type. Should only be done if the Mime type is not already available * as this will close the connection./*from ww w. ja v a 2s .co m*/ * @return The MimeType for the URL. * @throws NotModifiedException if the content validates against the cache */ @SuppressWarnings("unchecked") private MimeType readMimeType(HttpMethod method) throws NotModifiedException { MimeType result = null; String contentType = null; try { // obtain connection and retrieve the headers Header header = method.getResponseHeader("Content-Type"); if (header != null) { contentType = header.getValue(); // find the parameter separator so we can protect against bad params int sep = contentType.indexOf(';'); // no params, just create the MimeType if (sep < 0) result = new MimeType(contentType); else { // create the MimeType from the type/subtype result = new MimeType(contentType.substring(0, sep)); // parse parameters separately and set the result accordingly try { MimeTypeParameterList params = new MimeTypeParameterList(contentType.substring(sep + 1)); Enumeration<String> names = (Enumeration<String>) params.getNames(); while (names.hasMoreElements()) { String name = names.nextElement(); result.setParameter(name, params.get(name)); } } catch (MimeTypeParseException e) { logger.warn("Ignoring bad parameters in '" + contentType.substring(sep + 1) + "' from the content type for " + httpUri); } } if (logger.isInfoEnabled()) { logger.info("Obtain content type " + result + " from " + httpUri); } } } catch (java.lang.IllegalStateException e) { logger.info("Unable to obtain content type for " + httpUri); } catch (MimeTypeParseException e) { logger.warn("Unexpected parameters before ; in '" + contentType + "' as a content type for " + httpUri); } return result; }
From source file:net.di2e.ecdr.source.rest.AbstractCDRSource.java
protected ResourceResponse doRetrieval(WebClient retrieveWebClient, Map<String, Serializable> requestProperties) throws ResourceNotFoundException, IOException { ResourceResponse resourceResponse = null; setSecurityCredentials(retrieveWebClient, requestProperties); URI uri = retrieveWebClient.getCurrentURI(); try {/*from www .j ava2 s.c o m*/ Long bytesToSkip = null; // If a bytesToSkip property is present add range header if (requestProperties != null && requestProperties.containsKey(BYTES_TO_SKIP)) { bytesToSkip = (Long) requestProperties.get(BYTES_TO_SKIP); if (bytesToSkip != null) { LOGGER.debug( "Setting Range header on retrieve request from remote CDR Source [{}] with bytes to skip [{}]", getId(), bytesToSkip); // This creates a Range header in the following manner if // 100 bytes were to be skipped. The end - means its open ended // Range: bytes=100- retrieveWebClient.header(HEADER_RANGE, BYTES_EQUAL + bytesToSkip + "-"); } } Response clientResponse = retrieveWebClient.get(); MediaType mediaType = clientResponse.getMediaType(); MimeType mimeType = null; try { mimeType = (mediaType == null) ? new MimeType("application/octet-stream") : new MimeType(mediaType.toString()); LOGGER.debug( "Creating mime type from CDR Source named [{}] using uri [{}] with value [{}] defaulting to [{}]", getId(), uri, mediaType); } catch (MimeTypeParseException e) { try { mimeType = new MimeType("application/octet-stream"); LOGGER.warn( "Creating mime type from CDR Source named [{}] using uri [{}] with value [{}] defaulting to [{}]", getId(), uri, "application/octet-stream"); } catch (MimeTypeParseException e1) { LOGGER.error("Could not create MIMEType for resource being retrieved", e1); } } String dispositionString = clientResponse.getHeaderString(HEADER_CONTENT_DISPOSITION); String fileName = null; if (dispositionString != null) { ContentDisposition contentDisposition = new ContentDisposition(dispositionString); fileName = contentDisposition.getParameter("filename"); if (fileName == null) { fileName = contentDisposition.getParameter("\"filename\""); } if (fileName == null) { // ECDR-74 use MIMEType parser to get the file extension in fileName = getId() + "-" + System.currentTimeMillis(); } } else { // ECDR-74 use MIMEType parser to get the file extension in this case fileName = getId() + "-" + System.currentTimeMillis(); } InputStream binaryStream = (InputStream) clientResponse.getEntity(); if (binaryStream != null) { Map<String, Serializable> responseProperties = new HashMap<String, Serializable>(); if (bytesToSkip != null) { // Since we sent a range header an accept-ranges header // should be returned if the // remote endpoint support it. If is not present, the // inputStream hasn't skipped ahead // by the given number of bytes, so we need to take care of // it here. String rangeHeader = clientResponse.getHeaderString(HEADER_ACCEPT_RANGES); if (rangeHeader == null || !rangeHeader.equals(BYTES)) { LOGGER.debug( "Skipping {} bytes in CDR Remote Source because endpoint didn't support Range Headers", bytesToSkip); try { // the Java inputStream.skip() method is not guaranteed to skip all the bytes so we use a // utility method that is IOUtils.skipFully(binaryStream, bytesToSkip); } catch (EOFException e) { LOGGER.warn( "Skipping the requested number of bytes [{}] for URI [{}] resulted in an End of File, so re-retrieving the complete file without skipping bytes: {}", bytesToSkip, uri, e.getMessage()); try { binaryStream.close(); } catch (IOException e1) { LOGGER.debug("Error encountered while closing inputstream"); } return doRetrieval(retrieveWebClient, null); } } else if (rangeHeader != null && rangeHeader.equals(BYTES)) { LOGGER.debug( "CDR Remote source supports Range Headers, only retrieving part of file that has not been downloaded yet."); responseProperties.put(BYTES_SKIPPED_RESPONSE, Boolean.TRUE); } } resourceResponse = new ResourceResponseImpl(new ResourceRequestByProductUri(uri, requestProperties), responseProperties, new ResourceImpl(binaryStream, mimeType, fileName)); } } catch (RuntimeException e) { LOGGER.warn( "Expected exception encountered when trying to retrieve resource with URI [{}] from source [{}}", uri, getId()); } return resourceResponse; }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.transformer.CswQueryResponseTransformerTest.java
@Test public void verifyResultOrderIsMaintained() throws CatalogTransformerException, IOException { // when/*from ww w . j a va 2s . co m*/ when(mockPrintWriterProvider.build((Class<Metacard>) notNull())).thenReturn(mockPrintWriter); when(mockPrintWriter.makeString()).thenReturn(new String()); when(mockSourceResponse.getResults()).thenReturn(createResults(1, 10)); when(mockSourceResponse.getRequest()).thenReturn(mockQueryRequest); when(mockQueryRequest.getQuery()).thenReturn(mockQuery); when(mockArguments.get(CswConstants.RESULT_TYPE_PARAMETER)).thenReturn(ResultType.RESULTS); when(mockTransformerManager.getTransformerBySchema(anyString())).thenReturn(mockMetacardTransformer); when(mockMetacardTransformer.transform(any(Metacard.class), any(Map.class))) .thenAnswer(invocationOnMock -> { Metacard metacard = (Metacard) invocationOnMock.getArguments()[0]; BinaryContentImpl bci = new BinaryContentImpl(IOUtils.toInputStream(metacard.getId() + ","), new MimeType("application/xml")); return bci; }); // given transformer.init(); transformer.transform(mockSourceResponse, mockArguments); transformer.destroy(); // then ArgumentCaptor<String> tmCaptor = ArgumentCaptor.forClass(String.class); verify(mockTransformerManager, times(1)).getTransformerBySchema(tmCaptor.capture()); ArgumentCaptor<Map> mapCaptor = ArgumentCaptor.forClass(Map.class); ArgumentCaptor<Metacard> mcCaptor = ArgumentCaptor.forClass(Metacard.class); verify(mockMetacardTransformer, times(10)).transform(mcCaptor.capture(), mapCaptor.capture()); ArgumentCaptor<String> strCaptor = ArgumentCaptor.forClass(String.class); verify(mockPrintWriter, times(2)).setRawValue(strCaptor.capture()); String order = strCaptor.getAllValues().get(1); String[] ids = order.split(","); for (int i = 1; i < ids.length; i++) { assertThat(ids[i - 1], is(String.valueOf("id_" + i))); } }
From source file:com.lmco.ddf.endpoints.rest.RESTEndpoint.java
private MimeType getMimeType(HttpHeaders headers) { List<String> contentTypeList = headers.getRequestHeader(HttpHeaders.CONTENT_TYPE); String singleMimeType = null; if (contentTypeList != null && !contentTypeList.isEmpty()) { singleMimeType = contentTypeList.get(0); LOGGER.debug("Encountered [" + singleMimeType + "] " + HttpHeaders.CONTENT_TYPE); }//from w ww.java2 s .co m MimeType mimeType = null; // Sending a null argument to MimeType causes NPE if (singleMimeType != null) { try { mimeType = new MimeType(singleMimeType); } catch (MimeTypeParseException e) { LOGGER.debug("Could not parse mime type from headers.", e); } } return mimeType; }
From source file:fr.gael.dhus.datastore.processing.ProcessingUtils.java
public static List<MetadataIndex> getIndexesFrom(URL url) { java.util.Collection<String> properties = null; DrbNode node = null;/*w ww.j a v a 2 s . c o m*/ 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. node = ProcessingUtils.getNodeFromPath(url.getPath()); cl = ProcessingUtils.getClassFromNode(node); 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_METADATA_EXTRACTOR, 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(); try { out.close(); } catch (IOException e) { logger.warn("Cannot close stream !", e); } } 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.mule.endpoint.AbstractEndpointBuilder.java
public void setMimeType(String mimeType) { if (mimeType == null) { this.mimeType = null; } else {/*from w w w . j a v a2 s .c o m*/ MimeType mt; try { mt = new MimeType(mimeType); } catch (MimeTypeParseException e) { throw new IllegalArgumentException(e.getMessage(), e); } this.mimeType = mt.getPrimaryType() + "/" + mt.getSubType(); } }