javax.activation.URLDataSource Java Examples

The following examples show how to use javax.activation.URLDataSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DispatchHandlerInvocationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeWithDataSourcMessageModeXMLBinding() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/addNumbers.wsdl");
    assertNotNull(wsdl);

    XMLService service = new XMLService();
    assertNotNull(service);

    Dispatch<DataSource> disp = service.createDispatch(portNameXML, DataSource.class, Mode.MESSAGE);
    setAddress(disp, addNumbersAddress);

    TestHandlerXMLBinding handler = new TestHandlerXMLBinding();
    addHandlersProgrammatically(disp, handler);

    URL is = getClass().getResource("/messages/XML_GreetMeDocLiteralReq.xml");
    DataSource ds = new URLDataSource(is);

    DataSource resp = disp.invoke(ds);
    assertNotNull(resp);
}
 
Example #2
Source File: MailTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Message createMimeMessage( String specialCharacters, File attachedFile ) throws Exception {
  Session session = Session.getInstance( new Properties() );
  Message message = new MimeMessage( session );

  MimeMultipart multipart = new MimeMultipart();
  MimeBodyPart attachedFileAndContent = new MimeBodyPart();
  attachedFile.deleteOnExit();
  // create a data source
  URLDataSource fds = new URLDataSource( attachedFile.toURI().toURL() );
  // get a data Handler to manipulate this file type;
  attachedFileAndContent.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  String tempFileName = attachedFile.getName();
  message.setSubject( specialCharacters );
  attachedFileAndContent.setFileName( tempFileName );
  attachedFileAndContent.setText( specialCharacters );

  multipart.addBodyPart( attachedFileAndContent );
  message.setContent( multipart );

  return message;
}
 
Example #3
Source File: Mail.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private void addAttachedFilePart( FileObject file ) throws Exception {
  // create a data source

  MimeBodyPart files = new MimeBodyPart();
  // create a data source
  URLDataSource fds = new URLDataSource( file.getURL() );
  // get a data Handler to manipulate this file type;
  files.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  files.setFileName( file.getName().getBaseName() );
  // insist on base64 to preserve line endings
  files.addHeader( "Content-Transfer-Encoding", "base64" );
  // add the part with the file in the BodyPart();
  data.parts.addBodyPart( files );
  if ( isDetailed() ) {
    logDetailed( BaseMessages.getString( PKG, "Mail.Log.AttachedFile", fds.getName() ) );
  }

}
 
Example #4
Source File: MultiPartEmail.java    From commons-email with Apache License 2.0 6 votes vote down vote up
/**
 * Attach a file located by its URL.
 *
 * @param url The URL of the file (may be any valid URL).
 * @param name The name field for the attachment.
 * @param description A description for the attachment.
 * @param disposition Either mixed or inline.
 * @return A MultiPartEmail.
 * @throws EmailException see javax.mail.internet.MimeBodyPart
 *  for definitions
 * @since 1.0
 */
public MultiPartEmail attach(
    final URL url,
    final String name,
    final String description,
    final String disposition)
    throws EmailException
{
    // verify that the URL is valid
   try
   {
       final InputStream is = url.openStream();
       is.close();
   }
   catch (final IOException e)
   {
       throw new EmailException("Invalid URL set:" + url, e);
   }

   return attach(new URLDataSource(url), name, description, disposition);
}
 
Example #5
Source File: AttachmentUtil.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static DataSource getAttachmentDataSource(String contentId, Collection<Attachment> atts) {
    // Is this right? - DD
    if (contentId.startsWith("cid:")) {
        try {
            contentId = URLDecoder.decode(contentId.substring(4), StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException ue) {
            contentId = contentId.substring(4);
        }
        return loadDataSource(contentId, atts);
    } else if (contentId.indexOf("://") == -1) {
        return loadDataSource(contentId, atts);
    } else {
        try {
            return new URLDataSource(new URL(contentId));
        } catch (MalformedURLException e) {
            throw new Fault(e);
        }
    }

}
 
Example #6
Source File: DispatchHandlerInvocationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeWithDataSourcPayloadModeXMLBinding() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/addNumbers.wsdl");
    assertNotNull(wsdl);

    XMLService service = new XMLService();
    assertNotNull(service);

    Dispatch<DataSource> disp = service.createDispatch(portNameXML, DataSource.class, Mode.PAYLOAD);
    setAddress(disp, addNumbersAddress);

    TestHandlerXMLBinding handler = new TestHandlerXMLBinding();
    addHandlersProgrammatically(disp, handler);

    URL is = getClass().getResource("/messages/XML_GreetMeDocLiteralReq.xml");
    DataSource ds = new URLDataSource(is);
    DataSource resp = disp.invoke(ds);
    assertNotNull(resp);
}
 
Example #7
Source File: Mail.java    From hop with Apache License 2.0 6 votes vote down vote up
private void addAttachedFilePart( FileObject file ) throws Exception {
  // create a data source

  MimeBodyPart files = new MimeBodyPart();
  // create a data source
  URLDataSource fds = new URLDataSource( file.getURL() );
  // get a data Handler to manipulate this file type;
  files.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  files.setFileName( file.getName().getBaseName() );
  // insist on base64 to preserve line endings
  files.addHeader( "Content-Transfer-Encoding", "base64" );
  // add the part with the file in the BodyPart();
  data.parts.addBodyPart( files );
  if ( isDetailed() ) {
    logDetailed( BaseMessages.getString( PKG, "Mail.Log.AttachedFile", fds.getName() ) );
  }

}
 
Example #8
Source File: SampleIntegrationApplicationTest.java    From spring-boot-cxf-integration-example with MIT License 5 votes vote down vote up
@Test
public void test() throws Exception {
    String message = client.storeContent("test", new DataHandler(new URLDataSource(TEST_CONTENT_URL)));
    System.out.println("Server message: " + message);
    assertEquals("Content successfully stored", message);
    
    DataHandler dh = client.loadContent("test");
    assertNotNull(dh);
    File tempFile = new File(System.getProperty("java.io.tmpdir"), "spring_mtom_jaxws_tmp.bin");
    tempFile.deleteOnExit();
    long size = saveContentToFile(dh, tempFile);
    assertTrue(size > 0);
    assertTrue(tempFile.length()>0);
}
 
Example #9
Source File: AttachmentUtil.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Attachment getAttachment(String id, Collection<Attachment> attachments) {
    if (id == null) {
        throw new DatabindingException("Cannot get attachment: null id");
    }
    int i = id.indexOf("cid:");
    if (i != -1) {
        id = id.substring(4).trim();
    }

    if (attachments == null) {
        return null;
    }

    for (Iterator<Attachment> iter = attachments.iterator(); iter.hasNext();) {
        Attachment a = iter.next();
        if (a.getId().equals(id)) {
            return a;
        }
    }

    // Try loading the URL remotely
    try {
        URLDataSource source = new URLDataSource(new URL(id));
        return new AttachmentImpl(id, new DataHandler(source));
    } catch (MalformedURLException e) {
        return null;
    }
}
 
Example #10
Source File: EmailLiveTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
protected String getFromUrl(final URL url) throws Exception {

        final URLDataSource dataSource = new URLDataSource(url);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(dataSource.getInputStream(), baos);
        return new String(baos.toByteArray(), "UTF-8");
    }
 
Example #11
Source File: ZipIterator.java    From pumpernickel with MIT License 4 votes vote down vote up
public ZipIterator(URL url) throws Exception {
	this(new URLDataSource(url));
}
 
Example #12
Source File: StandardClasses.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public JAXBElement<DataHandler> standardClassDataHandler() {
	DataSource dataSource = new URLDataSource(getClass().getResource("spring-ws.png"));
	DataHandler dataHandler = new DataHandler(dataSource);
	return new JAXBElement<>(NAME, DataHandler.class, dataHandler);
}
 
Example #13
Source File: SerianalyzerInput.java    From serianalyzer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 
 * @param u
 * @throws IOException
 */
public void index ( URL u ) throws IOException {
    try ( InputStream openStream = u.openStream() ) {
        index(new URLDataSource(u));
    }
}
 
Example #14
Source File: StandardClasses.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public JAXBElement<DataHandler> standardClassDataHandler() {
	DataSource dataSource = new URLDataSource(getClass().getResource("spring-ws.png"));
	DataHandler dataHandler = new DataHandler(dataSource);
	return new JAXBElement<DataHandler>(NAME, DataHandler.class, dataHandler);
}
 
Example #15
Source File: SesSendNotificationHandler.java    From smart-security-camera with GNU General Public License v3.0 4 votes vote down vote up
public Parameters handleRequest(Parameters parameters, Context context) {
	context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	try {
		Session session = Session.getDefaultInstance(new Properties());
		MimeMessage message = new MimeMessage(session);
		message.setSubject(EMAIL_SUBJECT, "UTF-8");
		message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM")));
		message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) });
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT")));

		MimeBodyPart wrap = new MimeBodyPart();
		MimeMultipart cover = new MimeMultipart("alternative");
		MimeBodyPart html = new MimeBodyPart();
		cover.addBodyPart(html);
		wrap.setContent(cover);
		MimeMultipart content = new MimeMultipart("related");
		message.setContent(content);
		content.addBodyPart(wrap);

		URL attachmentURL = new URL(
				System.getenv("S3_URL_PREFIX") + parameters.getS3Bucket() + '/' + parameters.getS3Key());

		StringBuilder sb = new StringBuilder();
		String id = UUID.randomUUID().toString();
		sb.append("<img src=\"cid:");
		sb.append(id);
		sb.append("\" alt=\"ATTACHMENT\"/>\n");

		MimeBodyPart attachment = new MimeBodyPart();
		DataSource fds = new URLDataSource(attachmentURL);
		attachment.setDataHandler(new DataHandler(fds));

		attachment.setContentID("<" + id + ">");
		attachment.setDisposition("attachment");

		attachment.setFileName(fds.getName());
		content.addBodyPart(attachment);

		String prettyPrintLabels = parameters.getRekognitionLabels().toString();
		prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", "");
		prettyPrintLabels = prettyPrintLabels.replace(",", "<br>");
		html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "")
				+ "</h2><p><i>Step Function ID : " + parameters.getStepFunctionID()
				+ "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb
				+ "</body></html>", "text/html");

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		message.writeTo(outputStream);
		RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
		SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);

		AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient();
		client.sendRawEmail(rawEmailRequest);

	// Convert Checked Exceptions to RuntimeExceptions to ensure that
	// they get picked up by the Step Function infrastructure
	} catch (MessagingException | IOException e) {
		throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e);
	}

	context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	return parameters;
}
 
Example #16
Source File: HtmlEmail.java    From commons-email with Apache License 2.0 4 votes vote down vote up
/**
 * Embeds an URL in the HTML.
 *
 * <p>This method embeds a file located by an URL into
 * the mail body. It allows, for instance, to add inline images
 * to the email.  Inline files may be referenced with a
 * {@code cid:xxxxxx} URL, where xxxxxx is the Content-ID
 * returned by the embed function. It is an error to bind the same name
 * to more than one URL; if the same URL is embedded multiple times, the
 * same Content-ID is guaranteed to be returned.
 *
 * <p>While functionally the same as passing {@code URLDataSource} to
 * {@link #embed(DataSource, String, String)}, this method attempts
 * to validate the URL before embedding it in the message and will throw
 * {@code EmailException} if the validation fails. In this case, the
 * {@code HtmlEmail} object will not be changed.
 *
 * <p>
 * NOTE: Clients should take care to ensure that different URLs are bound to
 * different names. This implementation tries to detect this and throw
 * {@code EmailException}. However, it is not guaranteed to catch
 * all cases, especially when the URL refers to a remote HTTP host that
 * may be part of a virtual host cluster.
 *
 * @param url The URL of the file.
 * @param name The name that will be set in the file name header
 * field.
 * @return A String with the Content-ID of the file.
 * @throws EmailException when URL supplied is invalid or if {@code name} is null
 * or empty; also see {@link javax.mail.internet.MimeBodyPart} for definitions
 * @since 1.0
 */
public String embed(final URL url, final String name) throws EmailException
{
    if (EmailUtils.isEmpty(name))
    {
        throw new EmailException("name cannot be null or empty");
    }

    // check if a URLDataSource for this name has already been attached;
    // if so, return the cached CID value.
    if (inlineEmbeds.containsKey(name))
    {
        final InlineImage ii = inlineEmbeds.get(name);
        final URLDataSource urlDataSource = (URLDataSource) ii.getDataSource();
        // make sure the supplied URL points to the same thing
        // as the one already associated with this name.
        // NOTE: Comparing URLs with URL.equals() is a blocking operation
        // in the case of a network failure therefore we use
        // url.toExternalForm().equals() here.
        if (url.toExternalForm().equals(urlDataSource.getURL().toExternalForm()))
        {
            return ii.getCid();
        }
        throw new EmailException("embedded name '" + name
            + "' is already bound to URL " + urlDataSource.getURL()
            + "; existing names cannot be rebound");
    }

    // verify that the URL is valid
    InputStream is = null;
    try
    {
        is = url.openStream();
    }
    catch (final IOException e)
    {
        throw new EmailException("Invalid URL", e);
    }
    finally
    {
        try
        {
            if (is != null)
            {
                is.close();
            }
        }
        catch (final IOException ioe) // NOPMD
        { /* sigh */ }
    }

    return embed(new URLDataSource(url), name);
}
 
Example #17
Source File: StandardClasses.java    From java-technology-stack with MIT License 4 votes vote down vote up
public JAXBElement<DataHandler> standardClassDataHandler() {
	DataSource dataSource = new URLDataSource(getClass().getResource("spring-ws.png"));
	DataHandler dataHandler = new DataHandler(dataSource);
	return new JAXBElement<>(NAME, DataHandler.class, dataHandler);
}