Example usage for javax.activation DataSource DataSource

List of usage examples for javax.activation DataSource DataSource

Introduction

In this page you can find the example usage for javax.activation DataSource DataSource.

Prototype

DataSource

Source Link

Usage

From source file:de.innovationgate.webgate.api.WGDatabase.java

/**
 * Tool method for annotating a metadata object based on the given file, using the default and optionally given additional annotators
 * @param file The file data//from   ww  w . j a va  2  s . com
 * @param meta The metadata object to annotate
 * @param additionalAnnotators Additional annotators to run.
 * @throws WGAPIException
 */
public void annotateMetadata(final File file, WGFileMetaData meta, List<WGFileAnnotator> additionalAnnotators)
        throws WGAPIException {

    DataSource ds = new DataSource() {

        @Override
        public String getContentType() {
            return "application/octet-stream";
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new BufferedInputStream(new FileInputStream(file));
        }

        @Override
        public String getName() {
            return file.getName();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("This data source does not provide an output stream");
        }

    };

    annotateMetadata(ds, meta, additionalAnnotators);
}

From source file:org.jboss.bpm.console.server.FormProcessingFacade.java

private FieldMapping createFieldMapping(MultipartFormDataInput payload) {
    FieldMapping mapping = new FieldMapping();

    Map<String, InputPart> formData = payload.getFormData();
    Iterator<String> partNames = formData.keySet().iterator();

    while (partNames.hasNext()) {
        final String partName = partNames.next();
        final InputPart part = formData.get(partName);
        final MediaType mediaType = part.getMediaType();

        String mType = mediaType.getType();
        String mSubtype = mediaType.getSubtype();

        if ("text".equals(mType) && "plain".equals(mSubtype)) {
            // RFC2045: Each part has an optional "Content-Type" header
            // that defaults to "text/plain".
            // Can go into process without conversion
            if (mapping.isReserved(partName))
                mapping.directives.put(partName, part.getBodyAsString());
            else//from  w  ww.ja  v a  2s .com
                mapping.processVars.put(partName, part.getBodyAsString());
        } else {
            // anything else turns into a DataHandler
            final byte[] data = part.getBodyAsString().getBytes();
            DataHandler dh = new DataHandler(new DataSource() {
                public InputStream getInputStream() throws IOException {
                    return new ByteArrayInputStream(data);
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new RuntimeException("This is a readonly DataHandler");
                }

                public String getContentType() {
                    return mediaType.getType();
                }

                public String getName() {
                    return partName;
                }
            });

            mapping.processVars.put(partName, dh);
        }
    }

    return mapping;
}

From source file:org.jbpm.integration.console.forms.AbstractFormDispatcher.java

protected DataHandler processTemplate(final String name, InputStream src, Map<String, Object> renderContext) {
    DataHandler merged = null;// www .j  a  va2  s .co m
    try {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(name, new InputStreamReader(src), cfg);
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        Writer out = new OutputStreamWriter(bout);
        temp.process(renderContext, out);
        out.flush();
        merged = new DataHandler(new DataSource() {
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(bout.toByteArray());
            }

            public OutputStream getOutputStream() throws IOException {
                return bout;
            }

            public String getContentType() {
                return "*/*";
            }

            public String getName() {
                return name + "_DataSource";
            }
        });
    } catch (Exception e) {
        throw new RuntimeException("Failed to process form template", e);
    }
    return merged;
}

From source file:org.openehealth.ipf.platform.camel.lbs.mina.mllp.MllpEncoderTest.java

@Test
public void testSimpleEncodeWithDataSource() throws Exception {
    DataSource dataSource = new DataSource() {
        @Override/*from   w w  w .  j a  v  a 2 s.c o  m*/
        public InputStream getInputStream() throws IOException {
            return IOUtils.toInputStream("Hello World");
        }

        @Override
        public String getContentType() {
            return null;
        }

        @Override
        public String getName() {
            return null;
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return null;
        }
    };
    checkSimpleEncode(dataSource);
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

private void handlePart(PipelineContext pipelineContext, String dataInputSystemId, Part parentPart,
        Element partOrBodyElement) throws Exception {
    final String name = partOrBodyElement.attributeValue("name");
    String contentTypeAttribute = partOrBodyElement.attributeValue("content-type");
    final String contentType = NetUtils.getContentTypeMediaType(contentTypeAttribute);
    final String charset;
    {/*from ww  w .j  ava 2 s. co  m*/
        final String c = NetUtils.getContentTypeCharset(contentTypeAttribute);
        charset = (c != null) ? c : DEFAULT_CHARACTER_ENCODING;
    }
    final String contentTypeWithCharset = contentType + "; charset=" + charset;
    final String src = partOrBodyElement.attributeValue("src");

    // Either a String or a FileItem
    final Object content;
    if (src != null) {
        // Content of the part is not inline

        // Generate a FileItem from the source
        final SAXSource source = getSAXSource(EmailProcessor.this, pipelineContext, src, dataInputSystemId,
                contentType);
        content = handleStreamedPartContent(pipelineContext, source);
    } else {
        // Content of the part is inline

        // In the cases of text/html and XML, there must be exactly one root element
        final boolean needsRootElement = "text/html".equals(contentType);// || ProcessorUtils.isXMLContentType(contentType);
        if (needsRootElement && partOrBodyElement.elements().size() != 1)
            throw new ValidationException(
                    "The <body> or <part> element must contain exactly one element for text/html",
                    (LocationData) partOrBodyElement.getData());

        // Create Document and convert it into a String
        final Element rootElement = (Element) (needsRootElement ? partOrBodyElement.elements().get(0)
                : partOrBodyElement);
        final Document partDocument = new NonLazyUserDataDocument();
        partDocument.setRootElement((Element) rootElement.clone());
        content = handleInlinePartContent(partDocument, contentType);
    }

    if (!XMLUtils.isTextOrJSONContentType(contentType)) {
        // This is binary content (including application/xml)
        if (content instanceof FileItem) {
            final FileItem fileItem = (FileItem) content;
            parentPart.setDataHandler(new DataHandler(new DataSource() {
                public String getContentType() {
                    return contentType;
                }

                public InputStream getInputStream() throws IOException {
                    return fileItem.getInputStream();
                }

                public String getName() {
                    return name;
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("Write operation not supported");
                }
            }));
        } else {
            byte[] data = NetUtils.base64StringToByteArray((String) content);
            parentPart.setDataHandler(new DataHandler(new SimpleBinaryDataSource(name, contentType, data)));
        }
    } else {
        // This is text content (including text/xml)
        if (content instanceof FileItem) {
            // The text content was encoded when written to the FileItem
            final FileItem fileItem = (FileItem) content;
            parentPart.setDataHandler(new DataHandler(new DataSource() {
                public String getContentType() {
                    // This always contains a charset
                    return contentTypeWithCharset;
                }

                public InputStream getInputStream() throws IOException {
                    // This is encoded with the appropriate charset (user-defined, or the default)
                    return fileItem.getInputStream();
                }

                public String getName() {
                    return name;
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("Write operation not supported");
                }
            }));
        } else {
            parentPart.setDataHandler(
                    new DataHandler(new SimpleTextDataSource(name, contentTypeWithCharset, (String) content)));
        }
    }

    // Set content-disposition header
    String contentDisposition = partOrBodyElement.attributeValue("content-disposition");
    if (contentDisposition != null)
        parentPart.setDisposition(contentDisposition);

    // Set content-id header
    String contentId = partOrBodyElement.attributeValue("content-id");
    if (contentId != null)
        parentPart.setHeader("content-id", "<" + contentId + ">");
    //part.setContentID(contentId);
}

From source file:org.paxle.core.doc.impl.BasicDocumentFactoryTest.java

public void testLoadUnmarshalledCommand() throws IOException, ParseException {
    final ZipFile zf = new ZipFile(new File("src/test/resources/command.zip"));

    // process attachments
    final Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();
    for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) {
        final ZipEntry entry = entries.nextElement();
        final String name = entry.getName();
        if (name.equals("command.xml"))
            continue;

        // create a data-source to load the attachment
        final DataSource source = new DataSource() {
            private ZipFile zip = zf;
            private ZipEntry zipEntry = entry;

            public String getContentType() {
                return "application/x-java-serialized-object";
            }/*www  .j a va  2 s .  c o  m*/

            public InputStream getInputStream() throws IOException {
                return this.zip.getInputStream(this.zipEntry);
            }

            public String getName() {
                return this.zipEntry.getName();
            }

            public OutputStream getOutputStream() throws IOException {
                throw new UnsupportedOperationException();
            }
        };
        final DataHandler handler = new DataHandler(source);
        attachments.put(name, handler);
    }

    // process command
    final ZipEntry commandEntry = zf.getEntry("command.xml");
    final InputStream commandInput = zf.getInputStream(commandEntry);

    // marshal command
    TeeInputStream input = new TeeInputStream(commandInput, System.out);
    final ICommand cmd1 = this.docFactory.unmarshal(input, attachments);
    assertNotNull(cmd1);
    zf.close();

    final ICommand cmd2 = this.createTestCommand();
    assertEquals(cmd2, cmd1);
}

From source file:org.unitime.commons.Email.java

public void addAttachement(final FormFile file) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(new DataSource() {
        @Override//from   w  w  w  . j av  a2 s . c  om
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("No output stream.");
        }

        @Override
        public String getName() {
            return file.getFileName();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return file.getInputStream();
        }

        @Override
        public String getContentType() {
            return file.getContentType();
        }
    }));
    attachement.setFileName(file.getFileName());
    iBody.addBodyPart(attachement);
}

From source file:org.unitime.timetable.events.EventEmail.java

public void send(SessionContext context) throws UnsupportedEncodingException, MessagingException {
    try {/*from   w w  w.j a v  a 2 s  . c om*/
        if (!request().isEmailConfirmation())
            return;

        if (ApplicationProperty.EmailConfirmationEvents.isFalse()) {
            response().info(MESSAGES.emailDisabled());
            return;
        }

        Email email = Email.createEmail();
        if (event().hasContact() && event().getContact().getEmail() != null
                && !event().getContact().getEmail().isEmpty())
            email.addRecipient(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        if (event().hasAdditionalContacts()) {
            for (ContactInterface contact : event().getAdditionalContacts()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipient(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasSponsor() && event().getSponsor().hasEmail())
            email.addRecipientCC(event().getSponsor().getEmail(), event().getSponsor().getName());
        if (event().hasEmail()) {
            String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value();
            for (String address : event().getEmail().split("[\n,]")) {
                if (!address.trim().isEmpty()) {
                    if (suffix != null && address.indexOf('@') < 0)
                        email.addRecipientCC(address.trim() + suffix, null);
                    else
                        email.addRecipientCC(address.trim(), null);
                }
            }
        }
        if (event().hasInstructors() && ApplicationProperty.EmailConfirmationEventInstructors.isTrue()) {
            for (ContactInterface contact : event().getInstructors()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasCoordinators() && ApplicationProperty.EmailConfirmationEventCoordinators.isTrue()) {
            for (ContactInterface contact : event().getCoordinators()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }

        if (ApplicationProperty.EmailConfirmationEventManagers.isTrue()) {
            Set<Long> locationIds = new HashSet<Long>();
            if (event().hasMeetings()) {
                for (MeetingInterface m : event().getMeetings()) {
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
                }
            }
            if (response().hasDeletedMeetings()) {
                for (MeetingInterface m : response().getDeletedMeetings())
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
            }
            org.hibernate.Session hibSession = SessionDAO.getInstance().getSession();
            NameFormat nf = NameFormat.fromReference(context.getUser().getProperty(UserProperty.NameFormat));
            for (TimetableManager m : (List<TimetableManager>) hibSession.createQuery(
                    "select distinct m from Location l inner join l.eventDepartment.timetableManagers m inner join m.managerRoles r where "
                            + "l.uniqueId in :locationIds and m.emailAddress is not null and r.receiveEmails = true and :permission in elements (r.role.rights)")
                    .setParameterList("locationIds", locationIds, new LongType())
                    .setString("permission", Right.EventLookupContact.name()).list()) {
                email.addRecipientCC(m.getEmailAddress(), nf.format(m));
            }
        }

        if (replyTo() != null) {
            email.setReplyTo(replyTo().getAddress(), replyTo().getPersonal());
        } else if (context != null && context.isAuthenticated() && context.getUser().getEmail() != null) {
            email.setReplyTo(context.getUser().getEmail(), context.getUser().getName());
        } else {
            email.setReplyTo(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        }

        if (event().getId() != null && ApplicationProperty.InboundEmailsEnabled.isTrue()
                && ApplicationProperty.InboundEmailsReplyToAddress.value() != null) {
            email.setSubject("[EVENT-" + Long.toHexString(event().getId()) + "] " + event().getName() + " ("
                    + event().getType().getName(CONSTANTS) + ")");
            email.addReplyTo(ApplicationProperty.InboundEmailsReplyToAddress.value(),
                    ApplicationProperty.InboundEmailsReplyToAddressName.value());
        } else {
            email.setSubject(event().getName() + " (" + event().getType().getName(CONSTANTS) + ")");
        }

        if (context != null) {
            final FileItem file = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE);
            if (file != null) {
                email.addAttachment(new DataSource() {
                    @Override
                    public OutputStream getOutputStream() throws IOException {
                        throw new IOException("No output stream.");
                    }

                    @Override
                    public String getName() {
                        return file.getName();
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        return file.getInputStream();
                    }

                    @Override
                    public String getContentType() {
                        return file.getContentType();
                    }
                });
            }
        }

        if (attachment() != null)
            email.addAttachment(attachment());

        final String ical = icalendar();
        if (ical != null) {
            email.addAttachment(new DataSource() {
                @Override
                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("No output stream.");
                }

                @Override
                public String getName() {
                    return "event.ics";
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return new ByteArrayInputStream(ical.getBytes("UTF-8"));
                }

                @Override
                public String getContentType() {
                    return "text/calendar; charset=UTF-8";
                }
            });
        }

        email.setHTML(message());

        Long eventId = (response().hasEventWithId() ? response().getEvent().getId()
                : request().getEvent().getId());
        if (eventId != null) {
            String messageId = sMessageId.get(eventId);
            if (messageId != null)
                email.setInReplyTo(messageId);
        }

        email.send();

        if (eventId != null) {
            String messageId = email.getMessageId();
            if (messageId != null)
                sMessageId.put(eventId, messageId);
        }

        response().info(MESSAGES.infoConfirmationEmailSent(
                event().hasContact() ? event().getContact().getName(MESSAGES) : "?"));
    } catch (Exception e) {
        response().error(MESSAGES.failedToSendConfirmationEmail(e.getMessage()));
        sLog.warn(MESSAGES.failedToSendConfirmationEmail(e.getMessage()), e);
    }
}