List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource
public ByteArrayDataSource(String data, String type) throws IOException
From source file:org.apromore.service.impl.ProcessServiceImpl.java
/** * @see org.apromore.service.ProcessService#getBPMNRepresentation(String, Integer, String, Version) * {@inheritDoc}/*from w w w.ja va 2 s. co m*/ */ @Override public String getBPMNRepresentation(final String name, final Integer processId, final String branch, final Version version) throws RepositoryException { String xmlBPMNProcess; String format = "BPMN 2.0"; String annName = "BPMN 2.0"; try { // Debug tracing of the authenticated principal org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder .getContext().getAuthentication(); if (auth != null) { LOGGER.info("Authentication principal=" + auth.getPrincipal() + " details=" + auth.getDetails() + " thread=" + Thread.currentThread()); } else { LOGGER.info("Authentication is null"); } // Work out if we are looking at the original format or native format for this model. if (isRequestForNativeFormat(processId, branch, version, format)) { xmlBPMNProcess = nativeRepo.getNative(processId, branch, version.toString(), format).getContent(); LOGGER.info("native"); } else { LOGGER.info("notNative"); CanonicalProcessType cpt = getProcessModelVersion(processId, name, branch, version, false); Process process = processRepo.findOne(processId); DecanonisedProcess dp; AnnotationsType anf = null; Annotation ann = annotationRepo.getAnnotation(processId, branch, version.toString(), annName); if (ann != null) { String annotation = ann.getContent(); if (annotation != null && !annotation.equals("")) { ByteArrayDataSource dataSource = new ByteArrayDataSource(annotation, Constants.XML_MIMETYPE); anf = ANFSchema.unmarshalAnnotationFormat(dataSource.getInputStream(), false).getValue(); } } if (ann != null && !process.getNativeType().getNatType() .equalsIgnoreCase(ann.getNatve().getNativeType().getNatType())) { anf = annotationSrv.preProcess(ann.getNatve().getNativeType().getNatType(), format, cpt, anf); } else { anf = annotationSrv.preProcess(process.getNativeType().getNatType(), format, cpt, anf); } dp = canoniserSrv.deCanonise(format, cpt, anf, new HashSet<RequestParameterType<?>>()); xmlBPMNProcess = IOUtils.toString(dp.getNativeFormat(), "UTF-8"); } //LOGGER.info("[new method] PROCESS:\n" + xmlBPMNProcess); return xmlBPMNProcess; } catch (Exception e) { LOGGER.error("Failed to retrive the process!"); LOGGER.error("Original exception was: ", e); throw new RepositoryException(e); } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Computes the received content MIC and writes it to the message info object *///from w w w.j av a2s .c om public void computeReceivedContentMIC(byte[] rawMessageData, AS2Message message, Part partWithHeader, String contentType) throws Exception { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); boolean encrypted = messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE; boolean signed = messageInfo.getSignType() != AS2Message.SIGNATURE_NONE; boolean compressed = messageInfo.getCompressionType() != AS2Message.COMPRESSION_NONE; BCCryptoHelper helper = new BCCryptoHelper(); String sha1digestOID = helper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1); //compute the MIC if (signed) { //compute the content-type for the signed part. //If the message was not encrypted the content-type should simply be taken from the header //else we have to look into the part String singedPartContentType = null; if (!encrypted) { singedPartContentType = contentType; } else { InputStream dataIn = message.getDecryptedRawDataInputStream(); MimeBodyPart contentTypeTempPart = new MimeBodyPart(dataIn); dataIn.close(); singedPartContentType = contentTypeTempPart.getContentType(); } //ANY signed data //4.1 MIC Calculation For Signed Message //For any signed message, the MIC to be returned is calculated over //the same data that was signed in the original message as per [AS1]. //The signed content will be a mime bodypart that contains either //compressed or uncompressed data. MimeBodyPart signedPart = new MimeBodyPart(); signedPart.setDataHandler( new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType))); signedPart.setHeader("Content-Type", singedPartContentType); String digestOID = helper.getDigestAlgOIDFromSignature(signedPart); signedPart = null; String mic = helper.calculateMIC(partWithHeader, digestOID); String digestAlgorithmName = helper.convertOIDToAlgorithmName(digestOID); messageInfo.setReceivedContentMIC(mic + ", " + digestAlgorithmName); } else if (!signed && !compressed && !encrypted) { //uncompressed, unencrypted, unsigned: plaintext mic //http://tools.ietf.org/html/draft-ietf-ediint-compression-12 //4.3 MIC Calculation For Unencrypted, Unsigned Message //For unsigned, unencrypted messages, the MIC is calculated //over the uncompressed data content including all MIME header //fields and any applied Content-Transfer-Encoding. String mic = helper.calculateMIC(rawMessageData, sha1digestOID); messageInfo.setReceivedContentMIC(mic + ", sha1"); } else if (!signed && compressed && !encrypted) { //compressed, unencrypted, unsigned: uncompressed data mic //http://tools.ietf.org/html/draft-ietf-ediint-compression-12 //4.3 MIC Calculation For Unencrypted, Unsigned Message //For unsigned, unencrypted messages, the MIC is calculated //over the uncompressed data content including all MIME header //fields and any applied Content-Transfer-Encoding. String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID); messageInfo.setReceivedContentMIC(mic + ", sha1"); } else if (!signed && encrypted) { //http://tools.ietf.org/html/draft-ietf-ediint-compression-12 //4.2 MIC Calculation For Encrypted, Unsigned Message //For encrypted, unsigned messages, the MIC to be returned is //calculated over the uncompressed data content including all //MIME header fields and any applied Content-Transfer-Encoding. String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID); messageInfo.setReceivedContentMIC(mic + ", sha1"); } else { //this should never happen: String mic = helper.calculateMIC(partWithHeader, sha1digestOID); messageInfo.setReceivedContentMIC(mic + ", sha1"); } }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
/** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail>//from ww w.ja v a 2s . co m * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; if (bodyPart.getLocalName().equals("text")) { // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; } else if (bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; } else if (bodyPart.getLocalName().equals("generic")) { // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); } // Now, time to store it if (content != null && contentType != null && contentType.length() > 0) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (attachments.size() > 0) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Returns the signed part of the passed data or null if the data is not detected to be signed*/ public Part getSignedPart(byte[] data, String contentType) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); MimeBodyPart possibleSignedPart = new MimeBodyPart(); possibleSignedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); possibleSignedPart.setHeader("content-type", contentType); return (helper.getSignedEmbeddedPart(possibleSignedPart)); }
From source file:org.pentaho.di.trans.steps.mail.Mail.java
private void addAttachedContent(String filename, String fileContent) throws Exception { // create a data source MimeBodyPart mbp = new MimeBodyPart(); // get a data Handler to manipulate this file type; mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(fileContent.getBytes(), "application/x-any"))); // include the file in the data source mbp.setFileName(filename);/*from w w w. ja v a 2 s. co m*/ // add the part with the file in the BodyPart(); data.parts.addBodyPart(mbp); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed signed part*/ public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType, X509Certificate certificate) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); String signatureTransferEncoding = null; MimeMultipart checkPart = (MimeMultipart) signedPart.getContent(); //it is sure that it is a signed part: set the type to multipart if the //parser has problems parsing it. Don't know why sometimes a parsing fails for //MimeBodyPart. This check looks if the parser is able to find more than one subpart if (checkPart.getCount() == 1) { MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType)); MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null)); possibleSignedMessage.setContent(multipart, multipart.getContentType()); possibleSignedMessage.saveChanges(); //overwrite the formerly found signed part signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage); }// w ww . j a v a2s . c o m //get the content encoding of the signature MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent(); //body part 1 is always the signature String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding"); if (encodingHeader != null) { signatureTransferEncoding = encodingHeader[0]; } return (helper.verify(signedPart, signatureTransferEncoding, certificate)); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed message. If the transfer mode is unencrypted/unsigned, a new Bodypart will be constructed *@return the payload part, this is important to compute the MIC later *///from w w w. j a v a 2 s. co m private Part verifySignature(AS2Message message, Partner sender, String contentType) throws Exception { if (this.certificateManagerSignature == null) { throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "AS2MessageParser.verifySignature: pass a certification manager for the signature before calling verifySignature()", message); } AS2Info as2Info = message.getAS2Info(); if (!as2Info.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) as2Info; if (messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { InputStream memIn = message.getDecryptedRawDataInputStream(); MimeBodyPart testPart = new MimeBodyPart(memIn); memIn.close(); contentType = testPart.getContentType(); } } Part signedPart = this.getSignedPart(message.getDecryptedRawData(), contentType); //part is NOT signed but is defined to be signed if (signedPart == null) { as2Info.setSignType(AS2Message.SIGNATURE_NONE); if (as2Info.isMDN()) { this.logger.log(Level.INFO, this.rb.getResourceString("mdn.notsigned", as2Info.getMessageId()), as2Info); //MDN is not signed but should be signed if (sender.isSignedMDN()) { this.logger.log(Level.SEVERE, this.rb.getResourceString("mdn.unsigned.error", new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info); } } else { this.logger.log(Level.INFO, this.rb.getResourceString("msg.notsigned", as2Info.getMessageId()), as2Info); } if (!as2Info.isMDN() && sender.getSignType() != AS2Message.SIGNATURE_NONE) { throw new AS2Exception(AS2Exception.INSUFFICIENT_SECURITY_ERROR, "Incoming messages from AS2 partner " + sender.getAS2Identification() + " are defined to be signed.", message); } //if the message has been unsigned it is required to set a new datasource MimeBodyPart unsignedPart = new MimeBodyPart(); unsignedPart.setDataHandler( new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType))); unsignedPart.setHeader("content-type", contentType); return (unsignedPart); } else { //it is definitly a signed mdn if (as2Info.isMDN()) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("mdn.signed", as2Info.getMessageId()), as2Info); } as2Info.setSignType(this.getDigestFromSignature(signedPart)); //MDN is signed but shouldn't be signed' if (!sender.isSignedMDN()) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("mdn.signed.error", new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info); } } } else { //its no MDN, its a AS2 message if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("msg.signed", as2Info.getMessageId()), as2Info); } int signDigest = this.getDigestFromSignature(signedPart); String digest = null; if (signDigest == AS2Message.SIGNATURE_SHA1) { digest = "SHA1"; } else if (signDigest == AS2Message.SIGNATURE_MD5) { digest = "MD5"; } as2Info.setSignType(signDigest); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("signature.analyzed.digest", new Object[] { as2Info.getMessageId(), digest }), as2Info); } } } MimeBodyPart payloadPart = null; try { String signAlias = this.certificateManagerSignature .getAliasByFingerprint(sender.getSignFingerprintSHA1()); payloadPart = this.verifySignedPartUsingAlias(message, signAlias, signedPart, contentType); } catch (AS2Exception e) { //retry to verify the signature with the second certificate if this is possible String secondAlias = this.certificateManagerSignature .getAliasByFingerprint(sender.getSignFingerprintSHA1(2)); if (secondAlias != null) { payloadPart = this.verifySignedPartUsingAlias(message, secondAlias, signedPart, contentType); } else { throw e; } } return (payloadPart); }
From source file:nl.nn.adapterframework.http.HttpSender.java
protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters, ParameterResolutionContext prc) throws SenderException, MessagingException, IOException { MyMimeMultipart mimeMultipart = new MyMimeMultipart("related"); String start = null;//from w w w .j a v a 2s. co m if (StringUtils.isNotEmpty(getInputMessageParam())) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\""); start = "<" + getInputMessageParam() + ">"; mimeBodyPart.setContentID(start); ; mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value [" + message + "]"); } if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); String name = pv.getDefinition().getName(); if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) { Object value = pv.getValue(); if (value instanceof FileInputStream) { FileInputStream fis = (FileInputStream) value; String fileName = null; String sessionKey = pv.getDefinition().getSessionKey(); if (sessionKey != null) { fileName = (String) prc.getSession().get(sessionKey + "Name"); } MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(fileName); mimeBodyPart.setContentID("<" + name + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value + "] and name [" + fileName + "]"); } else { throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass() + "] for parameter [" + name + "]"); } } else { String value = pv.asStringValue(""); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(value, "text/xml"); if (start == null) { start = "<" + name + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + name + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug( getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]"); } } } if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) { String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey()); if (StringUtils.isEmpty(multipartXml)) { log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty"); } else { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { throw new SenderException(getLogPrefix() + "error building multipart xml", e); } Collection parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]"); } else { int c = 0; Iterator iter = parts.iterator(); while (iter.hasNext()) { c++; Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partMimeType = partElement.getAttribute("mimeType"); String partSessionKey = partElement.getAttribute("sessionKey"); Object partObject = prc.getSession().get(partSessionKey); if (partObject instanceof FileInputStream) { FileInputStream fis = (FileInputStream) partObject; MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, (partMimeType == null ? "application/octet-stream" : partMimeType)); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(partName); mimeBodyPart.setContentID("<" + partName + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { String partValue = (String) prc.getSession().get(partSessionKey); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(partValue, "text/xml"); if (start == null) { start = "<" + partName + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + partName + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey + "] with value [" + partValue + "]"); } } } } } MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties())); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream()); hmethod.setRequestEntity(request); String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\""; Header header = new Header("Content-Type", contentTypeMtom); hmethod.addRequestHeader(header); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Decrypts the data of a message with all given certificates etc * @param info MessageInfo, the encryption algorith will be stored in the encryption type of this info * @param rawMessageData encrypted data, will be decrypted * @param contentType contentType of the data * @param privateKey receivers private key * @param certificate receivers certificate */// www. ja v a 2 s . co m public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver, X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception { AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info(); MimeBodyPart encryptedBody = new MimeBodyPart(); encryptedBody.setHeader("content-type", contentType); encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); RecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver); SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody); BCCryptoHelper helper = new BCCryptoHelper(); String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID()); if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) { info.setEncryptionType(AS2Message.ENCRYPTION_3DES); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) { info.setEncryptionType(AS2Message.ENCRYPTION_DES); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) { info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_128); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_192); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_256); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) { info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN); } else { info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM); } RecipientInformationStore recipients = enveloped.getRecipientInfos(); enveloped = null; encryptedBody = null; RecipientInformation recipient = recipients.get(recipientId); if (recipient == null) { //give some details about the required and used cert for the decryption Collection recipientList = recipients.getRecipients(); Iterator iterator = recipientList.iterator(); while (iterator.hasNext()) { RecipientInformation recipientInfo = (RecipientInformation) iterator.next(); if (this.logger != null) { this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired", new Object[] { info.getMessageId(), recipientInfo.getRID() }), info); } } if (this.logger != null) { this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.infoassigned", new Object[] { info.getMessageId(), receiverCryptAlias, recipientId }), info); } throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR, "Error decrypting the message: Recipient certificate does not match.", message); } //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses //far more memory. InputStream contentStream = recipient .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC")) .getContentStream(); //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream(); //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_", ".mem", null); this.copyStreams(contentStream, decryptedOutput); decryptedOutput.flush(); decryptedOutput.close(); contentStream.close(); byte[] decryptedData = null; //size of the data was < than the threshold if (decryptedOutput.isInMemory()) { decryptedData = decryptedOutput.getData(); } else { //data has been written to a temp file: reread and return ByteArrayOutputStream memOut = new ByteArrayOutputStream(); decryptedOutput.writeTo(memOut); memOut.flush(); memOut.close(); //finally delete the temp file boolean deleted = decryptedOutput.getFile().delete(); decryptedData = memOut.toByteArray(); } if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("decryption.done.alias", new Object[] { info.getMessageId(), receiverCryptAlias, this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }), info); } return (decryptedData); }
From source file:cl.cnsv.wsreporteproyeccion.service.ReporteProyeccionServiceImpl.java
@Override public OutputObtenerCotizacionInternetVO obtenerCotizacionInternet(InputObtenerCotizacionInternetVO input) { //<editor-fold defaultstate="collapsed" desc="Inicio"> LOGGER.info("Iniciando el metodo obtenerCotizacionInternet..."); OutputObtenerCotizacionInternetVO output = new OutputObtenerCotizacionInternetVO(); String codigo;/*from w w w . j a v a2 s . co m*/ String mensaje; XStream xStream = new XStream(); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Validacion de entrada"> OutputVO outputValidacion = validator.validarObtenerCotizacionInternet(input); if (!Integer.valueOf(Propiedades.getFuncProperty("codigo.ok")).equals(outputValidacion.getCodigo())) { codigo = Integer.toString(outputValidacion.getCodigo()); mensaje = outputValidacion.getMensaje(); LOGGER.info(mensaje); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ir a JasperServer"> String numeroCotizacion = input.getNumeroCotizacion(); InputCotizacionInternet inputCotizacionInternet = new InputCotizacionInternet(); inputCotizacionInternet.setIdCotizacion(numeroCotizacion); String xmlInputCotizacionInternet = xStream.toXML(inputCotizacionInternet); LOGGER.info("Llamado a jasperserver: \n" + xmlInputCotizacionInternet); servicioJasperServer = new ServicioJasperServerJerseyImpl(); ResultadoDocumentoVO outputJasperServer; try { outputJasperServer = servicioJasperServer.buscarArchivoByCotizacion(inputCotizacionInternet); String xmlOutputJasperServer = xStream.toXML(outputJasperServer); LOGGER.info("Respuesta de jasperserver: \n" + xmlOutputJasperServer); String codigoJasperServer = outputJasperServer.getCodigo(); if (!Propiedades.getFuncProperty("jasperserver.ok.codigo").equals(codigoJasperServer)) { codigo = Propiedades.getFuncProperty("jasperserver.error.codigo"); mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje"); LOGGER.info(mensaje + ": " + outputJasperServer.getMensaje()); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } } catch (Exception e) { codigo = Propiedades.getFuncProperty("jasperserver.error.codigo"); mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ir a buscar datos email al servicio cotizador vida"> ClienteServicioCotizadorVida clienteCotizadorVida; try { clienteCotizadorVida = new ClienteServicioCotizadorVida(); } catch (Exception e) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //Se busca el nombre del asegurado, glosa del plan y numero de propuesta LOGGER.info("Llamado a getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlInputCotizacionInternet); OutputEmailCotizacionInternetVO outputEmail; try { outputEmail = clienteCotizadorVida.getDatosEmailCotizacionInternet(inputCotizacionInternet); String xmlOutputEmail = xStream.toXML(outputEmail); LOGGER.info("Respuesta de getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlOutputEmail); String codigoOutputEmail = outputEmail.getCodigo(); if (!Propiedades.getFuncProperty("ws.cotizadorvida.codigo.ok").equals(codigoOutputEmail)) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje"); LOGGER.info(mensaje + ": " + outputEmail.getMensaje()); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } } catch (Exception e) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Enviar correo con documento adjunto"> String documento = outputJasperServer.getDocumento(); try { EmailVO datosEmail = outputEmail.getDatosEmail(); String htmlBody = Propiedades.getFuncProperty("email.html"); String nombreAsegurable = datosEmail.getNombreAsegurable(); if (nombreAsegurable == null) { nombreAsegurable = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[NOMBRE_ASEGURADO]", nombreAsegurable); String glosaPlan = datosEmail.getGlosaPlan(); if (glosaPlan == null) { glosaPlan = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[GLOSA_PLAN]", glosaPlan); String numeroPropuesta = datosEmail.getNumeroPropuesta(); if (numeroPropuesta == null) { numeroPropuesta = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[NRO_PROPUESTA]", numeroPropuesta); //Parametrizar imagenes String imgBulletBgVerde = Propiedades.getFuncProperty("email.images.bulletbgverde"); if (imgBulletBgVerde == null) { imgBulletBgVerde = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_BULLET_BG_VERDE]", imgBulletBgVerde); String imgFace = Propiedades.getFuncProperty("email.images.face"); if (imgFace == null) { imgFace = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FACE]", imgFace); String imgTwitter = Propiedades.getFuncProperty("email.images.twitter"); if (imgTwitter == null) { imgTwitter = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_TWITTER]", imgTwitter); String imgYoutube = Propiedades.getFuncProperty("email.images.youtube"); if (imgYoutube == null) { imgYoutube = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_YOUTUBE]", imgYoutube); String imgMail15 = Propiedades.getFuncProperty("email.images.mail00115"); if (imgMail15 == null) { imgMail15 = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00115]", imgMail15); String imgFono = Propiedades.getFuncProperty("email.images.fono"); if (imgFono == null) { imgFono = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FONO]", imgFono); String imgMail16 = Propiedades.getFuncProperty("email.images.mail00116"); if (imgMail16 == null) { imgMail16 = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00116]", imgMail16); byte[] attachmentData = Base64.decodeBase64(documento); final String username = Propiedades.getKeyProperty("email.username"); final String encryptedPassword = Propiedades.getKeyProperty("email.password"); String privateKeyFile = Propiedades.getConfProperty("KEY"); CryptoUtil cryptoUtil = new CryptoUtil("", privateKeyFile); final String password = cryptoUtil.decryptData(encryptedPassword); final String auth = Propiedades.getFuncProperty("email.auth"); final String starttls = Propiedades.getFuncProperty("email.starttls"); final String host = Propiedades.getFuncProperty("email.host"); final String port = Propiedades.getFuncProperty("email.port"); //Log de datos de correo String strDatosCorreo = "username: " + username + "\n" + "auth: " + auth + "\n" + "host: " + host + "\n"; LOGGER.info("Datos correo: \n".concat(strDatosCorreo)); Properties props = new Properties(); props.put("mail.smtp.auth", auth); if (!"0".equals(starttls)) { props.put("mail.smtp.starttls.enable", starttls); } props.put("mail.smtp.host", host); if (!"0".equals(port)) { props.put("mail.smtp.port", port); } Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); String fileName = Propiedades.getFuncProperty("tmp.cotizacionInternet.file.name"); fileName = fileName.replaceAll("%s", numeroPropuesta); fileName = fileName + ".pdf"; // creates a new e-mail message Message msg = new MimeMessage(session); String from = Propiedades.getFuncProperty("email.from"); msg.setFrom(new InternetAddress(from)); //TODO considerar email de prueba o email del asegurado String emailTo; if ("1".equals(Propiedades.getFuncProperty("email.to.test"))) { emailTo = Propiedades.getFuncProperty("email.to.mail"); } else { emailTo = datosEmail.getEmail(); } InternetAddress[] toAddresses = { new InternetAddress(emailTo) }; msg.setRecipients(Message.RecipientType.TO, toAddresses); String subject = Propiedades.getFuncProperty("email.subject"); msg.setSubject(subject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(htmlBody, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments MimeBodyPart attachPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachmentData, "application/pdf"); attachPart.setDataHandler(new DataHandler(dataSource)); attachPart.setFileName(fileName); multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); } catch (Exception ex) { codigo = Propiedades.getFuncProperty("email.error.codigo"); mensaje = Propiedades.getFuncProperty("email.error.mensaje"); LOGGER.error(mensaje + ": " + ex.getMessage(), ex); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Termino"> codigo = Propiedades.getFuncProperty("codigo.ok"); mensaje = Propiedades.getFuncProperty("mensaje.ok"); output.setCodigo(codigo); output.setMensaje(mensaje); return output; //</editor-fold> }