private void doit() { DataFlavor xfer_flavors[]; Object content = null; // now let's create a DataHandler dh = new DataHandler(fds); dh.setCommandMap(cmdMap); System.out.println("DCHTest2: DataHandler created"); // get the dataflavors xfer_flavors = dh.getTransferDataFlavors(); System.out.println( "DCHTest2: dh.getTransferDF returned " + xfer_flavors.length + " data flavors."); // get the content: try { content = dh.getContent(); } catch (Exception e) { e.printStackTrace(); } if (content == null) System.out.println("DCHTest2: no content to be had!!!"); else System.out.println( "DCHTest2: got content of the following type: " + content.getClass().getName()); }
public void overwriteTemplate(Template template) throws CoreException { try { // get the directory String projectName = folderSelected.getProject().getName(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(projectName); IPath pathFolder = folderSelected.getProjectRelativePath(); String templateFileName = template.getFileName(); DataHandler dh = template.getContent(); InputStream is = dh.getInputStream(); IPath pathNewFile = pathFolder.append(templateFileName); IFile newFile = project.getFile(pathNewFile); // create new File if (newFile.exists()) { newFile.delete(true, null); } newFile.create(is, true, null); // set the dirty property to true newFile.setPersistentProperty(SpagoBIStudioConstants.DIRTY_MODEL, "true"); } catch (IOException e1) { MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Error in writing the file"); logger.error("Error in writing the file", e1); return; } }
/** * Sets the filename associated with this body part. * * @exception IllegalWriteException if the underlying implementation does not support modification * @exception IllegalStateException if this body part is obtained from a READ_ONLY folder */ public void setFileName(String filename) throws MessagingException { PrivilegedAction a = new GetSystemPropertyAction("mail.mime.encodefilename"); if ("true".equals(AccessController.doPrivileged(a))) { try { filename = MimeUtility.encodeText(filename); } catch (UnsupportedEncodingException e) { throw new MessagingException(e.getMessage(), e); } } String header = getHeader(CONTENT_DISPOSITION_NAME, null); if (header == null) { header = "attachment"; } ContentDisposition cd = new ContentDisposition(header); cd.setParameter("filename", filename); setHeader(CONTENT_DISPOSITION_NAME, cd.toString()); // We will also set the "name" parameter of the Content-Type field // to preserve compatibility with nonconformant MUAs header = getHeader(CONTENT_TYPE_NAME, null); if (header == null) { DataHandler dh0 = getDataHandler(); if (dh0 != null) header = dh0.getContentType(); else header = "text/plain"; } try { ContentType contentType = new ContentType(header); contentType.setParameter("name", filename); setHeader(CONTENT_TYPE_NAME, contentType.toString()); } catch (ParseException e) { } }
public void downloadBAMTool(String toolName, HttpServletResponse response) throws BAMToolboxDepolyerServiceBAMToolboxDeploymentExceptionException { try { ServletOutputStream out = response.getOutputStream(); DataHandler downloadData = stub.downloadToolBox(toolName); if (downloadData != null) { String fileName = ""; if (!toolName.endsWith(".tbox")) { fileName = toolName + ".tbox"; } else fileName = toolName; response.setHeader("Content-Disposition", "fileName=" + fileName); response.setContentType(downloadData.getContentType()); InputStream in = downloadData.getDataSource().getInputStream(); int nextChar; while ((nextChar = in.read()) != -1) { out.write((char) nextChar); } out.flush(); in.close(); } else { out.write("The requested service archive was not found on the server".getBytes()); } } catch (RemoteException e) { log.error(e.getMessage(), e); throw new BAMToolboxDepolyerServiceBAMToolboxDeploymentExceptionException(e); } catch (IOException e) { log.error(e.getMessage(), e); throw new BAMToolboxDepolyerServiceBAMToolboxDeploymentExceptionException(e); } }
@SuppressWarnings("unchecked") public void process(Exchange exchange) throws Exception { CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class); // verify request assertEquals(1, in.getBody().size()); Map<String, String> ns = new HashMap<String, String>(); ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS); ns.put("xop", MtomTestHelper.XOP_NS); XPathUtils xu = new XPathUtils(ns); Element body = new XmlConverter().toDOMElement(in.getBody().get(0)); Element ele = (Element) xu.getValue("//ns:Detail/ns:photo/xop:Include", body, XPathConstants.NODE); String photoId = ele.getAttribute("href").substring(4); // skip "cid:" assertEquals(MtomTestHelper.REQ_PHOTO_CID, photoId); ele = (Element) xu.getValue("//ns:Detail/ns:image/xop:Include", body, XPathConstants.NODE); String imageId = ele.getAttribute("href").substring(4); // skip "cid:" assertEquals(MtomTestHelper.REQ_IMAGE_CID, imageId); DataHandler dr = exchange.getIn().getAttachment(photoId); assertEquals("application/octet-stream", dr.getContentType()); MtomTestHelper.assertEquals( MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream())); dr = exchange.getIn().getAttachment(imageId); assertEquals("image/jpeg", dr.getContentType()); MtomTestHelper.assertEquals( MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream())); // create response List<Source> elements = new ArrayList<Source>(); elements.add( new DOMSource( DOMUtils.readXml(new StringReader(MtomTestHelper.RESP_MESSAGE)) .getDocumentElement())); CxfPayload<SoapHeader> sbody = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null); exchange.getOut().setBody(sbody); exchange .getOut() .addAttachment( MtomTestHelper.RESP_PHOTO_CID, new DataHandler( new ByteArrayDataSource( MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream"))); exchange .getOut() .addAttachment( MtomTestHelper.RESP_IMAGE_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg"))); }
private static String addStudyPOIsAndGetPatientID( List<ParticipantObjectIdentification> studyPOIs, RetrieveDocumentSetResponseType rsp) { Attributes attrs = null; String studyIUID, classUID; HashMap<String, HashMap<String, List<String>>> studySopClassMap = new HashMap<String, HashMap<String, List<String>>>(); HashMap<String, List<String>> sopClassInstanceMap; List<String> instances; for (DocumentResponse doc : rsp.getDocumentResponse()) { BufferedInputStream is = null; DicomInputStream dis = null; try { DataHandler dh = doc.getDocument(); is = new BufferedInputStream(dh.getInputStream(), BUF_SIZE); is.mark(BUF_SIZE); dis = new DicomInputStream(new BufferedInputStream(is)); attrs = dis.readDataset(-1, Tag.SeriesInstanceUID); is.reset(); doc.setDocument(new DataHandler(new InputStreamDataSource(is, dh.getContentType()))); studyIUID = attrs.getString(Tag.StudyInstanceUID); classUID = attrs.getString(Tag.SOPClassUID); sopClassInstanceMap = studySopClassMap.get(studyIUID); if (sopClassInstanceMap == null) { sopClassInstanceMap = new HashMap<String, List<String>>(); studySopClassMap.put(studyIUID, sopClassInstanceMap); instances = null; } else { instances = sopClassInstanceMap.get(classUID); } if (instances == null) { instances = new ArrayList<String>(); sopClassInstanceMap.put(classUID, instances); } instances.add(attrs.getString(Tag.SOPInstanceUID)); } catch (IOException x) { log.warn("Failed to read DICOM attachment! instanceUID:" + doc.getDocumentUniqueId(), x); } } for (Entry<String, HashMap<String, List<String>>> e : studySopClassMap.entrySet()) { ParticipantObjectDescription pod = new ParticipantObjectDescription(); studyPOIs.add(createStudyPOI(e.getKey(), pod)); for (Entry<String, List<String>> e1 : e.getValue().entrySet()) { SOPClass sc = new SOPClass(); sc.setUID(e1.getKey()); sc.setNumberOfInstances(e1.getValue().size()); for (String iuid : e1.getValue()) { Instance inst = new Instance(); inst.setUID(iuid); sc.getInstance().add(inst); } pod.getSOPClass().add(sc); } } return attrs == null ? null : attrs.getString(Tag.PatientID); }
public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException { Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingSwA"); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); ServiceClient sender = new ServiceClient(); sender.setOptions(options); OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); MessageContext mc = new MessageContext(); System.out.println("Sending file : " + fileName + " as SwA"); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); String attachmentID = mc.addAttachment(dataHandler); SOAPFactory factory = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope env = factory.getDefaultEnvelope(); OMNamespace ns = factory.createOMNamespace("http://services.samples/xsd", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns); OMElement request = factory.createOMElement("request", ns); OMElement imageId = factory.createOMElement("imageId", ns); imageId.setText(attachmentID); request.addChild(imageId); payload.addChild(request); env.getBody().addChild(payload); mc.setEnvelope(env); mepClient.addMessageContext(mc); mepClient.execute(true); MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = response.getEnvelope().getBody(); String imageContentId = body.getFirstChildWithName( new QName("http://services.samples/xsd", "uploadFileUsingSwAResponse")) .getFirstChildWithName(new QName("http://services.samples/xsd", "response")) .getFirstChildWithName(new QName("http://services.samples/xsd", "imageId")) .getText(); Attachments attachment = response.getAttachmentMap(); dataHandler = attachment.getDataHandler(imageContentId); File tempFile = File.createTempFile("swa-", ".gif"); FileOutputStream fos = new FileOutputStream(tempFile); dataHandler.writeTo(fos); fos.flush(); fos.close(); System.out.println("Saved response to file : " + tempFile.getAbsolutePath()); return response; }
@Override protected byte[] getBytes(Object object) { DataHandler handler = (DataHandler) object; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { InputStream stream = handler.getInputStream(); IOUtils.copy(stream, baos); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); }
/** * Parses the MimePart to create a DataSource. * * @param parent the parent multi-part * @param part the current part to be processed * @return the DataSource * @throws MessagingException creating the DataSource failed * @throws IOException creating the DataSource failed */ protected DataSource createDataSource(final Multipart parent, final MimePart part) throws MessagingException, IOException { final DataHandler dataHandler = part.getDataHandler(); final DataSource dataSource = dataHandler.getDataSource(); final String contentType = getBaseMimeType(dataSource.getContentType()); final byte[] content = this.getContent(dataSource.getInputStream()); final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType); final String dataSourceName = getDataSourceName(part, dataSource); result.setName(dataSourceName); return result; }
/** * Write binary attachment data from a {@link DataHandler}. * * @see XMLStreamWriterEx#writeBinary(DataHandler) */ public void writeBinary(final DataHandler data) throws XMLStreamException { // generate a unique id for the attachment final String id = "uuid:" + UUID.randomUUID().toString(); final DimeRecord dimeRecord = new DimeRecord(); dimeRecord.setContentId(id); dimeRecord.setData(data); if (data.getContentType() != null) { dimeRecord.setTypeNameFormat(TypeNameFormat.MEDIA_TYPE); dimeRecord.setContentType(data.getContentType()); } dimeMessage.add(dimeRecord); // write a reference to the SOAP message writeAttribute("href", id); }
private void manageAttachments(KpeopleAction action, DataHandler stream) throws IOException { InputStream is = null; String hashcode = null; try { is = stream.getInputStream(); hashcode = Hashcode.getHashcode(is, Hashcode.SHA512); } catch (IOException e) { e.printStackTrace(); throw e; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String path = (String) currentProperties.get(KpeopleLabel.getEventXMLPath()); try { path = ActionDataProcessorUtil.checkEventXMLPath(path); } catch (Exception e1) { e1.printStackTrace(); } FileOutputStream outputStream = null; File tmpFilePath = null; try { path = path + action.getIdAction() + "-" + fileName; tmpFilePath = new File(path); outputStream = new FileOutputStream(tmpFilePath); stream.writeTo(outputStream); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // ActionDataProcessorUtil.deleteEventFile(tmpFilePath); String idAttachmentId = Long.toString(action.getIdAction()) + "-" + hashcode.substring(0, 6); KpeopleAttachment attachment = new KpeopleAttachment(); attachment.setAttachmentName(fileName); attachment.setAttachmentHashcode(hashcode); attachment.setAttachmentData(path); attachment.setIdAttachment(idAttachmentId); attachment.setAttachmentType(eventResult.getContentType()); eventResult.addAttachment(attachment); }
// TODO common function see BpelUploader private void writeResource( DataHandler dataHandler, String destPath, String fileName, File bpelDest) throws IOException { File tempDestFile = new File(destPath, fileName); FileOutputStream fos = null; File destFile = new File(bpelDest, fileName); try { fos = new FileOutputStream(tempDestFile); /* File stream is copied to a temp directory in order handle hot deployment issue occurred in windows */ dataHandler.writeTo(fos); FileUtils.copyFile(tempDestFile, destFile); } catch (FileNotFoundException e) { log.error("Cannot find the file", e); throw e; } catch (IOException e) { log.error("IO error."); throw e; } finally { close(fos); } boolean isDeleted = tempDestFile.delete(); if (!isDeleted) { log.warn( "temp file: " + tempDestFile.getAbsolutePath() + " deletion failed, scheduled deletion on server exit."); tempDestFile.deleteOnExit(); } }
@Override public void storeArtifact( String applicationId, String version, String revision, DataHandler data, String fileName) throws AppFactoryException { String path = getApplicationStorageDirectoryPath(applicationId, version, revision) + File.separator + fileName; try { File destFile = new File(path); if (destFile.exists() == true) { destFile.delete(); } if (!destFile.getParentFile().exists()) { if (!destFile.getParentFile().mkdirs()) { throw new IOException("Failed to create directory structure."); } } FileOutputStream fileOutputStream = new FileOutputStream(destFile); data.writeTo(fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { log.error("Error storing the artifact file : " + e.getMessage(), e); throw new AppFactoryException("Error storing the artifact file : " + e.getMessage(), e); } }
public void addEndpointTemplate(DataHandler dh) throws IOException, XMLStreamException { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); // create the builder StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement endpointTemplate = builder.getDocumentElement(); endpointTemplateAdminStub.addEndpointTemplate(endpointTemplate.toString()); }
public java.io.InputStream getInputStream() throws OMException { if (isBinary) { if (dataHandlerObject == null) { getDataHandler(); } InputStream inStream; javax.activation.DataHandler dataHandler = (javax.activation.DataHandler) dataHandlerObject; try { inStream = dataHandler.getDataSource().getInputStream(); } catch (IOException e) { throw new OMException("Cannot get InputStream from DataHandler.", e); } return inStream; } else { throw new OMException("Unsupported Operation"); } }
public void addExistingConfiguration(DataHandler dh) throws IOException, LocalEntryAdminException, XMLStreamException { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement configSourceElem = builder.getDocumentElement(); configServiceAdminStub.addExistingConfiguration(configSourceElem.toString()); }
public DHResponse echoDataHandler(DHRequest request) { this.ensureInit(); DataHandler dataHandler = request.getDataHandler(); try { if (!dataHandler.getContentType().equals("text/plain")) { throw new WebServiceException("Wrong content type"); } if (!dataHandler.getContent().equals("some string")) { throw new WebServiceException("Wrong data"); } } catch (IOException e) { throw new WebServiceException(e); } DataHandler responseData = new DataHandler("Server data", "text/plain"); return new DHResponse(responseData); }
protected BodyPart getBodyPartForAttachment(DataHandler handler, String name) throws MessagingException { BodyPart part = new MimeBodyPart(); part.setDataHandler(handler); part.setDescription(name); part.setFileName(StringUtils.defaultString(handler.getName(), name)); return part; }
/** * adding sequence * * @param dh * @throws SequenceAdminServiceSequenceEditorException * @throws IOException * @throws XMLStreamException */ public void addSequence(DataHandler dh) throws SequenceAdminServiceSequenceEditorException, IOException, XMLStreamException { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); // create the builder StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement sequenceElem = builder.getDocumentElement(); sequenceAdminServiceStub.addSequence(sequenceElem); }
public void addLocalEntry(String sessionCookie, DataHandler dh) throws LocalEntryAdminException, IOException, XMLStreamException { AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub); XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); // create the builder StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement localEntryElem = builder.getDocumentElement(); localEntryAdminServiceStub.addEntry(localEntryElem.toString()); }
public void setCommandContext(String var1, DataHandler var2) throws IOException { InputStream var3 = var2.getInputStream(); ByteArrayOutputStream var4 = new ByteArrayOutputStream(); byte[] var5 = new byte[4096]; for (int var6 = var3.read(var5); var6 != -1; var6 = var3.read(var5)) { var4.write(var5, 0, var6); } var3.close(); String var7 = var4.toString(); this.setText(var7); }
private void manageDetails(final GetItemResponse response, final DataHandler stream) { InputStream is = null; ContentHandler contenthandler = new BodyContentHandler(); Metadata metadata = new Metadata(); // metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName()); Parser parser = new AutoDetectParser(); ParseContext context = new ParseContext(); try { is = stream.getInputStream(); parser.parse(is, contenthandler, metadata, context); is.close(); is.reset(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (TikaException e) { e.printStackTrace(); } String contentAuthorValue = metadata.get(Metadata.AUTHOR); String contentAuthorKey = currentProperties.getProperty(KpeopleLabel.getCorePropertiesAuthor()); if (contentAuthorValue != null) { eventResult.setDetail(contentAuthorKey, contentAuthorValue); } String contentCreationDateValue = metadata.get(Metadata.CREATION_DATE); String contentCreationDateKey = currentProperties.getProperty(KpeopleLabel.getCorePropertiesCreationDate()); if (contentCreationDateValue != null) { eventResult.setDetail(contentCreationDateKey, contentCreationDateValue); } String contentKeywordsValue = metadata.get(Metadata.KEYWORDS); String contentKeywordsKey = currentProperties.getProperty(KpeopleLabel.getCorePropertiesKeywords()); if (contentKeywordsValue != null) { eventResult.setDetail(contentKeywordsKey, contentKeywordsValue); } String[] names = metadata.names(); /* * for (int i = 0; i < names.length; i++) { * System.out.println(names[i]); } */ }
private byte[] getFileContent(SDKFile importExportSDKFile) throws NotAllowedOperationException { byte[] toReturn = null; logger.debug("IN"); int maxSize = ImportUtilities.getImportFileMaxSize(); logger.debug("Import/export file max size: " + maxSize); if (importExportSDKFile != null) { InputStream is = null; try { DataHandler dh = importExportSDKFile.getContent(); is = dh.getInputStream(); try { toReturn = SpagoBIUtilities.getByteArrayFromInputStream(is, maxSize); } catch (SecurityException e) { logger.error( "A security exception was thrown when getting import/export file content: file is too big", e); NotAllowedOperationException ex = new NotAllowedOperationException(); ex.setFaultString("File in input is too big"); throw ex; } } catch (NotAllowedOperationException e) { throw e; } catch (Exception e) { if (is != null) { try { is.close(); } catch (IOException ioe) { logger.error("Error closing input stream of attachment", ioe); } } throw new SpagoBIRuntimeException("Error while getting SDK file content", e); } finally { logger.debug("OUT"); } } return toReturn; }
/** * Updates the headers of this part, based on the content. * * @exception IllegalWriteException if the underlying implementation does not support modification * @exception IllegalStateException if this body part is obtained from a READ_ONLY folder */ protected void updateHeaders() throws MessagingException { if (getDataHandler() != null) { try { String contentType = dh.getContentType(); ContentType ct = new ContentType(contentType); if (ct.match("multipart/*")) { MimeMultipart mmp = (MimeMultipart) dh.getContent(); mmp.updateHeaders(); } else if (ct.match("message/rfc822")) { } else { // Update Content-Transfer-Encoding if (getHeader(CONTENT_TRANSFER_ENCODING_NAME) == null) { setHeader(CONTENT_TRANSFER_ENCODING_NAME, MimeUtility.getEncoding(dh)); } } // Update Content-Type if nonexistent, // and Content-Type "name" with Content-Disposition "filename" // parameter(see setFilename()) if (getHeader(CONTENT_TYPE_NAME) == null) { String disposition = getHeader(CONTENT_DISPOSITION_NAME, null); if (disposition != null) { ContentDisposition cd = new ContentDisposition(disposition); String filename = cd.getParameter("filename"); if (filename != null) { ct.setParameter("name", filename); contentType = ct.toString(); } } setHeader(CONTENT_TYPE_NAME, contentType); } } catch (IOException e) { throw new MessagingException("I/O error", e); } } }
public byte[] toGWT(DataHandler jaxbObject, GWTMappingContext context) throws GWTMappingException { if (jaxbObject == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { jaxbObject.writeTo(out); out.flush(); } catch (IOException e) { throw new GWTMappingException(e); } return out.toByteArray(); }
/** * Przy zwrocie wyniku translacji, zapisuje xliffa do pliku i zwraca go jako wynik. * * @param dh - wrapper dla przetłumaczonej treści */ public File saveResultFile(DataHandler dh) throws IOException { /* * File xliff = new File(getXliff()); String name = xliff.getName(); * name = name.replaceFirst(".old", ""); */ File xliffResult = new File(getXliff() + ".transl"); if (!xliffResult.exists()) xliffResult.createNewFile(); FileOutputStream out = new FileOutputStream(xliffResult); dh.writeTo(out); out.flush(); out.close(); return xliffResult; }
public static boolean writeData(DataHandler dh, long size, FileOutputStream out) throws IOException { byte[] dataBuf = new byte[4096]; long sizeCounter = 0; // FileOutputStream out = null; BufferedInputStream br = null; InputStream in = dh.getInputStream(); br = new BufferedInputStream(in); try { int numBytes; while ((numBytes = br.read(dataBuf)) != -1) { sizeCounter += numBytes; if (sizeCounter <= size) { out.write(dataBuf, 0, numBytes); } } } finally { br.close(); out.close(); } return true; }
/** * <b>function:</b>传递文件 * * @author hoojo * @createDate Dec 18, 2010 1:27:58 PM * @param handler DataHandler这个参数必须 * @param fileName 文件名称 * @return upload Info */ public String upload(DataHandler handler, String fileName) { if (fileName != null && !"".equals(fileName)) { File file = new File("D:/" + fileName); if (handler != null) { InputStream is = null; FileOutputStream fos = null; try { is = handler.getInputStream(); fos = new FileOutputStream(file); byte[] buff = new byte[1024 * 8]; int len = 0; while ((len = is.read(buff)) > 0) { fos.write(buff, 0, len); } } catch (FileNotFoundException e) { return "fileNotFound"; } catch (Exception e) { return "upload File failure"; } finally { try { if (fos != null) { fos.flush(); fos.close(); } if (is != null) { is.close(); } } catch (Exception e) { e.printStackTrace(); } } return "file absolute path:" + file.getAbsolutePath(); } else { return "handler is null"; } } else { return "fileName is null"; } }
@Override public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, MessagingException { MimeBodyPart mimeMessage; String contentType; Message camelMessage; Object content = null; if (headersInline) { mimeMessage = new MimeBodyPart(stream); camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); contentType = mimeMessage.getHeader(CONTENT_TYPE, null); // write the MIME headers not generated by javamail as Camel headers Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS); while (headersEnum.hasMoreElements()) { Object ho = headersEnum.nextElement(); if (ho instanceof Header) { Header header = (Header) ho; camelMessage.setHeader(header.getName(), header.getValue()); } } } else { // check if this a multipart at all. Otherwise do nothing contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class); if (contentType == null) { return stream; } try { ContentType ct = new ContentType(contentType); if (!ct.match("multipart/*")) { return stream; } } catch (ParseException e) { LOG.warn("Invalid Content-Type " + contentType + " ignored"); return stream; } camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(stream, bos); InternetHeaders headers = new InternetHeaders(); extractHeader(CONTENT_TYPE, camelMessage, headers); extractHeader(MIME_VERSION, camelMessage, headers); mimeMessage = new MimeBodyPart(headers, bos.toByteArray()); bos.close(); } DataHandler dh; try { dh = mimeMessage.getDataHandler(); if (dh != null) { content = dh.getContent(); contentType = dh.getContentType(); } } catch (MessagingException e) { LOG.warn("cannot parse message, no unmarshalling done"); } if (content instanceof MimeMultipart) { MimeMultipart mp = (MimeMultipart) content; content = mp.getBodyPart(0); for (int i = 1; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler()); @SuppressWarnings("unchecked") Enumeration<Header> headers = bp.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); camelAttachment.addHeader(header.getName(), header.getValue()); } camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment); } } if (content instanceof BodyPart) { BodyPart bp = (BodyPart) content; camelMessage.setBody(bp.getInputStream()); contentType = bp.getContentType(); if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) { camelMessage.setHeader(CONTENT_TYPE, contentType); ContentType ct = new ContentType(contentType); String charset = ct.getParameter("charset"); if (charset != null) { camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset)); } } } else { // If we find no body part, try to leave the message alone LOG.info("no MIME part found"); } return camelMessage; }
/** * Prepares the mediator for the invocation of an external script * * @param synCtx MessageContext script * @throws ScriptException For any errors , when compile the script */ protected synchronized void prepareExternalScript(MessageContext synCtx) throws ScriptException { // TODO: only need this synchronized method for dynamic registry entries. If there was a way // to access the registry entry during mediator initialization then for non-dynamic entries // this could be done just the once during mediator initialization. // Derive actual key from xpath expression or get static key String generatedScriptKey = key.evaluateValue(synCtx); Entry entry = synCtx.getConfiguration().getEntryDefinition(generatedScriptKey); boolean needsReload = (entry != null) && entry.isDynamic() && (!entry.isCached() || entry.isExpired()); synchronized (resourceLock) { if (scriptSourceCode == null || needsReload) { Object o = synCtx.getEntry(generatedScriptKey); if (o instanceof OMElement) { scriptSourceCode = ((OMElement) (o)).getText(); scriptEngine.eval(scriptSourceCode); } else if (o instanceof String) { scriptSourceCode = (String) o; scriptEngine.eval(scriptSourceCode); } else if (o instanceof OMText) { DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler(); if (dataHandler != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream())); scriptEngine.eval(reader); } catch (IOException e) { handleException("Error in reading script as a stream ", e, synCtx); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { handleException("Error in closing input stream ", e, synCtx); } } } } } } } // load <include /> scripts; reload each script if needed for (Value includeKey : includes.keySet()) { String includeSourceCode = (String) includes.get(includeKey); String generatedKey = includeKey.evaluateValue(synCtx); Entry includeEntry = synCtx.getConfiguration().getEntryDefinition(generatedKey); boolean includeEntryNeedsReload = (includeEntry != null) && includeEntry.isDynamic() && (!includeEntry.isCached() || includeEntry.isExpired()); synchronized (resourceLock) { if (includeSourceCode == null || includeEntryNeedsReload) { log.debug("Re-/Loading the include script with key " + includeKey); Object o = synCtx.getEntry(generatedKey); if (o instanceof OMElement) { includeSourceCode = ((OMElement) (o)).getText(); scriptEngine.eval(includeSourceCode); } else if (o instanceof String) { includeSourceCode = (String) o; scriptEngine.eval(includeSourceCode); } else if (o instanceof OMText) { DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler(); if (dataHandler != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream())); scriptEngine.eval(reader); } catch (IOException e) { handleException("Error in reading script as a stream ", e, synCtx); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { handleException("Error in closing input" + " stream ", e, synCtx); } } } } } } } } }