public static void setAttachment(Message message, String filename) throws MessagingException { // Create a multipar message Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //Set File DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); //Add "file part" to multipart multipart.addBodyPart(messageBodyPart); //Set multipart to message message.setContent(multipart); }
private static Message buildMessage(Session session, String from, String recipients, String subject, String text, String filename) throws MessagingException, AddressException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); message.setSubject(subject); BodyPart messageTextPart = new MimeBodyPart(); messageTextPart.setText(text); BodyPart messageAttachmentPart = new MimeBodyPart(); DataSource source = new FileDataSource(new File(filename)); messageAttachmentPart.setDataHandler(new DataHandler(source)); messageAttachmentPart.setFileName(filename); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageTextPart); multipart.addBodyPart(messageAttachmentPart); message.setContent(multipart); return message; }
/** * Add the specified file as an attachment * * @param fileName * name of the file * @throws PackageException * on error */ @PublicAtsApi public void addAttachment( String fileName ) throws PackageException { try { // add attachment to multipart content MimeBodyPart attPart = new MimeBodyPart(); FileDataSource ds = new FileDataSource(fileName); attPart.setDataHandler(new DataHandler(ds)); attPart.setDisposition(MimeBodyPart.ATTACHMENT); attPart.setFileName(ds.getName()); addPart(attPart, PART_POSITION_LAST); } catch (MessagingException me) { throw new PackageException(me); } }
public StoreResult saveStore(String model, String key, DataSource dataSource) throws Exception { String path = key; File dir = new File(baseDir + "/" + model); dir.mkdirs(); File targetFile = new File(baseDir + "/" + model + "/" + path); FileOutputStream fos = new FileOutputStream(targetFile); try { FileCopyUtils.copy(dataSource.getInputStream(), fos); fos.flush(); } finally { fos.close(); } StoreResult storeResult = new StoreResult(); storeResult.setModel(model); storeResult.setKey(path); storeResult.setDataSource(new FileDataSource(targetFile)); return storeResult; }
public static String addAttachment(MimeMultipart mm, String path) { if(count == Integer.MAX_VALUE) { count = 0; } int cid = count++; try { java.io.File file = new java.io.File(path); MimeBodyPart mbp = new MimeBodyPart(); mbp.setDisposition(MimeBodyPart.INLINE); mbp.setContent(new MimeMultipart("mixed")); mbp.setHeader("Content-ID", "<" + cid + ">"); mbp.setDataHandler(new DataHandler(new FileDataSource(file))); mbp.setFileName(new String(file.getName().getBytes("GBK"), "ISO-8859-1")); mm.addBodyPart(mbp); return String.valueOf(cid); } catch(Exception e) { e.printStackTrace(); } return ""; }
@Test public void marshalAttachments() throws Exception { marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(BinaryObject.class); marshaller.setMtomEnabled(true); marshaller.afterPropertiesSet(); MimeContainer mimeContainer = mock(MimeContainer.class); Resource logo = new ClassPathResource("spring-ws.png", getClass()); DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile())); given(mimeContainer.convertToXopPackage()).willReturn(true); byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream()); BinaryObject object = new BinaryObject(bytes, dataHandler); StringWriter writer = new StringWriter(); marshaller.marshal(object, new StreamResult(writer), mimeContainer); assertTrue("No XML written", writer.toString().length() > 0); verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class)); }
public EmailMessage addAttachment(String attachmentName, File file) throws MessagingException { _totalAttachmentSizeSoFar += file.length(); if (_totalAttachmentSizeSoFar > _totalAttachmentMaxSizeInByte) { throw new MessageAttachmentExceededMaximumSizeException( "Adding attachment '" + attachmentName + "' will exceed the allowed maximum size of " + _totalAttachmentMaxSizeInByte); } BodyPart attachmentPart = new MimeBodyPart(); DataSource fileDataSource = new FileDataSource(file); attachmentPart.setDataHandler(new DataHandler(fileDataSource)); attachmentPart.setFileName(attachmentName); _attachments.add(attachmentPart); return this; }
/** * 创建复杂的正文 * @return * @throws MessagingException */ private Multipart createMultiPart() throws MessagingException { // TODO Auto-generated method stub Multipart multipart=new MimeMultipart(); //第一块 BodyPart bodyPart1=new MimeBodyPart(); bodyPart1.setText("创建复杂的邮件,此为正文部分"); multipart.addBodyPart(bodyPart1); //第二块 以附件形式存在 MimeBodyPart bodyPart2=new MimeBodyPart(); //设置附件的处理器 FileDataSource attachFile=new FileDataSource(ClassLoader.getSystemResource("attach.txt").getFile()); DataHandler dh=new DataHandler(attachFile); bodyPart2.setDataHandler(dh); bodyPart2.setDisposition(Part.ATTACHMENT); bodyPart2.setFileName("test"); multipart.addBodyPart(bodyPart2); return multipart; }
public void sendUsingMTOM(String fileName, String targetEPR) throws IOException { final String EXPECTED = "<m0:uploadFileUsingMTOMResponse xmlns:m0=\"http://services.samples\"><m0:response>" + "<m0:image>PHByb3h5PkFCQzwvcHJveHk+</m0:image></m0:response></m0:uploadFileUsingMTOMResponse>"; OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns); OMElement request = factory.createOMElement("request", ns); OMElement image = factory.createOMElement("image", ns); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); OMText textData = factory.createOMText(dataHandler, true); image.addChild(textData); request.addChild(image); payload.addChild(request); ServiceClient serviceClient = new ServiceClient(); Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingMTOM"); options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE); options.setCallTransportCleanup(true); serviceClient.setOptions(options); OMElement response = serviceClient.sendReceive(payload); Assert.assertTrue(response.toString().contains(EXPECTED), "Attachment is missing in the response"); }
public void sendUsingMTOM(String fileName, String targetEPR) throws IOException { OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns); OMElement request = factory.createOMElement("request", ns); OMElement image = factory.createOMElement("image", ns); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); OMText textData = factory.createOMText(dataHandler, true); image.addChild(textData); request.addChild(image); payload.addChild(request); ServiceClient serviceClient = new ServiceClient(); Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingMTOM"); options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE); options.setCallTransportCleanup(true); serviceClient.setOptions(options); OMElement response = serviceClient.sendReceive(payload); Assert.assertTrue(response.toString().contains( "<m:testMTOM xmlns:m=\"http://services.samples/xsd\">" + "<m:test1>testMTOM</m:test1></m:testMTOM>")); }
/** * @param attachmentPaths * Paths to attachment files. * @throws Exception * Exception. * @return Message with attachments. */ private Message prepareMessage(String[] attachmentPaths) throws Exception { Message message = new MimeMessage(Session.getDefaultInstance(System.getProperties())); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Test."); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); for (String file : attachmentPaths) { BodyPart attachmentPart = new MimeBodyPart(); File attachment = new File(SRC_TEST_RESOURCES_MAILING_TEST + "/" + file); DataSource source = new FileDataSource(attachment); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setFileName(attachment.getName()); multipart.addBodyPart(attachmentPart); } message.setContent(multipart); message.removeHeader("Content-Type"); message.setHeader("Content-Type", "multipart/mixed"); Assert.assertTrue(message.isMimeType("multipart/*")); return message; }
public void testMessageWithAttachmentRedeliveryIssue() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); template.send("direct:start", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); exchange.getIn().addAttachment("message1.xml", new DataHandler(new FileDataSource(new File("src/test/data/message1.xml")))); exchange.getIn().addAttachment("message2.xml", new DataHandler(new FileDataSource(new File("src/test/data/message2.xml")))); } }); assertMockEndpointsSatisfied(); Message msg = getMockEndpoint("mock:result").getReceivedExchanges().get(0).getIn(); assertNotNull(msg); assertEquals("Hello World", msg.getBody()); assertTrue(msg.hasAttachments()); }
public void testAttachments() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(2); mock.expectedBodiesReceivedInAnyOrder("log4j.properties", "jndi-example.properties"); template.send("direct:begin", new Processor() { @Override public void process(Exchange exchange) throws Exception { Message m = exchange.getIn(); m.setBody("Hello World"); m.addAttachment("log4j", new DataHandler(new FileDataSource("src/test/resources/log4j.properties"))); m.addAttachment("jndi-example", new DataHandler(new FileDataSource("src/test/resources/jndi-example.properties"))); } }); assertMockEndpointsSatisfied(); Map<String, DataHandler> attachments = mock.getExchanges().get(0).getIn().getAttachments(); assertTrue(attachments == null || attachments.size() == 0); }
public void testBeanWithAnnotationAndExchangeTest() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("attachment"); template.send("direct:in", new Processor() { public void process(Exchange exchange) throws Exception { exchange.setPattern(ExchangePattern.InOut); Message m = exchange.getIn(); m.addAttachment("attachment", new DataHandler(new FileDataSource("src/test/org/apache/camel/component/bean/BeanWithAttachmentAnnotationTest.java"))); } }); mock.assertIsSatisfied(); }
private void addAttachment(String filename) throws Exception { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); messageBodyPart.setHeader("Content-ID","<image>"); _multipart.addBodyPart(messageBodyPart); }
public MimeMessage createEmailMessageWithImage(String to, String subject, String body, String imgFileName) throws AddressException, MessagingException { MimeMessage msg = createEmailMessage(to, subject, String.format("%s <br/>\n <img src=\"%s\"/>", body, imgFileName)); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(String.format("%s <br/>\n <img src=\"%s\"/>", body, imgFileName), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); File img = new File(imgFileName); DataSource source = new FileDataSource(img); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(imgFileName); messageBodyPart.setDisposition(Part.INLINE); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); return msg; }
/** * We compare a document with itself. */ @Test public void testIdenticalPdfDocuments() throws Exception { DataSource referenceDataSource = new FileDataSource(new File(testDocumentDir, "open-office-01.pdf")); DataSource documentDataSource = new FileDataSource(new File(testDocumentDir, "open-office-01.pdf")); PdfDocumentComparatorResult pdfDocumentComparatorResult = new PdfDocumentComparator().compareDocuments(referenceDataSource, documentDataSource); System.out.println(pdfDocumentComparatorResult); new PdfDocumentComparatorResultWriter().writeToDirectory(testResultDir, "testIdenticalPdfDocuments", pdfDocumentComparatorResult); assertNotNull(pdfDocumentComparatorResult); assertEquals(1, pdfDocumentComparatorResult.getReferenceNrOfPages()); assertEquals(1, pdfDocumentComparatorResult.getDocumentNrOfPages()); assertEquals(1, pdfDocumentComparatorResult.getImageDifferResultList().size()); assertTrue(pdfDocumentComparatorResult.isIdentical()); assertEquals("open-office-01.pdf", pdfDocumentComparatorResult.getReferenceName()); assertEquals("open-office-01.pdf", pdfDocumentComparatorResult.getDocumentName()); assertTrue(pdfDocumentComparatorResult.toString().length() > 16); }
/** * We compare a document with its slightly modified version assuming that the * small difference will be detected. */ @Test public void testSimilarPdfDocuments() throws Exception { DataSource referenceDataSource = new FileDataSource(new File(testDocumentDir, "open-office-02.pdf")); DataSource documentDataSource = new FileDataSource(new File(testDocumentDir, "open-office-02-similar.pdf")); PdfDocumentComparatorResult pdfDocumentComparatorResult = new PdfDocumentComparator().compareDocuments(referenceDataSource, documentDataSource); new PdfDocumentComparatorResultWriter().writeToDirectory(testResultDir, "testSimilarPdfDocuments", pdfDocumentComparatorResult); assertNotNull(pdfDocumentComparatorResult); assertEquals(1, pdfDocumentComparatorResult.getReferenceNrOfPages()); assertEquals(1, pdfDocumentComparatorResult.getDocumentNrOfPages()); assertEquals(1, pdfDocumentComparatorResult.getImageDifferResultList().size()); assertTrue(pdfDocumentComparatorResult.hasSameNrOfPages()); assertFalse(pdfDocumentComparatorResult.isIdentical()); assertEquals("open-office-02.pdf", pdfDocumentComparatorResult.getReferenceName()); assertEquals("open-office-02-similar.pdf", pdfDocumentComparatorResult.getDocumentName()); assertTrue(pdfDocumentComparatorResult.toString().length() > 16); }
/** * We compare two different PDF documents both having one page. */ @Test public void testDifferentPdfDocuments() throws Exception { DataSource referenceDataSource = new FileDataSource(new File(testDocumentDir, "open-office-01.pdf")); DataSource documentDataSource = new FileDataSource(new File(testDocumentDir, "open-office-02.pdf")); PdfDocumentComparatorResult pdfDocumentComparatorResult = new PdfDocumentComparator().compareDocuments(referenceDataSource, documentDataSource); new PdfDocumentComparatorResultWriter().writeToDirectory(testResultDir, "testDifferentPdfDocuments", pdfDocumentComparatorResult); assertNotNull(pdfDocumentComparatorResult); assertEquals(1, pdfDocumentComparatorResult.getReferenceNrOfPages()); assertEquals(1, pdfDocumentComparatorResult.getDocumentNrOfPages()); assertEquals(1, pdfDocumentComparatorResult.getImageDifferResultList().size()); assertTrue(pdfDocumentComparatorResult.hasSameNrOfPages()); assertFalse(pdfDocumentComparatorResult.isIdentical()); assertEquals("open-office-01.pdf", pdfDocumentComparatorResult.getReferenceName()); assertEquals("open-office-02.pdf", pdfDocumentComparatorResult.getDocumentName()); assertTrue(pdfDocumentComparatorResult.toString().length() > 16); }
/** * Attempts to find or upload the default SDK examples test source * * @param server * Server to operate on * @return The analysis source location of the test source on the server * @throws SdkFault * If there is an issue uploading/finding the source */ private static AnalysisSourceLocation getHibernateCoreSource(ProtexServerProxy server) throws SdkFault { // First, check that the source aren't already there - lets not duplicate the upload AnalysisSourceLocation testLocation = new AnalysisSourceLocation(); testLocation.setHostname("localhost"); testLocation.setRepository(AnalysisSourceRepository.REMOTE_SERVER); testLocation.setSourcePath(HIBERNATE_SOURCE_NAME); if (!isSourceUploaded(server, testLocation)) { logger.info("Test sources not yet present - uploading to server"); File temporaryUnpackLocation = unpackClasspathSource(HIBERNATE_SOURCE_LOCATION, ".zip"); DataSource unexpandedfileDS = new FileDataSource(temporaryUnpackLocation); SourceCodeUploadRequest sourceCodeUploadRequest = new SourceCodeUploadRequest(); sourceCodeUploadRequest.setSourceName(HIBERNATE_SOURCE_NAME + ".zip"); sourceCodeUploadRequest.setSourceContent(new DataHandler(unexpandedfileDS)); testLocation = server.getPolicyApi().uploadSourceArchive(sourceCodeUploadRequest); } return testLocation; }
public ResourceDescriptor modifyReportUnitResource(String reportUnitUri, ResourceDescriptor descriptor, File inputFile) throws Exception { RequestAttachment[] attachments; if (inputFile == null) { attachments = new RequestAttachment[0]; } else { // patch jrxml files.... // if (IReportManager.getPreferences().getBoolean("use_jrxml_DTD", // false)) // { // if (inputFile.getName().toLowerCase().endsWith(".jrxml")) // { // inputFile = patchJRXML(inputFile); // } // } FileDataSource fileDataSource = new FileDataSource(inputFile); RequestAttachment attachment = new RequestAttachment(fileDataSource); attachments = new RequestAttachment[] { attachment }; } return putReportUnitResource(reportUnitUri, descriptor, attachments); }
/** * @return A MimeMultipart object containing the zipped result files */ public MimeMultipart getResult() { File file = new File(JPLAG_RESULTS_DIRECTORY + File.separator + submissionID + getUsername() + ".zip"); MimeMultipart mmp = new MimeMultipart(); FileDataSource fds1 = new FileDataSource(file); MimetypesFileTypeMap mftp = new MimetypesFileTypeMap(); mftp.addMimeTypes("multipart/zip zip ZIP"); fds1.setFileTypeMap(mftp); MimeBodyPart mbp = new MimeBodyPart(); try { mbp.setDataHandler(new DataHandler(fds1)); mbp.setFileName(file.getName()); mmp.addBodyPart(mbp); } catch (MessagingException me) { me.printStackTrace(); } return mmp; }
private void includeAttachments(MimeMultipart mimeMultipart,List<LabelValueBean> attachments) throws MessagingException { for (int i = 0; i < attachments.size(); i++) { LabelValueBean lvb=attachments.get(i); File f=new File(lvb.getValue()); if(f!=null&&f.exists()){ LOGGER.debug("Use attachment file:"+f.getAbsolutePath()); MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(lvb.getLabel()); mimeMultipart.addBodyPart(mbpFile); }else{ LOGGER.debug("Attachment file:\""+lvb.getValue()+"\" not exits!"); } } }
private void setAttachments(Multipart multipart, Collection<MailAttachment> attachments) throws MessagingException { if (attachments == null || attachments.isEmpty()) { return; } for(final MailAttachment attachment : attachments){ MimeBodyPart attachmentPart = new MimeBodyPart(); FileDataSource fileDataSource = new FileDataSource(attachment.getLocation()) { @Override public String getContentType() { return attachment.getContentTypeText(); } }; attachmentPart.setDataHandler(new DataHandler(fileDataSource)); attachmentPart.setFileName(attachment.getFileName()); multipart.addBodyPart(attachmentPart); } }
public void save(String targetInstanceName, String directory, File[] files) throws DigitalAssetStoreException { try { int numAttachments = files.length; String[] filenames = new String[numAttachments]; DataHandler[] handlers = new DataHandler[numAttachments]; for(int i=0; i<numAttachments; i++) { filenames[i] = files[i].getName(); handlers[i] = new DataHandler(new FileDataSource(files[i])); } WCTSoapCall call = new WCTSoapCall(host, port, service, "save"); call.regTypes(DataHandler.class); call.invoke(targetInstanceName, directory, filenames, handlers); } catch(Exception ex) { throw new DigitalAssetStoreException("Failed to save to ARC File Store : " + ex.getMessage(), ex); } }
public void save(String targetInstanceName, File[] files) throws DigitalAssetStoreException { try { int numAttachments = files.length; String[] filenames = new String[numAttachments]; DataHandler[] handlers = new DataHandler[numAttachments]; for(int i=0; i<numAttachments; i++) { filenames[i] = files[i].getName(); handlers[i] = new DataHandler(new FileDataSource(files[i])); } WCTSoapCall call = new WCTSoapCall(host, port, service, "save"); call.regTypes(DataHandler.class); call.invoke(targetInstanceName, filenames, handlers); } catch(Exception ex) { throw new DigitalAssetStoreException("Failed to save to ARC File Store : " + ex.getMessage(), ex); } }
private void deployArtifacts() throws RemoteException { String bpelArchiveName = processName + BPELDeployer.Constants.ZIP_EXT; String archiveHome = System.getProperty(BPELDeployer.Constants.TEMP_DIR_PROPERTY) + File.separator; DataSource bpelDataSource = new FileDataSource(archiveHome + bpelArchiveName); WorkflowDeployerClient workflowDeployerClient; if (bpsProfile.getProfileName().equals(WFImplConstant.DEFAULT_BPS_PROFILE_NAME)) { workflowDeployerClient = new WorkflowDeployerClient(bpsProfile.getManagerHostURL(), bpsProfile.getUsername()); } else { workflowDeployerClient = new WorkflowDeployerClient(bpsProfile.getManagerHostURL(), bpsProfile.getUsername(), bpsProfile.getPassword()); } workflowDeployerClient.uploadBPEL(getBPELUploadedFileItem(new DataHandler(bpelDataSource), bpelArchiveName, BPELDeployer.Constants.ZIP_TYPE)); String htArchiveName = htName + BPELDeployer.Constants.ZIP_EXT; DataSource htDataSource = new FileDataSource(archiveHome + htArchiveName); workflowDeployerClient.uploadHumanTask(getHTUploadedFileItem(new DataHandler(htDataSource), htArchiveName, BPELDeployer.Constants.ZIP_TYPE)); }
/** * Delivers a map with all possible outcome-variables of this onyx test. * * @param node The course node with the Onyx test. * @return A map with all outcome-variables with name as key and type as value. */ public Map<String, String> getOutcomes(final AssessableCourseNode node) throws RemoteException { final Map<String, String> outcomes = new HashMap<String, String>(); final OnyxReporterStub stub = client.getOnyxReporterStub(); final File onyxTestZip = getCP(node.getReferencedRepositoryEntry()); // Get outcomes final ContentPackage cp = new ContentPackage(); cp.setContentPackage(new DataHandler(new FileDataSource(onyxTestZip))); final ResultVariableCandidatesInput resultVariableCandidatesInput = new ResultVariableCandidatesInput(); resultVariableCandidatesInput.setResultVariableCandidatesInput(cp); final ResultVariableCandidatesResponse response = stub.resultVariableCandidates(resultVariableCandidatesInput); final PostGetParams[] params = response.getResultVariableCandidatesResponse().getReturnValues(); for (final PostGetParams param : params) { outcomes.put(param.getParamName(), param.getParamValue()); } return outcomes; }
/** * For every result xml file found in the survey folder a dummy student is created. * * @param nodeId * @return */ private List<Student> getAnonymizedStudentsWithResultsForSurvey(final String nodeId) { final List<Student> serviceStudents = new ArrayList<Student>(); final File directory = new File(this.surveyFolderPath); if (directory.exists()) { final String[] allXmls = directory.list(new myFilenameFilter(nodeId)); if (allXmls != null && allXmls.length > 0) { int id = 0; for (final String xmlFileName : allXmls) { final File xmlFile = new File(this.surveyFolderPath + xmlFileName); final Student serviceStudent = new Student(); serviceStudent.setResultFile(new DataHandler(new FileDataSource(xmlFile))); serviceStudent.setStudentId("st" + id); serviceStudents.add(serviceStudent); id++; } } } return serviceStudents; }
public ResourceDescriptor modifyReportUnitResource(String reportUnitUri, ResourceDescriptor descriptor, File inputFile) throws Exception { RequestAttachment[] attachments; if (inputFile == null) { attachments = new RequestAttachment[0]; } else { // patch jrxml files.... //if (IReportManager.getPreferences().getBoolean("use_jrxml_DTD", false)) //{ // if (inputFile.getName().toLowerCase().endsWith(".jrxml")) // { // inputFile = patchJRXML(inputFile); // } //} FileDataSource fileDataSource = new FileDataSource(inputFile); RequestAttachment attachment = new RequestAttachment(fileDataSource); attachments = new RequestAttachment[]{attachment}; } return putReportUnitResource(reportUnitUri, descriptor, attachments); }
/** * 添加附件 * * @param filename * String */ public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:" + filename); try { BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch (Exception e) { System.err.println("增加邮件附件:" + filename + "发生错误!" + e); return false; } }