Example usage for javax.activation DataSource getInputStream

List of usage examples for javax.activation DataSource getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

This method returns an InputStream representing the data and throws the appropriate exception if it can not do so.

Usage

From source file:org.shredzone.cilla.service.impl.PictureServiceImpl.java

@Override
@CacheEvict(value = "processedImages", allEntries = true)
public void updatePicture(Picture picture, DataSource source) throws CillaServiceException {
    if (picture.getId() == 0) {
        throw new IllegalArgumentException("picture is not persisted");
    }/* ww w  .j a va 2  s . c o  m*/

    if (source != null) {
        try {
            Store store = picture.getImage();
            store.setContentType(source.getContentType());
            store.setName(source.getName());
            store.setLastModified(new Date());

            Dimension dim = imageProcessor.analyzeDimension(source);
            if (dim != null) {
                picture.setWidth(dim.width);
                picture.setHeight(dim.height);
            }

            ExifAnalyzer exif = imageProcessor.createExifAnalyzer(source);
            if (exif != null) {
                picture.setCreateDate(exif.getDateTime(picture.getCreateTimeZone()));
                picture.setExifData(exif.getExifData());
                picture.setLocation(exif.getGeolocation());
            } else {
                picture.setCreateDate(null);
                picture.setExifData(null);
                picture.setLocation(null);
            }

            ResourceDataSource ds = storeDao.access(store);
            FileCopyUtils.copy(source.getInputStream(), ds.getOutputStream());
        } catch (IOException ex) {
            throw new CillaServiceException("Could not read medium", ex);
        }
    }

    eventService.fireEvent(new Event<Picture>(EventType.GALLERY_PICTURE_UPDATE, picture));
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

@Override
public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status) throws DAOException {
    try {// w  w  w .jav  a2 s.  c  o  m
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    Date timestamp = new Date();
                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            message.getMessageHeader().getCPAId(),
                            message.getMessageHeader().getConversationId(),
                            message.getMessageOrder() == null ? null
                                    : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                            message.getMessageHeader().getMessageData().getMessageId(),
                            message.getMessageHeader().getMessageData().getRefToMessageId(),
                            message.getMessageHeader().getFrom().getRole(),
                            message.getMessageHeader().getTo().getRole(),
                            message.getMessageHeader().getService().getType(),
                            message.getMessageHeader().getService().getValue(),
                            message.getMessageHeader().getAction(), message.getOriginal(),
                            XMLMessageBuilder.getInstance(SignatureType.class)
                                    .handle(new ObjectFactory().createSignature(message.getSignature())),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(message.getMessageHeader()),
                            XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                            XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                            XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                            XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()),
                            status), keyHolder);

                    for (DataSource attachment : message.getAttachments()) {
                        simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name,"
                                + "content_type," + "content" + ") values (?,?,?,?)",
                                keyHolder.getKey().longValue(),
                                attachment.getName() == null ? Constants.DEFAULT_FILENAME
                                        : attachment.getName(),
                                attachment.getContentType().split(";")[0].trim(),
                                IOUtils.toByteArray(attachment.getInputStream()));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        });
    } catch (RuntimeException e) {
        throw new DAOException(e);
    }
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

@Override
public void insertMessage(final EbMSMessage message, final List<EbMSSendEvent> sendEvents) throws DAOException {
    try {/* w w  w  .j ava 2  s  . c o m*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    Date timestamp = new Date();
                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            message.getMessageHeader().getCPAId(),
                            message.getMessageHeader().getConversationId(),
                            message.getMessageOrder() == null ? null
                                    : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                            message.getMessageHeader().getMessageData().getMessageId(),
                            message.getMessageHeader().getMessageData().getRefToMessageId(),
                            message.getMessageHeader().getFrom().getRole(),
                            message.getMessageHeader().getTo().getRole(),
                            message.getMessageHeader().getService().getType(),
                            message.getMessageHeader().getService().getValue(),
                            message.getMessageHeader().getAction(),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(message.getMessageHeader()),
                            XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                            XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                            XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                            XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest())),
                            keyHolder);

                    for (DataSource attachment : message.getAttachments()) {
                        simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name,"
                                + "content_type," + "content" + ") values (?,?,?,?)",
                                keyHolder.getKey().longValue(),
                                attachment.getName() == null ? Constants.DEFAULT_FILENAME
                                        : attachment.getName(),
                                attachment.getContentType().split(";")[0].trim(),
                                IOUtils.toByteArray(attachment.getInputStream()));
                    }

                    List<Object[]> events = new ArrayList<Object[]>();
                    for (EbMSSendEvent sendEvent : sendEvents) {
                        //events.add(new Object[]{keyHolder.getKey().longValue(),String.format(getDateFormat(),sendEvent.getTime())});
                        events.add(new Object[] { keyHolder.getKey().longValue(), sendEvent.getTime() });
                    }
                    simpleJdbcTemplate.batchUpdate(
                            "insert into ebms_send_event (" + "ebms_message_id," + "time" + ") values (?,?)",
                            events);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        });
    } catch (RuntimeException e) {
        throw new DAOException(e);
    }
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

@Override
public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status,
        final EbMSMessageError messageError, final EbMSSendEvent sendEvent) throws DAOException {
    try {/*ww  w  .j  ava2  s.c om*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    Date timestamp = new Date();
                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            message.getMessageHeader().getCPAId(),
                            message.getMessageHeader().getConversationId(),
                            message.getMessageOrder() == null ? null
                                    : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                            message.getMessageHeader().getMessageData().getMessageId(),
                            message.getMessageHeader().getMessageData().getRefToMessageId(),
                            message.getMessageHeader().getFrom().getRole(),
                            message.getMessageHeader().getTo().getRole(),
                            message.getMessageHeader().getService().getType(),
                            message.getMessageHeader().getService().getValue(),
                            message.getMessageHeader().getAction(), message.getOriginal(),
                            XMLMessageBuilder.getInstance(SignatureType.class)
                                    .handle(new ObjectFactory().createSignature(message.getSignature())),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(message.getMessageHeader()),
                            XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                            XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                            XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                            XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()),
                            status), keyHolder);

                    for (DataSource attachment : message.getAttachments()) {
                        simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name,"
                                + "content_type," + "content" + ") values (?,?,?,?)",
                                keyHolder.getKey().longValue(),
                                attachment.getName() == null ? Constants.DEFAULT_FILENAME
                                        : attachment.getName(),
                                attachment.getContentType().split(";")[0].trim(),
                                IOUtils.toByteArray(attachment.getInputStream()));
                    }

                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            messageError.getMessageHeader().getCPAId(),
                            messageError.getMessageHeader().getConversationId(),
                            messageError.getMessageHeader().getMessageData().getMessageId(),
                            messageError.getMessageHeader().getMessageData().getRefToMessageId(),
                            messageError.getMessageHeader().getFrom().getRole(),
                            messageError.getMessageHeader().getTo().getRole(),
                            messageError.getMessageHeader().getService().getType(),
                            messageError.getMessageHeader().getService().getValue(),
                            messageError.getMessageHeader().getAction(),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(messageError.getMessageHeader()),
                            XMLMessageBuilder.getInstance(ErrorList.class).handle(messageError.getErrorList())),
                            keyHolder);

                    simpleJdbcTemplate.update(
                            "insert into ebms_send_event (" + "ebms_message_id," + "time" + ") values (?,?)",
                            keyHolder.getKey().longValue(),
                            //String.format(getDateFormat(),sendEvent.getTime())
                            sendEvent.getTime());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        });
    } catch (RuntimeException e) {
        throw new DAOException(e);
    }
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

@Override
public void insertMessage(final EbMSMessage message, final EbMSMessageStatus status,
        final EbMSAcknowledgment acknowledgment, final EbMSSendEvent sendEvent) throws DAOException {
    try {//w ww.  ja v  a  2s. c  o m
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {
                    Date timestamp = new Date();
                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            message.getMessageHeader().getCPAId(),
                            message.getMessageHeader().getConversationId(),
                            message.getMessageOrder() == null ? null
                                    : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                            message.getMessageHeader().getMessageData().getMessageId(),
                            message.getMessageHeader().getMessageData().getRefToMessageId(),
                            message.getMessageHeader().getFrom().getRole(),
                            message.getMessageHeader().getTo().getRole(),
                            message.getMessageHeader().getService().getType(),
                            message.getMessageHeader().getService().getValue(),
                            message.getMessageHeader().getAction(), message.getOriginal(),
                            XMLMessageBuilder.getInstance(SignatureType.class)
                                    .handle(new ObjectFactory().createSignature(message.getSignature())),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(message.getMessageHeader()),
                            XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                            XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                            XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                            XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()),
                            status), keyHolder);

                    for (DataSource attachment : message.getAttachments()) {
                        simpleJdbcTemplate.update("insert into ebms_attachment (" + "ebms_message_id," + "name,"
                                + "content_type," + "content" + ") values (?,?,?,?)",
                                keyHolder.getKey().longValue(),
                                attachment.getName() == null ? Constants.DEFAULT_FILENAME
                                        : attachment.getName(),
                                attachment.getContentType().split(";")[0].trim(),
                                IOUtils.toByteArray(attachment.getInputStream()));
                    }

                    jdbcTemplate.update(getEbMSMessagePreparedStatement(timestamp,
                            acknowledgment.getMessageHeader().getCPAId(),
                            acknowledgment.getMessageHeader().getConversationId(),
                            acknowledgment.getMessageHeader().getMessageData().getMessageId(),
                            acknowledgment.getMessageHeader().getMessageData().getRefToMessageId(),
                            acknowledgment.getMessageHeader().getFrom().getRole(),
                            acknowledgment.getMessageHeader().getTo().getRole(),
                            acknowledgment.getMessageHeader().getService().getType(),
                            acknowledgment.getMessageHeader().getService().getValue(),
                            acknowledgment.getMessageHeader().getAction(),
                            XMLMessageBuilder.getInstance(MessageHeader.class)
                                    .handle(acknowledgment.getMessageHeader()),
                            XMLMessageBuilder.getInstance(Acknowledgment.class)
                                    .handle(acknowledgment.getAcknowledgment())),
                            keyHolder);

                    simpleJdbcTemplate.update(
                            "insert into ebms_send_event (" + "ebms_message_id," + "time" + ") values (?,?)",
                            keyHolder.getKey().longValue(),
                            //String.format(getDateFormat(),sendTime)
                            sendEvent.getTime());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        });
    } catch (RuntimeException e) {
        throw new DAOException(e);
    }
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void importContentStoreDump(RemoteSession session, DataSource csDump, String dbKey, boolean includeACL,
        boolean includeSystemAreas) throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }/*from ww w  .  j  a v  a 2s .  co m*/

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    try {
        WGDatabase db = retrieveAndOpenDB(session, dbKey);
        if (db != null && db.isSessionOpen()) {
            _core.importContentStoreDump(new ZipInputStream(csDump.getInputStream()), db, _core.getLog(),
                    includeACL, includeSystemAreas);
        } else {
            throw new WGAServiceException("Unable to open database '" + dbKey + "'.");
        }
        // reconnect cs
        _core.removeContentDB(dbKey);
        _core.updateContentDBs();
    } catch (Exception e) {
        throw new WGAServiceException("Import of content store dump failed for database '" + dbKey + "'.", e);
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *//*from   www. j  a  v a 2  s . c  o m*/
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet.java

/**
 * Handles the reception of a STORK response message
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*w  w  w .j  a v  a  2s.  c  om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pendingRequestID = null;

    try {

        Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

        Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
        Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));

        super.setNoCachingHeadersInHttpRespone(request, response);
        Logger.trace("No Caching headers set for HTTP response");

        //check if https or only http
        super.checkIfHTTPisAllowed(request.getRequestURL().toString());

        Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");

        //extract STORK Response from HTTP Request
        //Decodes SAML Response
        byte[] decSamlToken;
        try {
            decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
            Logger.debug("SAMLResponse: " + new String(decSamlToken));

        } catch (NullPointerException e) {
            Logger.error("Unable to retrieve STORK Response", e);
            throw new MOAIDException("stork.04", null);
        }

        //Get SAMLEngine instance
        STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");

        STORKAuthnResponse authnResponse = null;
        try {
            //validate SAML Token
            Logger.debug("Starting validation of SAML response");
            authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost());
            Logger.info("SAML response succesfully verified!");
        } catch (STORKSAMLEngineException e) {
            Logger.error("Failed to verify STORK SAML Response", e);
            throw new MOAIDException("stork.05", null);
        }

        Logger.info("STORK SAML Response message succesfully extracted");
        Logger.debug("STORK response: ");
        Logger.debug(authnResponse.toString());

        Logger.debug("Trying to find MOA Session-ID ...");
        //String moaSessionID = request.getParameter(PARAM_SESSIONID);
        //first use SAML2 relayState 
        String moaSessionID = request.getParameter("RelayState");

        // escape parameter strings
        moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

        //check if SAML2 relaystate includes a MOA sessionID
        if (StringUtils.isEmpty(moaSessionID)) {
            //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier

            moaSessionID = authnResponse.getInResponseTo();
            moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

            if (StringUtils.isEmpty(moaSessionID)) {
                //No authentication session has been started before
                Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
                Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
                throw new AuthenticationException("auth.02", new Object[] { moaSessionID });

            } else
                Logger.trace(
                        "Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");

        } else
            //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
            Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");

        /*INFO!!!!
         * SAML message IDs has an different format then MOASessionIDs
         * This is only a workaround because many PEPS does not support SAML2 relayState or
         * MOASessionID as AttributConsumerServiceURL GET parameter
        */
        //            if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
        //                throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");

        pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);

        //load MOASession from database
        AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
        //change MOASessionID
        moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Found MOA sessionID: " + moaSessionID);

        String statusCodeValue = authnResponse.getStatusCode();

        if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
            Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
            throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
        }

        Logger.info("Got SAML response with authentication success message.");

        Logger.debug("MOA session is still valid");

        STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();

        if (storkAuthnRequest == null) {
            Logger.error(
                    "Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
            throw new MOAIDException("stork.07", null);
        }

        OAAuthParameter oaParam = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
        if (oaParam == null)
            throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
        //================== Check QAA level start ====================
        int reqQaa = -1;
        int authQaa = -1;
        String authQaaStr = null;
        try {
            reqQaa = storkAuthnRequest.getQaa();

            //TODO: found better solution, but QAA Level in response could be not supported yet
            try {

                authQaaStr = authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext()
                        .getAuthnContextClassRef().getAuthnContextClassRef();
                moaSession.setQAALevel(authQaaStr);

            } catch (Throwable e) {
                Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
                moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
                authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
            }
            if (authQaaStr != null)//Check value only if set
            {
                authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length()));
                //               authQaa = Integer.valueOf(authQaaStr);
                if (reqQaa > authQaa) {
                    Logger.warn("Requested QAA level does not match to authenticated QAA level");
                    throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa });

                }
            }
        } catch (MOAIDException e) {
            throw e;

        } catch (Exception e) {
            if (Logger.isDebugEnabled())
                Logger.warn("STORK QAA Level evaluation error", e);

            else
                Logger.warn("STORK QAA Level evaluation error (ErrorMessage=" + e.getMessage() + ")");

            throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa });

        }
        //================== Check QAA level end ====================

        Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);

        ////////////// incorporate gender from parameters if not in stork response

        IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();

        // but first, check if we have a representation case
        if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
                || STORKResponseProcessor.hasAttribute("representative", attributeList)
                || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
            // in a representation case...
            moaSession.setUseMandate("true");

            // and check if we have the gender value
            PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if there is no representation case?
            if (null == gender) {
                String gendervalue = (String) request.getParameter("gender");
                if (null != gendervalue) {
                    gender = new PersonalAttribute();
                    gender.setName("gender");
                    ArrayList<String> tmp = new ArrayList<String>();
                    tmp.add(gendervalue);
                    gender.setValue(tmp);

                    authnResponse.getPersonalAttributeList().add(gender);
                }
            }
        }

        //////////////////////////////////////////////////////////////////////////

        Logger.debug("Starting extraction of signedDoc attribute");
        //extract signed doc element and citizen signature
        String citizenSignature = null;
        try {
            String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING

            Logger.debug("signatureInfo:" + signatureInfo);

            SignResponse dssSignResponse = (SignResponse) ApiUtils
                    .unmarshal(new StreamSource(new java.io.StringReader(signatureInfo)));

            // fetch signed doc
            DataSource ds = null;
            try {
                ds = LightweightSourceResolver.getDataSource(dssSignResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ds == null) {
                //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500 
                //which results in an exception and ds==null

                //try to load document from documentservice
                citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
                //throw new ApiUtilsException("No datasource found in response");
            } else {
                InputStream incoming = ds.getInputStream();
                citizenSignature = IOUtils.toString(incoming);
                incoming.close();

                Logger.debug("citizenSignature:" + citizenSignature);
                if (isDocumentServiceUsed(citizenSignature) == true) {
                    citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
                    //               Logger.debug("Loading document from DocumentService.");
                    //               String url = getDtlUrlFromResponse(dssSignResponse);
                    //               //get Transferrequest
                    //               String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
                    //               //Load document from DocumentService
                    //               byte[] data = getDocumentFromDtl(transferRequest, url);
                    //               citizenSignature = new String(data, "UTF-8");
                    //               Logger.debug("Overridung citizenSignature with:"+citizenSignature);
                }
            }
            JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
            SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller()
                    .unmarshal(IOUtils.toInputStream(citizenSignature))).getValue();

            // memorize signature into authblock
            moaSession.setAuthBlock(citizenSignature);

            // extract certificate
            for (Object current : root.getKeyInfo().getContent())
                if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
                    for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
                            .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
                        if (casted.getName().getLocalPart().equals("X509Certificate")) {
                            moaSession.setSignerCertificate(
                                    new X509Certificate(((String) casted.getValue()).getBytes("UTF-8")));
                            break;
                        }
                    }
                }

        } catch (Throwable e) {
            Logger.error("Could not extract citizen signature from C-PEPS", e);
            throw new MOAIDException("stork.09", null);
        }
        Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
        Logger.debug("Citizen signature will be verified by SZR Gateway!");

        Logger.debug("fetching OAParameters from database");

        //         //read configuration paramters of OA
        //           AuthenticationSession moasession;
        //         try {
        //            moasession = AuthenticationSessionStoreage.getSession(moaSessionID);
        //         } catch (MOADatabaseException e2) {
        //            Logger.error("could not retrieve moa session");
        //            throw new AuthenticationException("auth.01", null);
        //         }
        //          OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
        //          if (oaParam == null)
        //                throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });

        // retrieve target
        //TODO: check in case of SSO!!!
        String targetType = null;
        if (oaParam.getBusinessService()) {
            String id = oaParam.getIdentityLinkDomainIdentifier();
            if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
                targetType = id;
            else
                targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
        } else {
            targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
        }

        IdentityLink identityLink = null;
        try {
            AuthConfigurationProvider config = AuthConfigurationProvider.getInstance();
            if (config.isStorkFakeIdLActive()
                    && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
                // create fake IdL
                // - fetch IdL template from resources
                InputStream s = PEPSConnectorServlet.class
                        .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml");
                Element idlTemplate = DOMUtils.parseXmlValidating(s);

                identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink();

                // replace data
                Element idlassertion = identityLink.getSamlAssertion();
                // - set bpk/wpbk;
                Node prIdentification = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH);
                if (!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList))
                    throw new STORKException("eIdentifier is missing");
                String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList,
                        false);
                prIdentification.getFirstChild().setNodeValue(eIdentifier);

                // - set last name
                Node prFamilyName = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH);
                if (!STORKResponseProcessor.hasAttribute("surname", attributeList))
                    throw new STORKException("surname is missing");
                String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false);
                prFamilyName.getFirstChild().setNodeValue(familyName);

                // - set first name
                Node prGivenName = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH);
                if (!STORKResponseProcessor.hasAttribute("givenName", attributeList))
                    throw new STORKException("givenName is missing");
                String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false);
                prGivenName.getFirstChild().setNodeValue(givenName);

                // - set date of birth
                Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH);
                if (!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList))
                    throw new STORKException("dateOfBirth is missing");
                String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList,
                        false);
                prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth);

                identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink();

                //resign IDL
                IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance();
                Element resignedilAssertion = identitylinkresigner.resignIdentityLink(
                        identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey());
                identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink();
            } else {
                //contact SZR Gateway
                Logger.debug("Starting connecting SZR Gateway");
                identityLink = STORKResponseProcessor.connectToSZRGateway(
                        authnResponse.getPersonalAttributeList(), oaParam.getFriendlyName(), targetType, null,
                        oaParam.getMandateProfiles(), citizenSignature);
            }
        } catch (STORKException e) {
            // this is really nasty but we work against the system here. We are supposed to get the gender attribute from
            // stork. If we do not, we cannot register the person in the ERnP - we have to have the
            // gender for the represented person. So here comes the dirty hack. 
            if (e.getCause() instanceof STORKException
                    && e.getCause().getMessage().equals("gender not found in response")) {
                try {
                    Logger.trace("Initialize VelocityEngine...");

                    VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
                    Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
                    VelocityContext context = new VelocityContext();
                    context.put("SAMLResponse", request.getParameter("SAMLResponse"));
                    context.put("action", request.getRequestURL());

                    StringWriter writer = new StringWriter();
                    template.merge(context, writer);

                    response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
                } catch (Exception e1) {
                    Logger.error("Error sending gender retrival form.", e1);
                    //                  httpSession.invalidate();
                    throw new MOAIDException("stork.10", null);
                }

                return;
            }

            Logger.error("Error connecting SZR Gateway", e);
            throw new MOAIDException("stork.10", null);
        }
        Logger.debug("SZR communication was successfull");

        if (identityLink == null) {
            Logger.error("SZR Gateway did not return an identity link.");
            throw new MOAIDException("stork.10", null);
        }
        moaSession.setForeigner(true);

        Logger.info("Received Identity Link from SZR Gateway");
        moaSession.setIdentityLink(identityLink);

        Logger.debug("Adding addtional STORK attributes to MOA session");
        moaSession.setStorkAttributes(authnResponse.getPersonalAttributeList());

        Logger.debug("Add full STORK AuthnResponse to MOA session");
        moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));

        //We don't have BKUURL, setting from null to "Not applicable"
        moaSession.setBkuURL("Not applicable (STORK Authentication)");

        // free for single use
        moaSession.setAuthenticatedUsed(false);

        // stork did the authentication step
        moaSession.setAuthenticated(true);

        //         //TODO: found better solution, but QAA Level in response could be not supported yet
        //         try {
        //
        //            moaSession.setQAALevel(authnResponse.getAssertions().get(0).
        //                  getAuthnStatements().get(0).getAuthnContext().
        //                  getAuthnContextClassRef().getAuthnContextClassRef());
        //            
        //         } catch (Throwable e) {
        //            Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
        //            moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
        //            
        //         }

        //session is implicit stored in changeSessionID!!!!
        String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);

        //redirect
        String redirectURL = null;
        redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
                ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
                newMOASessionID);
        redirectURL = response.encodeRedirectURL(redirectURL);

        //          response.setContentType("text/html");
        //          response.setStatus(302);
        //          response.addHeader("Location", redirectURL);
        response.sendRedirect(redirectURL);
        Logger.info("REDIRECT TO: " + redirectURL);

    } catch (AuthenticationException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (MOAIDException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (Exception e) {
        Logger.error("PEPSConnector has an interal Error.", e);
    }

    finally {
        ConfigurationDBUtils.closeSession();
    }

}

From source file:org.shredzone.cilla.service.impl.PictureServiceImpl.java

@Override
public void addPicture(GallerySection section, Picture picture, DataSource source)
        throws CillaServiceException {
    if (picture.getId() != 0) {
        throw new IllegalArgumentException("picture is already persisted, id " + picture.getId());
    }/*from  w  w  w  .j  a v  a  2s .c o m*/
    if (section.getId() == 0) {
        throw new IllegalArgumentException("section is not persisted");
    }
    if (source == null) {
        throw new IllegalArgumentException("DataSource is not set");
    }

    try {
        Store store = picture.getImage();
        store.setContentType(source.getContentType());
        store.setName(source.getName());
        store.setLastModified(new Date());

        Dimension dim = imageProcessor.analyzeDimension(source);
        if (dim != null) {
            picture.setWidth(dim.width);
            picture.setHeight(dim.height);
        }

        ExifAnalyzer exif = imageProcessor.createExifAnalyzer(source);
        if (exif != null) {
            TimeZone tz = picture.getCreateTimeZone();
            if (tz == null) {
                tz = section.getDefaultTimeZone();
            }
            picture.setCreateDate(exif.getDateTime(tz));
            picture.setExifData(exif.getExifData());
            picture.setLocation(exif.getGeolocation());
        } else {
            picture.setCreateDate(null);
            picture.setExifData(null);
            picture.setLocation(null);
        }

        picture.setGallery(section);
        section.getPictures().add(picture);
        pictureDao.persist(picture);

        ResourceDataSource ds = storeDao.access(store);
        FileCopyUtils.copy(source.getInputStream(), ds.getOutputStream());
    } catch (IOException ex) {
        throw new CillaServiceException("Could not read medium", ex);
    }

    eventService.fireEvent(new Event<Picture>(EventType.GALLERY_PICTURE_NEW, picture));
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void updateFSDesignResource(RemoteSession session, String path, DataSource content, long lastModified)
        throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }/*from   w  ww.j  av  a  2s  .c  o m*/

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    WGADesignSource source = _core.getDesignManager().getDesignSources()
            .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
    if (source instanceof FileSystemDesignSource) {
        FileSystemDesignSource fsSource = (FileSystemDesignSource) source;
        try {
            fsSource.getDir().refresh();
            FileObject resource = fsSource.getDir().resolveFile(path);

            String basePath = fsSource.getDir().getURL().getPath();
            String resourcePath = resource.getURL().getPath();
            if (!resourcePath.startsWith(basePath)) {
                throw new WGAServiceException(
                        new IllegalArgumentException("Illegal design resource path '" + path + "'."));
            }

            resource.createFile();
            OutputStream out = resource.getContent().getOutputStream();
            InputStream in = content.getInputStream();
            WGUtils.inToOut(in, out, 1024);
            out.close();
            in.close();
            resource.getContent().setLastModifiedTime(lastModified);

            clearDesignFileCache(fsSource, fsSource.getDir().getName().getRelativeName(resource.getName()));

        } catch (FileSystemException e) {
            //            throw new WGAServiceException("Updating FSDesignResource '" + path + "' failed.", e);
        } catch (IOException e) {
            throw new WGAServiceException("Updating FSDesignResource '" + path + "' failed.", e);
        }
    }
}