Example usage for javax.activation FileDataSource FileDataSource

List of usage examples for javax.activation FileDataSource FileDataSource

Introduction

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

Prototype

public FileDataSource(String name) 

Source Link

Document

Creates a FileDataSource from the specified path name.

Usage

From source file:com.email.SendEmail.java

/**
 * Sends a single email and uses account based off of the section that the
 * email comes from after email is sent the attachments are gathered
 * together and collated into a single PDF file and a history entry is
 * created based off of that entry/*  w  w w. ja va2s . c om*/
 *
 * @param eml EmailOutModel
 */
public static void sendEmails(EmailOutModel eml) {
    SystemEmailModel account = null;

    String section = eml.getSection();
    if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED")
            || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) {
        section = eml.getCaseType();
    }

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(section)) {
            account = acc;
            break;
        }
    }

    //Account Exists?
    if (account != null) {
        //Case Location
        String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG"))
                ? FileService.getCaseFolderORGCSCLocation(eml)
                : FileService.getCaseFolderLocation(eml);

        //Attachment List
        boolean allFilesExists = true;
        List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId());

        for (EmailOutAttachmentModel attach : attachmentList) {
            File attachment = new File(casePath + attach.getFileName());
            boolean exists = attachment.exists();
            if (exists == false) {
                allFilesExists = false;
                SECExceptionsModel item = new SECExceptionsModel();
                item.setClassName("SendEmail");
                item.setMethodName("sendEmails");
                item.setExceptionType("FileMissing");
                item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId()
                        + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator()
                        + "File: " + attachment);

                ExceptionHandler.HandleNoException(item);

                break;
            } else {
                if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))
                        || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) {
                    if (!attachment.renameTo(attachment)) {
                        allFilesExists = false;
                        SECExceptionsModel item = new SECExceptionsModel();
                        item.setClassName("SendEmail");
                        item.setMethodName("sendEmails");
                        item.setExceptionType("File In Use");
                        item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId()
                                + System.lineSeparator() + "EmailSubject: " + eml.getSubject()
                                + System.lineSeparator() + "File: " + attachment);

                        ExceptionHandler.HandleNoException(item);
                        break;
                    }
                }
            }
        }

        if (allFilesExists) {
            //Set up Initial Merge Utility
            PDFMergerUtility ut = new PDFMergerUtility();

            //List ConversionPDFs To Delete Later
            List<String> tempPDFList = new ArrayList<>();

            //create email message body
            Date emailSentTime = new Date();
            String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime);

            //Add Email Body To PDF Merge
            try {
                ut.addSource(casePath + emailPDFname);
                tempPDFList.add(casePath + emailPDFname);
            } catch (FileNotFoundException ex) {
                ExceptionHandler.Handle(ex);
            }

            //Get parts
            String FromAddress = account.getEmailAddress();
            String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";"));
            String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";"));
            String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";"));
            String emailSubject = eml.getSubject();
            String emailBody = eml.getBody();

            //Set Email Parts
            Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
            Properties properties = EmailProperties.setEmailOutProperties(account);
            Session session = Session.getInstance(properties, auth);
            MimeMessage smessage = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            //Add Parts to Email Message
            try {
                smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
                for (String To : TOAddressess) {
                    if (EmailValidator.getInstance().isValid(To)) {
                        smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                    }
                }
                for (String CC : CCAddressess) {
                    if (EmailValidator.getInstance().isValid(CC)) {
                        smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC));
                    }
                }
                for (String BCC : BCCAddressess) {
                    if (EmailValidator.getInstance().isValid(BCC)) {
                        smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                    }
                }
                smessage.setSubject(emailSubject);

                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailBody, "text/plain");
                multipart.addBodyPart(messageBodyPart);

                //get attachments
                for (EmailOutAttachmentModel attachment : attachmentList) {
                    String fileName = attachment.getFileName();
                    String extension = FilenameUtils.getExtension(fileName);

                    //Convert attachments to PDF
                    //If Image
                    if (FileService.isImageFormat(fileName)) {
                        fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Word Doc
                    } else if (extension.equals("docx") || extension.equals("doc")) {
                        fileName = WordToPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Text File
                    } else if ("txt".equals(extension)) {
                        fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If PDF
                    } else if (FilenameUtils.getExtension(fileName).equals("pdf")) {

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }
                    }

                    DataSource source = new FileDataSource(casePath + fileName);
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(fileName);
                    multipart.addBodyPart(messageBodyPart);
                }
                smessage.setContent(multipart);

                //Send Message
                if (Global.isOkToSendEmail()) {
                    Transport.send(smessage);
                } else {
                    Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject);
                }

                //DocumentFileName
                String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject())
                        .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf";

                //Set Merge File Destination
                ut.setDestinationFileName(casePath + savedDoc);

                //Try to Merge
                try {
                    ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
                } catch (IOException ex) {
                    ExceptionHandler.Handle(ex);
                }

                //Add emailBody Activity
                addEmailActivity(eml, savedDoc, emailSentTime);

                //Copy to related case folders
                if (section.equals("MED")) {
                    List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml);
                    if (relatedMedList.size() > 0) {
                        for (RelatedCaseModel related : relatedMedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                } else {
                    //This is blanket and should grab all related cases. (UNTESTED outside of CMDS)
                    List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml);
                    if (relatedList.size() > 0) {
                        for (EmailOutRelatedCaseModel related : relatedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationEmailOutRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                }

                //Clean SQL entries
                EmailOut.deleteEmailEntry(eml.getId());
                EmailOutAttachment.deleteAttachmentsForEmail(eml.getId());
                EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId());

                //Clean up temp PDFs
                for (String tempPDF : tempPDFList) {
                    new File(tempPDF).delete();
                }

            } catch (AddressException ex) {
                ExceptionHandler.Handle(ex);
            } catch (MessagingException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Prepares message prior to be sent via execute()-method, i.e. sets
 * properties such as protocol, authentication, etc.
 *
 * @return Message-object to be sent to execute()-method
 * @throws MessagingException/*from  ww w .jav  a  2 s.  co  m*/
 *             when problems constructing or sending the mail occur
 * @throws IOException
 *             when the mail content can not be read or truststore problems
 *             are detected
 */
public Message prepareMessage() throws MessagingException, IOException {

    Properties props = new Properties();

    String protocol = getProtocol();

    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));

    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());

    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils
                    .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }

    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }

    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }

    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info(
                    "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  "
                    + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info(
                        "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()
                                + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : "
                        + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }

    session = Session.getInstance(props, null);

    Message message;

    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) { // i.e. mailBody is empty
                File first = attachments.get(0);
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(first));
                    message.setText(IOUtils.toString(is));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }

    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }

    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }

    if (null != subject) {
        message.setSubject(subject);
    }

    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }

    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }

    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }

    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }

    message.saveChanges();
    return message;
}

From source file:org.wso2.carbon.connector.integration.test.apns.PushNotificationIntegrationTest.java

/**
 * Test case to verify that the connectors works as expected with optional
 * parameters./*from  w w  w.  j  a  v  a  2  s .  c om*/
 * 
 * @throws Exception
 */
@Test(groups = {
        "org.wso2.carbon.connector.apns" }, priority = 1, description = "Integration test to cover optional parameters")
public void testSendPushNotificationOptionalParams() throws Exception {

    // Add proxy service
    String proxyServiceName = "apns_push";

    URL proxyUrl = new URL(
            "file:" + File.separator + File.separator + ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION
                    + ConnectorIntegrationUtil.ESB_CONFIG_LOCATION + File.separator + "proxies" + File.separator
                    + CONNECTOR_NAME + File.separator + proxyServiceName + ".xml");

    proxyAdmin.addProxyService(new DataHandler(proxyUrl));

    // Construct and send the request.

    String environment = PushNotificationRequest.SANDBOX_DESTINATION;
    String certificateAttachmentName = "certificate";
    String password = apnsProperties.getProperty(PROPERTY_KEY_CERTIFICATE_PASSWORD);

    String deviceToken = apnsProperties.getProperty(PROPERTY_KEY_DEVICE_TOKEN);

    String alert = String.format("Test Message : %s", UUID.randomUUID().toString());
    int badge = new Random().nextInt(10);
    String sound = String.format("sound_%s", new Random().nextInt(20));

    String requestTemplate = ConnectorIntegrationUtil.getRequest("with_optional_params");
    String request = String.format(requestTemplate, environment, certificateAttachmentName, password,
            deviceToken, alert, Integer.toString(badge), sound);
    OMElement requestEnvelope = AXIOMUtil.stringToOM(request);

    String certificateFileName = apnsProperties.getProperty(PROPERTY_KEY_APNS_CERTIFICATE_FILENAME);
    Map<String, DataHandler> attachmentMap = new HashMap<String, DataHandler>();
    attachmentMap
            .put(certificateAttachmentName,
                    new DataHandler(new FileDataSource(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION
                            + ConnectorIntegrationUtil.ESB_CONFIG_LOCATION + File.separator + "auth"
                            + File.separator + certificateFileName))));

    OperationClient mepClient = ConnectorIntegrationUtil.buildMEPClientWithAttachment(
            new EndpointReference(getProxyServiceURL(proxyServiceName)), requestEnvelope, attachmentMap);
    try {
        mepClient.execute(true);

        MessageContext responseMsgCtx = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

        OMElement resultParentTag = responseMsgCtx.getEnvelope().getBody()
                .getFirstChildWithName(new QName(NS_URI_APNS, TAG_DISPATCH_TO_DEVICE_RESULT));

        OMElement successfulTag = resultParentTag.getFirstChildWithName(new QName(NS_URI_APNS, TAG_SUCCESSFUL));
        Assert.assertEquals("true", successfulTag.getText());

    } finally {
        proxyAdmin.deleteProxy(proxyServiceName);
    }
}

From source file:gmailclientfx.core.GmailClient.java

public static void sendMessage(String to, String subject, String body, List<String> attachments)
        throws Exception {
    // authenticate with gmail smtp server
    SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true);

    // kreiraj MimeMessage objekt
    MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession());

    // dodaj headere
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(EMAIL));
    msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to));
    msg.setSubject(subject, "UTF-8");
    msg.setReplyTo(InternetAddress.parse(EMAIL, false));

    // tijelo poruke
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setText(body);//from w  w  w .j  av a 2 s .co m

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(msgBodyPart);
    msg.setContent(multipart);

    // dodaj privitke
    if (attachments.size() > 0) {
        for (String attachment : attachments) {
            msgBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            msgBodyPart.setDataHandler(new DataHandler(source));
            msgBodyPart.setFileName(source.getName());
            multipart.addBodyPart(msgBodyPart);
        }
        msg.setContent(multipart);
    }
    smtpTransport.sendMessage(msg, InternetAddress.parse(to));

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Poruka poslana!");
    alert.setHeaderText(null);
    alert.setContentText("Email uspjeno poslan!");
    alert.showAndWait();
}

From source file:org.wso2.carbon.wsdl2code.WSDL2Code.java

private CodegenDownloadData getJaxWSCodegenDownloadData(ConfigurationContext configContext,
        String codegenOutputDir, ArrayList<String> optionsList, HashMap<String, String> projOptionsList)
        throws AxisFault {
    String uuid;//  w  w  w.ja  v  a2s. c  o m
    optionsList.add("-frontend");
    optionsList.add("jaxws21");
    optionsList.add("-client");

    String[] args = optionsList.toArray(new String[optionsList.size()]);

    try {
        (new POMGenerator()).generateJaxWSClient(optionsList, codegenOutputDir, projOptionsList);
    } catch (Exception e) {
        String rootMsg = "Code generation failed";
        Throwable throwable = e.getCause();
        if (throwable != null) {
            String msg = throwable.getMessage();
            if (msg != null) {
                log.error(rootMsg + " " + msg, throwable);
                throw new AxisFault(throwable.toString());
            }
        }
        log.error(rootMsg, e);
        throw AxisFault.makeFault(e);
    }

    try {
        //achive destination
        uuid = String.valueOf(System.currentTimeMillis() + Math.random());
        File destDir = new File(configContext.getProperty(ServerConstants.WORK_DIR) + File.separator
                + "tools_codegen" + File.separator + uuid);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        //String destFileName = uuid.substring(2) + ".zip";
        String destFileName = getJAXWSRSProjectname(optionsList) + "-Client.zip";
        String destArchive = destDir.getAbsolutePath() + File.separator + destFileName;

        new ArchiveManipulator().archiveDir(destArchive, new File(codegenOutputDir).getPath());
        FileManipulator.deleteDir(new File(codegenOutputDir));

        DataHandler handler;
        if (destArchive != null) {
            File file = new File(destArchive);
            FileDataSource datasource = new FileDataSource(file);
            handler = new DataHandler(datasource);

            CodegenDownloadData data = new CodegenDownloadData();
            data.setFileName(file.getName());
            data.setCodegenFileData(handler);
            return data;
        } else {
            return null;
        }

    } catch (IOException e) {
        String msg = WSDL2Code.class.getName() + " IOException has occured.";
        log.error(msg, e);
        throw new AxisFault(msg, e);
    }
}

From source file:at.gv.egiz.pdfas.cli.Main.java

private static void perform_sign(CommandLine cli) throws Exception {

    String configurationFile = null;

    if (cli.hasOption(CLI_ARG_CONF_SHORT)) {
        configurationFile = cli.getOptionValue(CLI_ARG_CONF_SHORT);
    } else {//from w w  w  . j a  v  a 2 s . c  o m
        configurationFile = STANDARD_CONFIG_LOCATION;
        deployConfigIfNotexisting();
    }

    String positionString = null;

    if (cli.hasOption(CLI_ARG_POSITION_SHORT)) {
        positionString = cli.getOptionValue(CLI_ARG_POSITION_SHORT);
    } else {
        positionString = null;
    }

    String profilID = null;

    if (cli.hasOption(CLI_ARG_PROFILE_SHORT)) {
        profilID = cli.getOptionValue(CLI_ARG_PROFILE_SHORT);
    }

    String outputFile = null;

    if (cli.hasOption(CLI_ARG_OUTPUT_SHORT)) {
        outputFile = cli.getOptionValue(CLI_ARG_OUTPUT_SHORT);
    }

    String connector = null;

    if (cli.hasOption(CLI_ARG_CONNECTOR_SHORT)) {
        connector = cli.getOptionValue(CLI_ARG_CONNECTOR_SHORT);
    }

    String pdfFile = null;

    pdfFile = cli.getArgs()[cli.getArgs().length - 1];

    File inputFile = new File(pdfFile);

    if (!inputFile.exists()) {
        throw new Exception("Input file does not exists");
    }

    if (outputFile == null) {
        if (pdfFile.endsWith(".pdf")) {
            outputFile = pdfFile.subSequence(0, pdfFile.length() - ".pdf".length()) + "_signed.pdf";
        } else {
            outputFile = pdfFile + "_signed.pdf";
        }
    }

    File outputPdfFile = new File(outputFile);

    DataSource dataSource = new FileDataSource(inputFile);

    PdfAs pdfAs = null;

    pdfAs = PdfAsFactory.createPdfAs(new File(configurationFile));

    Configuration configuration = pdfAs.getConfiguration();
    FileOutputStream fos = new FileOutputStream(outputPdfFile, false);
    SignParameter signParameter = PdfAsFactory.createSignParameter(configuration, dataSource, fos);

    String id = UUID.randomUUID().toString();
    signParameter.setTransactionId(id);
    System.out.println("Transaction: " + id);

    IPlainSigner slConnector = null;

    if (connector != null) {
        if (connector.equalsIgnoreCase("bku")) {
            slConnector = new PAdESSigner(new BKUSLConnector(configuration));
        } else if (connector.equalsIgnoreCase("moa")) {
            slConnector = new PAdESSigner(new MOAConnector(configuration));
        } else if (connector.equalsIgnoreCase("ks")) {
            String keystoreFilename = null;
            String keystoreAlias = null;
            String keystoreType = null;
            String keystoreStorepass = null;
            String keystoreKeypass = null;

            if (cli.hasOption(CLI_ARG_KEYSTORE_FILE_SHORT)) {
                keystoreFilename = cli.getOptionValue(CLI_ARG_KEYSTORE_FILE_SHORT);
            }

            if (cli.hasOption(CLI_ARG_KEYSTORE_ALIAS_SHORT)) {
                keystoreAlias = cli.getOptionValue(CLI_ARG_KEYSTORE_ALIAS_SHORT);
            }
            if (cli.hasOption(CLI_ARG_KEYSTORE_TYPE_SHORT)) {
                keystoreType = cli.getOptionValue(CLI_ARG_KEYSTORE_TYPE_SHORT);
            }
            if (cli.hasOption(CLI_ARG_KEYSTORE_STOREPASS_SHORT)) {
                keystoreStorepass = cli.getOptionValue(CLI_ARG_KEYSTORE_STOREPASS_SHORT);
            }
            if (cli.hasOption(CLI_ARG_KEYSTORE_KEYPASS_SHORT)) {
                keystoreKeypass = cli.getOptionValue(CLI_ARG_KEYSTORE_KEYPASS_SHORT);
            }

            if (keystoreFilename == null) {
                throw new Exception("You need to provide a keystore file if using ks connector");
            }
            if (keystoreAlias == null) {
                throw new Exception("You need to provide a key alias if using ks connector");
            }
            if (keystoreType == null) {
                keystoreType = "PKCS12";
                System.out.println("Defaulting to " + keystoreType + " keystore type.");
            }

            if (keystoreStorepass == null) {
                keystoreStorepass = "";
            }

            if (keystoreKeypass == null) {
                keystoreKeypass = "";
            }

            slConnector = new PAdESSignerKeystore(keystoreFilename, keystoreAlias, keystoreStorepass,
                    keystoreKeypass, keystoreType);
        }
    }
    if (slConnector == null) {
        slConnector = new PAdESSigner(new BKUSLConnector(configuration));
    }

    signParameter.setPlainSigner(slConnector);
    signParameter.setDataSource(dataSource);
    signParameter.setSignaturePosition(positionString);
    signParameter.setSignatureProfileId(profilID);
    System.out.println("Starting signature for " + pdfFile);
    System.out.println("Selected signature Profile " + profilID);

    SignResult result = null;
    try {
        result = pdfAs.sign(signParameter);
    } finally {
        if (result != null) {
            Iterator<Entry<String, String>> infoIt = result.getProcessInformations().entrySet().iterator();

            while (infoIt.hasNext()) {
                Entry<String, String> infoEntry = infoIt.next();
                logger.debug("Process Information: {} = {}", infoEntry.getKey(), infoEntry.getValue());
            }
        }
    }

    fos.close();
    System.out.println("Signed document " + outputFile);
}

From source file:org.wso2.carbon.humantask.core.mgt.services.HumanTaskPackageManagementSkeleton.java

public HumanTaskPackageDownloadData downloadHumanTaskPackage(String packageName)
        throws PackageManagementException {

    File humanTaskArchive = getTenantTaskStore().getHumanTaskArchiveLocation(packageName);

    DataHandler handler;//from  w w  w . ja  v  a  2s. co m
    if (humanTaskArchive != null) {
        FileDataSource dataSource = new FileDataSource(humanTaskArchive);
        handler = new DataHandler(dataSource);

        HumanTaskPackageDownloadData data = new HumanTaskPackageDownloadData();
        data.setPackageName(humanTaskArchive.getName());
        data.setPackageFileData(handler);
        return data;
    } else {
        return null;
    }
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * //from   ww  w  .  j a  v a  2  s  . c  o  m
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    String name = attachment.getFilename();
    byte[] stream = attachment.getContent();
    File temp = File.createTempFile("tmpfile", ".tmp");
    FileOutputStream fos = new FileOutputStream(temp);
    fos.write(stream);
    fos.close();
    DataSource source = new FileDataSource(temp);
    MimeBodyPart part = new MimeBodyPart();
    String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

    part.setDataHandler(new DataHandler(source));
    part.setHeader("Content-Type", mimeType);
    part.setFileName(name);
    part.setContentID("<" + name + ">");
    part.setDisposition("inline");

    temp.deleteOnExit();

    return part;
}

From source file:com.clustercontrol.infra.util.InfraEndpointWrapper.java

public void addInfraFile(InfraFileInfo info, String filePath)
        throws HinemosUnknown_Exception, InfraFileTooLarge_Exception, InvalidRole_Exception,
        InvalidUserPass_Exception, InfraManagementDuplicate_Exception {
    WebServiceException wse = null;
    for (EndpointSetting<InfraEndpoint> endpointSetting : getInfraEndpoint(endpointUnit)) {
        try {// w ww  .  ja va  2s. c o  m
            InfraEndpoint endpoint = endpointSetting.getEndpoint();
            endpoint.addInfraFile(info, new DataHandler(new FileDataSource(filePath)));
            return;
        } catch (WebServiceException e) {
            wse = e;
            m_log.warn("addInfraFile(), " + e.getMessage());
            endpointUnit.changeEndpoint();
        }
    }
    throw wse;
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param pathToFile The complete path to the file - including file name.
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart./*from  w  ww. j  a  v  a 2 s  .co m*/
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final String pathToFile, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(pathToFile) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}