List of usage examples for javax.activation DataSource DataSource
DataSource
From source file:com.jt.https.test.send.java
public static void main(String[] args) throws Exception { //final String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ChinaTourinsApply xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Head><UserId>0000000000</UserId><CommandId>CTAA0001</CommandId><SeqNo>JT2014_0000000263863</SeqNo></Head><Body><Apply><ApplyId>1201201407256948</ApplyId><TravelAgencyInfo><Id>1129035</Id><Name>???</Name><Address>?45?</Address><Zipcode>310000</Zipcode><Telphone>0571-63700288</Telphone><License>L-ZJ00295</License><OrgCode>79093228-2</OrgCode><OutboundTourismCredentials>N</OutboundTourismCredentials><LastYearTouristAmount>0.0</LastYearTouristAmount><LastYearRevenue>0-600</LastYearRevenue><last3YearAccidents>N</last3YearAccidents><Last1YearAccidentsFee>0.0</Last1YearAccidentsFee><Last2YearAccidentsFee>0.0</Last2YearAccidentsFee><Last3YearAccidentsFee>0.0</Last3YearAccidentsFee><Contact><Name></Name><Telphone>0571-63700288</Telphone><Mail>385816647@qq.ocm</Mail><Fax>0571-63700288</Fax></Contact><Branches /><Location><ProvinceId>12</ProvinceId><ProvinceName>?</ProvinceName><CityId>1201</CityId><CityName>?</CityName></Location><Properties><Key Name=\"LastApplyNo\" /><Key Name=\"LastPolicyNo\" /><Key Name=\"NewNum\" /><Key Name=\"NewLocation\" /></Properties><Last1YearPolicyNoList><Last1YearPolicyNoInfo><UserId /><PolicyNo /></Last1YearPolicyNoInfo></Last1YearPolicyNoList></TravelAgencyInfo><InsurancePolicyInfo><BeginDate>20140801</BeginDate><EndDate>20141231</EndDate><InsuranceDays>153</InsuranceDays><Renewal>N</Renewal><IssuingCompanyId>2014004</IssuingCompanyId><IssuingCompanyName>?????</IssuingCompanyName><IssuingGeneralCompanyName>???</IssuingGeneralCompanyName><RetroactiveDate>20140801</RetroactiveDate><MainInsurance><EachAccidentLiabilityLimit>20141000</EachAccidentLiabilityLimit><EachAccidentEveryLiabilityLimit>20142004</EachAccidentEveryLiabilityLimit><Properties><Key Name=\"MainPremium\">3135.4509</Key></Properties></MainInsurance><AdditionalInfo><Properties /></AdditionalInfo><PayDate>20140730</PayDate><PremiumInfo><PremiumAdjustmentFactor><YearTouristAmountRatio>-0.15</YearTouristAmountRatio><DistrictRatio>0</DistrictRatio><EachAccidentEveryLiabilityLimitRatio>0.1</EachAccidentEveryLiabilityLimitRatio><LossRatio>0</LossRatio><PreviousLossRatio>0</PreviousLossRatio><AdditionalRatio>0</AdditionalRatio><RiskControlRatio>0</RiskControlRatio><LoyaltyRatio>0</LoyaltyRatio><CoverageRateSystem>0</CoverageRateSystem><DatePreferentialRatio /></PremiumAdjustmentFactor><PremiumDistribution><TotalPremium>3135.45</TotalPremium><Distribution><RenBao CompanyId=\"2014004\">1442.30</RenBao><TaiBao CompanyId=\"2014058\">501.67</TaiBao><RenShou CompanyId=\"2014049\">250.84</RenShou><PingAn CompanyId=\"2014060\">344.90</PingAn><DaDi CompanyId=\"2014045\">282.19</DaDi><TaiPing CompanyId=\"2014039\">313.55</TaiPing></Distribution></PremiumDistribution><PremiumAdjust><RiskControl>0</RiskControl><Prepaid /></PremiumAdjust></PremiumInfo></InsurancePolicyInfo></Apply></Body></ChinaTourinsApply>"; final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ChinaTourinsResponse><Head><UserId>String</UserId><CommandId>String</CommandId><SeqNo>String</SeqNo><Ref-SeqNo>String</Ref-SeqNo></Head><Body><Apply><ApplyId>String</ApplyId><TravelAgencyId>String</TravelAgencyId><ResponseCode>String</ResponseCode><ResponseMessage>String</ResponseMessage><PolicyNo>String</PolicyNo><UpdateNo>String</UpdateNo><Fee>String</Fee><IssuingDate>String</IssuingDate><ElectricalDocument>String</ElectricalDocument></Apply></Body><IssuingCompany><Name>String</Name><Address>String</Address><Zipcode>String</Zipcode><Telphone>String</Telphone><Contact><Name>String</Name><Telphone>String</Telphone><Mail>String</Mail><Fax>String</Fax></Contact><Ccheck>String</Ccheck><Cbill>String</Cbill><Agent>String</Agent></IssuingCompany></ChinaTourinsResponse>"; WebInsuranceExchangeStub client = new WebInsuranceExchangeStub( "http://localhost/exchange/webservices/webInsuranceExchange"); com.jt.https.test.WebInsuranceExchangeStub.PolicyApplyConfirm post = new com.jt.https.test.WebInsuranceExchangeStub.PolicyApplyConfirm(); post.setUserId(""); DataHandler param = new DataHandler(new DataSource() { public InputStream getInputStream() { return new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8"))); }// www. ja v a2 s . c o m public OutputStream getOutputStream() { return null; } public String getContentType() { return ""; } public String getName() { return ""; } }); post.setConfirmMessage(param); com.jt.https.test.WebInsuranceExchangeStub.PolicyApplyConfirmResponse response = client .policyApplyConfirm(post); InputStream is = response.getResponseMessage().getInputStream(); String xml_result = ToolsUtils.ConvertStreamToString(is); System.out.println(xml_result); //PostTo(xml); }
From source file:org.ambraproject.wombat.service.FreemarkerMailServiceImpl.java
private static DataHandler createBodyPartDataHandler(byte[] data, String contentType) { Objects.requireNonNull(data); Objects.requireNonNull(contentType); return new DataHandler(new DataSource() { @Override//from ww w. java 2 s .c om public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } @Override public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } @Override public String getContentType() { return contentType; } @Override public String getName() { return "main"; } }); }
From source file:de.softwareforge.pgpsigner.commands.MailCommand.java
@Override public void executeInteractiveCommand(final String[] args) { SecretKey secretKey = getContext().getSignKey(); String senderMail = secretKey.getMailAddress(); String senderName = secretKey.getName(); if (StringUtils.isEmpty(senderMail)) { System.out.println("Could not extract sender mail from sign key."); return;/*from w w w . j ava 2 s. c o m*/ } for (final PublicKey key : getContext().getPartyRing().getVisibleKeys().values()) { if (key.isSigned() && !key.isMailed()) { try { String recipient = getContext().isSimulation() ? senderMail : key.getMailAddress(); if (StringUtils.isEmpty(recipient)) { System.out.println("No mail address for key " + key.getKeyId() + ", skipping."); continue; } System.out.println("Sending Key " + key.getKeyId() + " to " + recipient); MultiPartEmail mail = new MultiPartEmail(); mail.setHostName(getContext().getMailServerHost()); mail.setSmtpPort(getContext().getMailServerPort()); mail.setFrom(senderMail, senderName); mail.addTo(recipient); if (!getContext().isSimulation()) { mail.addBcc(senderMail); } mail.setSubject("Your signed PGP key - " + key.getKeyId()); mail.setMsg("This is your signed PGP key " + key.getKeyId() + " from the " + getContext().getSignEvent() + " key signing event."); final String name = key.getKeyId() + ".asc"; mail.attach(new DataSource() { public String getContentType() { return "application/pgp-keys"; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(key.getArmor()); } public String getName() { return name; } public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException(); } }, name, "Signed Key " + key.getKeyId()); mail.send(); key.setMailed(true); } catch (EmailException ee) { System.out.println("Could not send mail for Key " + key.getKeyId()); } } } }
From source file:cherry.foundation.mail.MailSendHandlerImplTest.java
@Test public void testSendNowAttached() throws Exception { LocalDateTime now = LocalDateTime.now(); MailSendHandler handler = create(now); ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class); doNothing().when(mailSender).send(preparator.capture()); final File file = File.createTempFile("test_", ".txt", new File(".")); file.deleteOnExit();/*from ww w .j av a 2 s . c om*/ try { try (OutputStream out = new FileOutputStream(file)) { out.write("attach2".getBytes()); } final DataSource dataSource = new DataSource() { @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getName() { return "name3.txt"; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream("attach3".getBytes()); } @Override public String getContentType() { return "text/plain"; } }; long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"), asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() { @Override public void prepare(Attachment attachment) throws MessagingException { attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes())); attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()), "application/octet-stream"); attachment.add("name2.txt", file); attachment.add("name3.txt", dataSource); } }); Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); preparator.getValue().prepare(message); assertEquals(0L, messageId); assertEquals(1, message.getRecipients(RecipientType.TO).length); assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]); assertEquals(1, message.getRecipients(RecipientType.CC).length); assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]); assertEquals(1, message.getRecipients(RecipientType.BCC).length); assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]); assertEquals(1, message.getFrom().length); assertEquals(parse("from@addr")[0], message.getFrom()[0]); assertEquals("subject", message.getSubject()); MimeMultipart mm = (MimeMultipart) message.getContent(); assertEquals(5, mm.getCount()); assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent()); assertEquals("name0.txt", mm.getBodyPart(1).getFileName()); assertEquals("text/plain", mm.getBodyPart(1).getContentType()); assertEquals("attach0", mm.getBodyPart(1).getContent()); assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName()); assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType()); assertEquals("attach1", new String( ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent()))); assertEquals("name2.txt", mm.getBodyPart(3).getFileName()); assertEquals("text/plain", mm.getBodyPart(3).getContentType()); assertEquals("attach2", mm.getBodyPart(3).getContent()); assertEquals("name3.txt", mm.getBodyPart(4).getFileName()); assertEquals("text/plain", mm.getBodyPart(4).getContentType()); assertEquals("attach3", mm.getBodyPart(4).getContent()); } finally { file.delete(); } }
From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java
/** * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and * creates a new request that represents the intended original request * * @param request the request to be decoded * * @return a decoded RestRequest//from w w w. j ava 2s. c om */ public static RestRequest decode(final RestRequest request) throws MessagingException, IOException, URISyntaxException { if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) { // Not a tunnelled request, just pass thru return request; } String query = null; byte[] entity = new byte[0]; // All encoded requests must have a content type. If the header is missing, ContentType throws an exception ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE)); RestRequestBuilder requestBuilder = request.builder(); // Get copy of headers and remove the override Map<String, String> h = new HashMap<String, String>(request.getHeaders()); h.remove(HEADER_METHOD_OVERRIDE); // Simple case, just extract query params from entity, append to query, and clear entity if (contentType.getBaseType().equals(FORM_URL_ENCODED)) { query = request.getEntity().asString(Data.UTF_8_CHARSET); h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); } else if (contentType.getBaseType().equals(MULTIPART)) { // Clear these in case there is no body part h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); MimeMultipart multi = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return request.getEntity().asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return request.getHeader(HEADER_CONTENT_TYPE); } @Override public String getName() { return null; } }); for (int i = 0; i < multi.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i); if (part.isMimeType(FORM_URL_ENCODED) && query == null) { // Assume the first segment we come to that is urlencoded is the tunneled query params query = IOUtils.toString((InputStream) part.getContent(), UTF8); } else if (entity.length <= 0) { // Assume the first non-urlencoded content we come to is the intended entity. entity = IOUtils.toByteArray((InputStream) part.getContent()); h.put(CONTENT_LENGTH, Integer.toString(entity.length)); h.put(HEADER_CONTENT_TYPE, part.getContentType()); } else { // If it's not form-urlencoded and we've already found another section, // this has to be be an extra body section, which we have no way to handle. // Proceed with the request as if the 1st part we found was the expected body, // but log a warning in case some client is constructing a request that doesn't // follow the rules. String unexpectedContentType = part.getContentType(); LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type=" + unexpectedContentType); } } } // Based on what we've found, construct the modified request. It's possible that someone has // modified the request URI, adding extra query params for debugging, tracking, etc, so // we have to check and append the original query correctly. if (query != null && query.length() > 0) { String separator = "&"; String existingQuery = request.getURI().getRawQuery(); if (existingQuery == null) { separator = "?"; } else if (existingQuery.isEmpty()) { // This would mean someone has appended a "?" with no args to the url underneath us separator = ""; } requestBuilder.setURI(new URI(request.getURI().toString() + separator + query)); } requestBuilder.setEntity(entity); requestBuilder.setHeaders(h); requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE)); return requestBuilder.build(); }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and * creates a new request that represents the intended original request * * @param request the request to be decoded * @param requestContext a RequestContext object associated with the request * * @return a decoded RestRequest//from w w w . j a v a 2s. co m */ public static RestRequest decode(final RestRequest request, RequestContext requestContext) throws MessagingException, IOException, URISyntaxException { if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) { // Not a tunnelled request, just pass thru return request; } String query = null; byte[] entity = new byte[0]; // All encoded requests must have a content type. If the header is missing, ContentType throws an exception ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE)); RestRequestBuilder requestBuilder = request.builder(); // Get copy of headers and remove the override Map<String, String> h = new HashMap<String, String>(request.getHeaders()); h.remove(HEADER_METHOD_OVERRIDE); // Simple case, just extract query params from entity, append to query, and clear entity if (contentType.getBaseType().equals(FORM_URL_ENCODED)) { query = request.getEntity().asString(Data.UTF_8_CHARSET); h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); } else if (contentType.getBaseType().equals(MULTIPART)) { // Clear these in case there is no body part h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); MimeMultipart multi = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return request.getEntity().asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return request.getHeader(HEADER_CONTENT_TYPE); } @Override public String getName() { return null; } }); for (int i = 0; i < multi.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i); if (part.isMimeType(FORM_URL_ENCODED) && query == null) { // Assume the first segment we come to that is urlencoded is the tunneled query params query = IOUtils.toString((InputStream) part.getContent(), UTF8); } else if (entity.length <= 0) { // Assume the first non-urlencoded content we come to is the intended entity. Object content = part.getContent(); if (content instanceof MimeMultipart) { ByteArrayOutputStream os = new ByteArrayOutputStream(); ((MimeMultipart) content).writeTo(os); entity = os.toByteArray(); } else { entity = IOUtils.toByteArray((InputStream) content); } h.put(CONTENT_LENGTH, Integer.toString(entity.length)); h.put(HEADER_CONTENT_TYPE, part.getContentType()); } else { // If it's not form-urlencoded and we've already found another section, // this has to be be an extra body section, which we have no way to handle. // Proceed with the request as if the 1st part we found was the expected body, // but log a warning in case some client is constructing a request that doesn't // follow the rules. String unexpectedContentType = part.getContentType(); LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type=" + unexpectedContentType); } } } // Based on what we've found, construct the modified request. It's possible that someone has // modified the request URI, adding extra query params for debugging, tracking, etc, so // we have to check and append the original query correctly. if (query != null && query.length() > 0) { String separator = "&"; String existingQuery = request.getURI().getRawQuery(); if (existingQuery == null) { separator = "?"; } else if (existingQuery.isEmpty()) { // This would mean someone has appended a "?" with no args to the url underneath us separator = ""; } requestBuilder.setURI(new URI(request.getURI().toString() + separator + query)); } requestBuilder.setEntity(entity); requestBuilder.setHeaders(h); requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE)); requestContext.putLocalAttr(R2Constants.IS_QUERY_TUNNELED, true); return requestBuilder.build(); }
From source file:org.topazproject.ambra.email.impl.FreemarkerTemplateMailer.java
public BodyPartDataHandler(final ByteArrayOutputStream outputStream, final String contentType) { super(new DataSource() { public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(outputStream.toByteArray()); }/* w w w.j a v a 2 s. c o m*/ public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return contentType; } public String getName() { return "main"; } }); }
From source file:cz.zcu.kiv.eegdatabase.webservices.datadownload.UserDataImpl.java
public DataHandler downloadDataFile(int dataFileId) throws UserDataServiceException { List<DataFile> files = experimentDao.getDataFilesWhereId(dataFileId); DataFile file = files.get(0);// ww w .j a v a2s .c o m DataSource rawData; final InputStream in; try { in = new ByteArrayInputStream(file.getFileContent().getBytes(1, (int) file.getFileContent().length())); } catch (SQLException ex) { throw new RuntimeException(ex); } rawData = new DataSource() { public String getContentType() { return "application/octet-stream"; } public InputStream getInputStream() throws IOException { return in; } public String getName() { return "application/octet-stream"; } public OutputStream getOutputStream() throws IOException { return null; } }; log.debug("User " + personDao.getLoggedPerson().getEmail() + " retrieved file " + dataFileId); return new DataHandler(rawData); }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both *//*from w w w.jav a2 s .co m*/ private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); if (MULTIPART.equals(contentType.getBaseType())) { MimeMultipart nested = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return entity.asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return entityContentType; } @Override public String getName() { return null; } }); dataPart.setContent(nested, contentType.getBaseType()); } else { dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); } dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }
From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java
public DataSource createContentStoreDump(RemoteSession session, String dbKey, final boolean includeACL, final boolean includeSystemAreas) throws WGAServiceException { if (!isAdminServiceEnabled()) { throw new WGAServiceException("Administrative services are disabled"); }//from w w w.j ava 2 s . c o m if (!isAdminSession(session)) { throw new WGAServiceException("You need an administrative login to access this service."); } try { final WGDatabase db = retrieveAndOpenDB(session, dbKey); if (db != null && db.isSessionOpen()) { return new DataSource() { public OutputStream getOutputStream() throws IOException { return null; } public String getName() { return "Dump '" + db.getDbReference() + "'"; } public InputStream getInputStream() throws IOException { try { return _core.dumpContentStore(db, "", true, _core.getLog(), includeACL, includeSystemAreas); } catch (WGAPIException e) { IOException ioe = new IOException(e.getMessage()); ioe.setStackTrace(e.getStackTrace()); throw ioe; } } public String getContentType() { return "application/zip"; } }; } else { throw new WGAServiceException("Unable to open database '" + dbKey + "'."); } } catch (Exception e) { throw new WGAServiceException("Import of content store dump failed for database '" + dbKey + "'.", e); } }