List of usage examples for javax.activation MimeTypeParseException getMessage
public String getMessage()
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender, PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData, PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) { if (peppolEndpointData.getCommonName() == null) { throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData); }//from www. ja v a2s .c om X509Certificate ourCertificate = keystoreManager.getOurCertificate(); SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(), ourCertificate); MimeMessage signedMimeMessage = null; Mic mic = null; try { MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream, new MimeType("application/xml")); mic = MimeMessageHelper.calculateMic(mimeBodyPart); log.debug("Outbound MIC is : " + mic.toString()); signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart); } catch (MimeTypeParseException e) { throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e); } String endpointAddress = peppolEndpointData.getUrl().toExternalForm(); HttpPost httpPost = new HttpPost(endpointAddress); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { signedMimeMessage.writeTo(byteArrayOutputStream); } catch (Exception e) { throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream"); } httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString()); try { httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(), PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString()); } catch (InvalidAs2SystemIdentifierException e) { throw new IllegalArgumentException( "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData); } httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no"); httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(), As2DispositionNotificationOptions.getDefault().toString()); httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION); httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS"); TransmissionId transmissionId = new TransmissionId(); httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString()); httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date())); // Inserts the S/MIME message to be posted. // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header try { String contentType = signedMimeMessage.getContentType(); ContentType ct = ContentType.create(contentType); httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct)); } catch (Exception ex) { throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage()); } CloseableHttpResponse postResponse = null; // EXECUTE !!!! try { CloseableHttpClient httpClient = createCloseableHttpClient(); log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type " + peppolDocumentTypeId); postResponse = httpClient.execute(httpPost); } catch (HttpHostConnectException e) { throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress); } catch (Exception e) { throw new IllegalStateException( "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(), e); } if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode() + " from " + endpointAddress); throw handleFailedRequest(postResponse); } // handle normal HTTP OK response log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress + " returned HTTP OK, verify MDN response"); MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData); // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields(); String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST); if (messageDigestAsBase64 == null) { messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes())); } String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP); Date receptionTimeStamp = null; if (receptionTimeStampAsString != null) { receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString); } else { receptionTimeStamp = new Date(); } // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString()); @NotNull As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence( EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage, new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64), transmissionId); ByteArrayOutputStream evidenceBytes; try { evidenceBytes = new ByteArrayOutputStream(); IOUtils.copy(evidence.getInputStream(), evidenceBytes); } catch (IOException e) { throw new IllegalStateException( "Unable to transform transport evidence to byte array." + e.getMessage(), e); } return new SendResult(transmissionId, evidenceBytes.toByteArray()); }
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 {//from w ww .jav a 2s . 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: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 {/* ww w .jav a2s . 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.mule.endpoint.AbstractEndpointBuilder.java
public void setMimeType(String mimeType) { if (mimeType == null) { this.mimeType = null; } else {/*from w ww. ja 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(); } }
From source file:org.osaf.cosmo.dav.impl.StandardDavRequest.java
private Document getSafeRequestDocument(boolean requireDocument) throws DavException { try {/*ww w. j a v a 2 s . c om*/ if (StringUtils.isBlank(getContentType())) { if (requireDocument) throw new BadRequestException("No Content-Type specified"); return null; } MimeType mimeType = new MimeType(getContentType()); if (!(mimeType.match(APPLICATION_XML) || mimeType.match(TEXT_XML))) throw new UnsupportedMediaTypeException( "Expected Content-Type " + APPLICATION_XML + " or " + TEXT_XML); return getRequestDocument(); } catch (MimeTypeParseException e) { throw new UnsupportedMediaTypeException(e.getMessage()); } catch (IllegalArgumentException e) { Throwable cause = e.getCause(); String msg = cause != null ? cause.getMessage() : null; if (msg == null) msg = "Unknown error parsing request document"; throw new BadRequestException(msg); } }
From source file:org.unitedinternet.cosmo.dav.impl.StandardDavRequest.java
/** * /* w ww . j a va2 s. co m*/ * @param requireDocument boolean * @return Document * @throws CosmoDavException */ private Document getSafeRequestDocument(boolean requireDocument) throws CosmoDavException { try { if (StringUtils.isBlank(getContentType()) && requireDocument) { throw new BadRequestException("No Content-Type specified"); } MimeType mimeType = new MimeType(getContentType()); if (!(mimeType.match(APPLICATION_XML) || mimeType.match(TEXT_XML))) { throw new UnsupportedMediaTypeException( "Expected Content-Type " + APPLICATION_XML + " or " + TEXT_XML); } return getRequestDocument(); } catch (MimeTypeParseException e) { throw new UnsupportedMediaTypeException(e.getMessage()); } catch (IllegalArgumentException e) { throwBadRequestExceptionFrom(e); } catch (DavException e) { throwBadRequestExceptionFrom(e); } return null; }