List of usage examples for javax.activation DataSource getContentType
public String getContentType();
From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java
@Override public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status) throws DAOException { try {/*w w w . j av a2s. c o m*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus transactionStatus) { try { Date timestamp = new Date(); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp, message.getMessageHeader().getCPAId(), message.getMessageHeader().getConversationId(), message.getMessageOrder() == null ? null : message.getMessageOrder().getSequenceNumber().getValue().longValue(), message.getMessageHeader().getMessageData().getMessageId(), message.getMessageHeader().getMessageData().getRefToMessageId(), message.getMessageHeader().getFrom().getRole(), message.getMessageHeader().getTo().getRole(), message.getMessageHeader().getService().getType(), message.getMessageHeader().getService().getValue(), message.getMessageHeader().getAction(), message.getOriginal(), XMLMessageBuilder.getInstance(SignatureType.class) .handle(new ObjectFactory().createSignature(message.getSignature())), XMLMessageBuilder.getInstance(MessageHeader.class) .handle(message.getMessageHeader()), XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()), XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()), XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()), XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()), status), keyHolder); for (DataSource attachment : message.getAttachments()) { simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name," + "content_type," + "content" + ") values (?,?,?,?)", keyHolder.getKey().longValue(), attachment.getName() == null ? Constants.DEFAULT_FILENAME : attachment.getName(), attachment.getContentType().split(";")[0].trim(), IOUtils.toByteArray(attachment.getInputStream())); } } catch (Exception e) { throw new RuntimeException(e); } } }); } catch (RuntimeException e) { throw new DAOException(e); } }
From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java
@Override public void insertMessage(final EbMSMessage message, final List<EbMSSendEvent> sendEvents) throws DAOException { try {/*from w w w . j av a2 s. c o m*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus transactionStatus) { try { Date timestamp = new Date(); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp, message.getMessageHeader().getCPAId(), message.getMessageHeader().getConversationId(), message.getMessageOrder() == null ? null : message.getMessageOrder().getSequenceNumber().getValue().longValue(), message.getMessageHeader().getMessageData().getMessageId(), message.getMessageHeader().getMessageData().getRefToMessageId(), message.getMessageHeader().getFrom().getRole(), message.getMessageHeader().getTo().getRole(), message.getMessageHeader().getService().getType(), message.getMessageHeader().getService().getValue(), message.getMessageHeader().getAction(), XMLMessageBuilder.getInstance(MessageHeader.class) .handle(message.getMessageHeader()), XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()), XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()), XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()), XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest())), keyHolder); for (DataSource attachment : message.getAttachments()) { simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name," + "content_type," + "content" + ") values (?,?,?,?)", keyHolder.getKey().longValue(), attachment.getName() == null ? Constants.DEFAULT_FILENAME : attachment.getName(), attachment.getContentType().split(";")[0].trim(), IOUtils.toByteArray(attachment.getInputStream())); } List<Object[]> events = new ArrayList<Object[]>(); for (EbMSSendEvent sendEvent : sendEvents) { //events.add(new Object[]{keyHolder.getKey().longValue(),String.format(getDateFormat(),sendEvent.getTime())}); events.add(new Object[] { keyHolder.getKey().longValue(), sendEvent.getTime() }); } simpleJdbcTemplate.batchUpdate( "insert into ebms_send_event (" + "ebms_message_id," + "time" + ") values (?,?)", events); } catch (Exception e) { throw new RuntimeException(e); } } }); } catch (RuntimeException e) { throw new DAOException(e); } }
From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java
@Override public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status, final EbMSMessageError messageError, final EbMSSendEvent sendEvent) throws DAOException { try {/*from w w w .j a v a 2 s .c om*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus transactionStatus) { try { Date timestamp = new Date(); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp, message.getMessageHeader().getCPAId(), message.getMessageHeader().getConversationId(), message.getMessageOrder() == null ? null : message.getMessageOrder().getSequenceNumber().getValue().longValue(), message.getMessageHeader().getMessageData().getMessageId(), message.getMessageHeader().getMessageData().getRefToMessageId(), message.getMessageHeader().getFrom().getRole(), message.getMessageHeader().getTo().getRole(), message.getMessageHeader().getService().getType(), message.getMessageHeader().getService().getValue(), message.getMessageHeader().getAction(), message.getOriginal(), XMLMessageBuilder.getInstance(SignatureType.class) .handle(new ObjectFactory().createSignature(message.getSignature())), XMLMessageBuilder.getInstance(MessageHeader.class) .handle(message.getMessageHeader()), XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()), XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()), XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()), XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()), status), keyHolder); for (DataSource attachment : message.getAttachments()) { simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name," + "content_type," + "content" + ") values (?,?,?,?)", keyHolder.getKey().longValue(), attachment.getName() == null ? Constants.DEFAULT_FILENAME : attachment.getName(), attachment.getContentType().split(";")[0].trim(), IOUtils.toByteArray(attachment.getInputStream())); } jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp, messageError.getMessageHeader().getCPAId(), messageError.getMessageHeader().getConversationId(), messageError.getMessageHeader().getMessageData().getMessageId(), messageError.getMessageHeader().getMessageData().getRefToMessageId(), messageError.getMessageHeader().getFrom().getRole(), messageError.getMessageHeader().getTo().getRole(), messageError.getMessageHeader().getService().getType(), messageError.getMessageHeader().getService().getValue(), messageError.getMessageHeader().getAction(), XMLMessageBuilder.getInstance(MessageHeader.class) .handle(messageError.getMessageHeader()), XMLMessageBuilder.getInstance(ErrorList.class).handle(messageError.getErrorList())), keyHolder); simpleJdbcTemplate.update( "insert into ebms_send_event (" + "ebms_message_id," + "time" + ") values (?,?)", keyHolder.getKey().longValue(), //String.format(getDateFormat(),sendEvent.getTime()) sendEvent.getTime()); } catch (Exception e) { throw new RuntimeException(e); } } }); } catch (RuntimeException e) { throw new DAOException(e); } }
From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java
@Override public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status, final EbMSAcknowledgment acknowledgment, final EbMSSendEvent sendEvent) throws DAOException { try {/*from w w w . j a va 2 s . c o m*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus transactionStatus) { try { Date timestamp = new Date(); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp, message.getMessageHeader().getCPAId(), message.getMessageHeader().getConversationId(), message.getMessageOrder() == null ? null : message.getMessageOrder().getSequenceNumber().getValue().longValue(), message.getMessageHeader().getMessageData().getMessageId(), message.getMessageHeader().getMessageData().getRefToMessageId(), message.getMessageHeader().getFrom().getRole(), message.getMessageHeader().getTo().getRole(), message.getMessageHeader().getService().getType(), message.getMessageHeader().getService().getValue(), message.getMessageHeader().getAction(), message.getOriginal(), XMLMessageBuilder.getInstance(SignatureType.class) .handle(new ObjectFactory().createSignature(message.getSignature())), XMLMessageBuilder.getInstance(MessageHeader.class) .handle(message.getMessageHeader()), XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()), XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()), XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()), XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()), status), keyHolder); for (DataSource attachment : message.getAttachments()) { simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name," + "content_type," + "content" + ") values (?,?,?,?)", keyHolder.getKey().longValue(), attachment.getName() == null ? Constants.DEFAULT_FILENAME : attachment.getName(), attachment.getContentType().split(";")[0].trim(), IOUtils.toByteArray(attachment.getInputStream())); } jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp, acknowledgment.getMessageHeader().getCPAId(), acknowledgment.getMessageHeader().getConversationId(), acknowledgment.getMessageHeader().getMessageData().getMessageId(), acknowledgment.getMessageHeader().getMessageData().getRefToMessageId(), acknowledgment.getMessageHeader().getFrom().getRole(), acknowledgment.getMessageHeader().getTo().getRole(), acknowledgment.getMessageHeader().getService().getType(), acknowledgment.getMessageHeader().getService().getValue(), acknowledgment.getMessageHeader().getAction(), XMLMessageBuilder.getInstance(MessageHeader.class) .handle(acknowledgment.getMessageHeader()), XMLMessageBuilder.getInstance(Acknowledgment.class) .handle(acknowledgment.getAcknowledgment())), keyHolder); simpleJdbcTemplate.update( "insert into ebms_send_event (" + "ebms_message_id," + "time" + ") values (?,?)", keyHolder.getKey().longValue(), //String.format(getDateFormat(),sendTime) sendEvent.getTime()); } catch (Exception e) { throw new RuntimeException(e); } } }); } catch (RuntimeException e) { throw new DAOException(e); } }
From source file:com.collabnet.tracker.core.TrackerWebServicesClient.java
/** * Attach a file to a PT artifact// w ww. j a v a 2 s . c o m * * @param taskId * @param comment * @param attachment * @throws ServiceException * @throws WSException * @throws RemoteException */ public long postAttachment(String taskId, String comment, DataSource attachment) throws ServiceException, WSException, RemoteException { EngineConfiguration config = mClient.getEngineConfiguration(); AttachmentService service = new AttachmentServiceLocator(config); URL portAddress = mClient.constructServiceURL("/tracker/Attachment"); AttachmentManager theService = service.getAttachmentService(portAddress); DataHandler attachmentHandler = new DataHandler(attachment); theService.addAttachment(taskId, attachment.getName(), comment, attachment.getContentType(), attachmentHandler); long[] ids = theService.getAttachmentIds(taskId); Arrays.sort(ids); return ids[ids.length - 1]; }
From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java
/** * A method that executes the reading of data from the email account to the * RBNB server after all configuration of settings, connections to hosts, * and thread initiatizing occurs. This method contains the detailed code * for reading the data and interpreting the data files. *///w w w . j a va2 s . com protected boolean execute() { logger.debug("StorXDispatcher.execute() called."); boolean failed = true; // indicates overall success of execute() boolean messageProcessed = false; // indicates per message success // declare the account properties that will be pulled from the // email.account.properties.xml file String accountName = ""; String server = ""; String username = ""; String password = ""; String protocol = ""; String dataMailbox = ""; String processedMailbox = ""; String prefetch = ""; // fetch data from each sensor in the account list List accountList = this.xmlConfiguration.getList("account.accountName"); for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) { int aIndex = accountList.indexOf(aIterator.next()); // populate the email connection variables from the xml properties // file accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName"); server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server"); username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username"); password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password"); protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol"); dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox"); processedMailbox = (String) this.xmlConfiguration .getProperty("account(" + aIndex + ").processedMailbox"); prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch"); logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n" + "prefetch : " + prefetch + "\n"); // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); try { // create the imaps mail session this.mailSession = Session.getDefaultInstance(props, null); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe) { try { // pause for 10 seconds logger.debug( "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry."); Thread.sleep(10000L); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe2) { logger.debug("There was an error connecting to the mail server. The " + "message was: " + nspe2.getMessage()); nspe2.printStackTrace(); failed = true; return !failed; } catch (InterruptedException ie) { logger.debug("The thread was interrupted: " + ie.getMessage()); failed = true; return !failed; } } try { this.mailStore.connect(server, username, password); // get folder references for the inbox and processed data box Folder inbox = mailStore.getFolder(dataMailbox); inbox.open(Folder.READ_WRITE); Folder processed = this.mailStore.getFolder(processedMailbox); processed.open(Folder.READ_WRITE); Message[] msgs; while (!inbox.isOpen()) { inbox.open(Folder.READ_WRITE); } msgs = inbox.getMessages(); List<Message> messages = new ArrayList<Message>(); Collections.addAll(messages, msgs); // sort the messages found in the inbox by date sent Collections.sort(messages, new Comparator<Message>() { public int compare(Message message1, Message message2) { int value = 0; try { value = message1.getSentDate().compareTo(message2.getSentDate()); } catch (MessagingException e) { e.printStackTrace(); } return value; } }); logger.debug("Number of messages: " + messages.size()); for (Message message : messages) { // Copy the message to ensure we have the full attachment MimeMessage mimeMessage = (MimeMessage) message; MimeMessage copiedMessage = new MimeMessage(mimeMessage); // determine the sensor serial number for this message String messageSubject = copiedMessage.getSubject(); Date sentDate = copiedMessage.getSentDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); // The subfolder of the processed mail folder (e.g. 2016-12); String destinationFolder = formatter.format(sentDate); logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber()); String[] subjectParts = messageSubject.split("\\s"); String loggerSerialNumber = "SerialNumber"; if (subjectParts.length > 1) { loggerSerialNumber = subjectParts[2]; } // Do we have a data attachment? If not, there's no data to // process if (copiedMessage.isMimeType("multipart/mixed")) { logger.debug("Message size: " + copiedMessage.getSize()); MimeMessageParser parser = new MimeMessageParser(copiedMessage); try { parser.parse(); } catch (Exception e) { logger.error("Failed to parse the MIME message: " + e.getMessage()); continue; } ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only logger.debug("Has attachments: " + parser.hasAttachments()); for (DataSource dataSource : parser.getAttachmentList()) { if (StringUtils.isNotBlank(dataSource.getName())) { logger.debug( "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), outputStream); messageAttachment = ByteBuffer.wrap(outputStream.toByteArray()); } } // We now have the attachment and serial number. Parse the attachment // for the data components, look up the storXSource based on the serial // number, and push the data to the DataTurbine // parse the binary attachment StorXParser storXParser = new StorXParser(messageAttachment); // iterate through the parsed framesMap and handle each // frame // based on its instrument type BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap(); Collection frameCollection = framesMap.getAll("/frames/frame"); Iterator framesIterator = frameCollection.iterator(); while (framesIterator.hasNext()) { BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next(); // logger.debug(frameMap.toXMLString(1000)); String frameType = (String) frameMap.get("type"); String sensorSerialNumber = (String) frameMap.get("serialNumber"); // handle each instrument type if (frameType.equals("HDR")) { logger.debug("This is a header frame. Skipping it."); } else if (frameType.equals("STX")) { try { // handle StorXSource StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber); // process the data using the StorXSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("SBE")) { try { // handle CTDSource CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber); // process the data using the CTDSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NLB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NDB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else { logger.debug("The frame type " + frameType + " is not recognized. Skipping it."); } } // end while() if (this.sourceMap.get(loggerSerialNumber) != null) { // Note: Use message (not copiedMessage) when setting flags if (!messageProcessed) { logger.info("Failed to process message: " + "Message Number: " + message.getMessageNumber() + " " + "Logger Serial:" + loggerSerialNumber); // leave it in the inbox, flagged as seen (read) message.setFlag(Flags.Flag.SEEN, true); logger.debug("Saw message " + message.getMessageNumber()); } else { // message processed successfully. Create a by-month sub folder if it doesn't exist // Copy the message and flag it deleted Folder destination = processed.getFolder(destinationFolder); boolean created = destination.create(Folder.HOLDS_MESSAGES); inbox.copyMessages(new Message[] { message }, destination); message.setFlag(Flags.Flag.DELETED, true); logger.debug("Deleted message " + message.getMessageNumber()); } // end if() } else { logger.debug("There is no configuration information for " + "the logger serial number " + loggerSerialNumber + ". Please add the configuration to the " + "email.account.properties.xml configuration file."); } // end if() } else { logger.debug("This is not a data email since there is no " + "attachment. Skipping it. Subject: " + messageSubject); } // end if() } // end for() // expunge messages and close the mail server store once we're // done inbox.expunge(); this.mailStore.close(); } catch (MessagingException me) { try { this.mailStore.close(); } catch (MessagingException me2) { failed = true; return !failed; } logger.info( "There was an error reading the mail message. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IOException me) { try { this.mailStore.close(); } catch (MessagingException me3) { failed = true; return !failed; } logger.info("There was an I/O error reading the message part. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IllegalStateException ese) { try { this.mailStore.close(); } catch (MessagingException me4) { failed = true; return !failed; } logger.info("There was an error reading messages from the folder. The " + "message was: " + ese.getMessage()); failed = true; return !failed; } finally { try { this.mailStore.close(); } catch (MessagingException me2) { logger.debug("Couldn't close the mail store: " + me2.getMessage()); } } } return !failed; }
From source file:de.innovationgate.wgpublisher.WGPDispatcher.java
private void writeRangesData(DataSource data, List<AcceptRange> ranges, HttpServletResponse response, String dbHint, long size) throws IOException, HttpErrorException, UnsupportedEncodingException { ServletOutputStream out = response.getOutputStream(); for (AcceptRange range : ranges) { InputStream in = data.getInputStream(); if (in == null) { throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint); }//from w w w. j a va 2s . co m if (ranges.size() != 1) { out.println(); out.println("--" + BYTERANGE_BOUNDARY); out.println("Content-Type: " + data.getContentType()); out.println("Content-Range: bytes " + range.from + "-" + range.to + "/" + size); out.println(); } if (range.from > 0) { in.skip(range.from); } try { WGUtils.inToOutLimited(in, out, (new Long(range.to - range.from + 1)).intValue(), 2048); out.flush(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } if (ranges.size() != 1) { out.println(); out.print("--" + BYTERANGE_BOUNDARY + "--"); out.flush(); } }
From source file:at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.SignedDocAttributeRequestProvider.java
public IPersonalAttributeList parse(HttpServletRequest httpReq) throws MOAIDException, UnsupportedAttributeException { Logger.debug("Beginning to extract OASIS-DSS response out of HTTP Request"); try {//from ww w . j a va 2s .c om String base64 = httpReq.getParameter("signresponse"); Logger.debug("signresponse url: " + httpReq.getRequestURI().toString()); Logger.debug("signresponse querystring: " + httpReq.getQueryString()); Logger.debug("signresponse method: " + httpReq.getMethod()); Logger.debug("signresponse content type: " + httpReq.getContentType()); Logger.debug("signresponse parameter:" + base64); String signResponseString = new String(Base64.decodeBase64(base64), "UTF8"); Logger.debug("RECEIVED signresponse:" + signResponseString); //create SignResponse object Source response = new StreamSource(new java.io.StringReader(signResponseString)); SignResponse signResponse = ApiUtils.unmarshal(response, SignResponse.class); //Check if Signing was successfully or not if (!signResponse.getResult().getResultMajor().equals(ResultMajor.RESULT_MAJOR_SUCCESS)) { //Pass unmodifed or unmarshal & marshal?? InputStream istr = ApiUtils.marshalToInputStream(signResponse); StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse with error (unmodified):" + signResponseString); istr.close(); } else { //extract doc from signresponse DataSource dataSource = LightweightSourceResolver.getDataSource(signResponse); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), baos); byte[] data = baos.toByteArray(); baos.close(); //update doc in DTL String docId, dssId = ""; docId = signResponse.getDocUI(); //For reference dssId equals docId dssId = docId; if (dssId != null && data != null) { boolean success = false; try { success = updateDocumentInDtl(data, docId, signResponseString); } catch (Exception e) {//No document service used? Logger.info("No document service used?"); e.printStackTrace(); success = false; } if (success) { // set the url in the SignResponse DocumentWithSignature documentWithSignature = new DocumentWithSignature(); DocumentType value = new DocumentType(); if (dtlUrl.endsWith("?wsdl")) { String tmp = dtlUrl.replace("?wsdl", ""); Logger.debug("DocumentUrl ends with ? wsdl, using " + tmp + " instead."); value.setDocumentURL(tmp); } else { value.setDocumentURL(dtlUrl); } documentWithSignature.setDocument(value); if (signResponse.getOptionalOutputs() != null) { //signResponse.getOptionalOutputs().getAny().add(documentWithSignature); for (Object o : signResponse.getOptionalOutputs().getAny()) { if (o instanceof DocumentWithSignature) { signResponse.getOptionalOutputs().getAny().remove(o); signResponse.getOptionalOutputs().getAny().add(documentWithSignature); break; } } } else { AnyType anytype = new AnyType(); anytype.getAny().add(documentWithSignature); signResponse.setOptionalOutputs(anytype); } // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl); InputStream istr = ApiUtils.marshalToInputStream(signResponse); StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse overwritten:" + signResponseString); istr.close(); } else { //No document service used? // do nothing.... //TODO temporary fix because document is deleted after fetching => SP can't download Doc //Add doc to Signresponse DocumentWithSignature documentWithSignature = new DocumentWithSignature(); DocumentType value = new DocumentType(); if (signResponse.getProfile().toLowerCase().contains("xades")) { value.setBase64XML(data); } else { Base64Data base64data = new Base64Data(); base64data.setValue(data); base64data.setMimeType(dataSource.getContentType()); value.setBase64Data(base64data); } documentWithSignature.setDocument(value); if (signResponse.getOptionalOutputs() != null) { //signResponse.getOptionalOutputs().getAny().add(documentWithSignature); for (Object o : signResponse.getOptionalOutputs().getAny()) { if (o instanceof DocumentWithSignature) { signResponse.getOptionalOutputs().getAny().remove(o); signResponse.getOptionalOutputs().getAny().add(documentWithSignature); break; } } } else { AnyType anytype = new AnyType(); anytype.getAny().add(documentWithSignature); signResponse.setOptionalOutputs(anytype); } // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl); InputStream istr = ApiUtils.marshalToInputStream(signResponse); StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse overwritten:" + signResponseString); istr.close(); } } else throw new Exception("No DSS id found."); } //alter signresponse //done List<String> values = new ArrayList<String>(); values.add(signResponseString); Logger.debug("Assembling signedDoc attribute"); PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, AttributeStatusType.AVAILABLE.value()); // pack and return the result PersonalAttributeList result = new PersonalAttributeList(); result.add(signedDocAttribute); return result; } catch (UnsupportedEncodingException e) { Logger.error("Failed to assemble signedDoc attribute"); throw new MOAIDException("stork.05", null); } catch (ApiUtilsException e) { e.printStackTrace(); Logger.error("Failed to assemble signedDoc attribute"); throw new MOAIDException("stork.05", null); } catch (IOException e) { e.printStackTrace(); Logger.error("Failed to assemble signedDoc attribute"); throw new MOAIDException("stork.05", null); } catch (Exception e) { e.printStackTrace(); Logger.error("Failed to assemble signedDoc attribute"); //throw new MOAIDException("stork.05", null); throw new UnsupportedAttributeException(); } }
From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java
public static EbMSMessageContent EbMSMessageToEbMSMessageContent(EbMSMessage message) throws IOException { List<EbMSAttachment> attachments = new ArrayList<EbMSAttachment>(); for (DataSource attachment : message.getAttachments()) attachments.add(new EbMSAttachment(attachment.getName(), attachment.getContentType(), IOUtils.toByteArray(attachment.getInputStream()))); return new EbMSMessageContent(new EbMSMessageContext(message.getMessageHeader()), attachments); }
From source file:org.apache.axis.attachments.AttachmentPart.java
/** * Gets the content of this <CODE>AttachmentPart</CODE> object * as a Java object. The type of the returned Java object * depends on (1) the <CODE>DataContentHandler</CODE> object * that is used to interpret the bytes and (2) the <CODE> * Content-Type</CODE> given in the header. * * <P>For the MIME content types "text/plain", "text/html" and * "text/xml", the <CODE>DataContentHandler</CODE> object does * the conversions to and from the Java types corresponding to * the MIME types. For other MIME types,the <CODE> * DataContentHandler</CODE> object can return an <CODE> * InputStream</CODE> object that contains the content data as * raw bytes.</P>/*from www.j a v a 2 s. c o m*/ * * <P>A JAXM-compliant implementation must, as a minimum, * return a <CODE>java.lang.String</CODE> object corresponding * to any content stream with a <CODE>Content-Type</CODE> * value of <CODE>text/plain</CODE> and a <CODE> * javax.xml.transform.StreamSource</CODE> object * corresponding to a content stream with a <CODE> * Content-Type</CODE> value of <CODE>text/xml</CODE>. For * those content types that an installed <CODE> * DataContentHandler</CODE> object does not understand, the * <CODE>DataContentHandler</CODE> object is required to * return a <CODE>java.io.InputStream</CODE> object with the * raw bytes.</P> * @return a Java object with the content of this <CODE> * AttachmentPart</CODE> object * @throws SOAPException if there is no content set * into this <CODE>AttachmentPart</CODE> object or if there * was a data transformation error */ public Object getContent() throws SOAPException { if (contentObject != null) { return contentObject; } if (datahandler == null) { throw new SOAPException(Messages.getMessage("noContent")); } javax.activation.DataSource ds = datahandler.getDataSource(); InputStream is = null; try { is = ds.getInputStream(); ; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new SOAPException(io); } if (ds.getContentType().equals("text/plain")) { try { byte[] bytes = new byte[is.available()]; IOUtils.readFully(is, bytes); return new String(bytes); } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new SOAPException(io); } } else if (ds.getContentType().equals("text/xml")) { return new StreamSource(is); } else if (ds.getContentType().equals("image/gif") || ds.getContentType().equals("image/jpeg")) { try { return ImageIOFactory.getImageIO().loadImage(is); } catch (Exception ex) { log.error(Messages.getMessage("javaIOException00"), ex); throw new SOAPException(ex); } } return is; }