Example usage for org.apache.commons.io FileUtils writeByteArrayToFile

List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeByteArrayToFile.

Prototype

public static void writeByteArrayToFile(File file, byte[] data) throws IOException 

Source Link

Document

Writes a byte array to a file creating the file if it does not exist.

Usage

From source file:com.aliyun.odps.mapred.unittest.MRUnitTest.java

private void processResources(JobConf job, UTContext context) throws IOException {

    RuntimeContext ctx = context.getRuntimeContext();

    // process files
    Map<String, byte[]> fileResources = context.getFileResources();
    for (Map.Entry<String, byte[]> entry : fileResources.entrySet()) {
        LOG.info("process file resource: " + entry.getKey());
        File resFile = new File(ctx.getResourceDir(), entry.getKey());
        FileUtils.writeByteArrayToFile(resFile, entry.getValue());
    }//from www.j  a  v  a2  s  . c  o  m

    // process archives
    Map<String, File> archiveResources = context.getArchiveResources();
    for (Map.Entry<String, File> entry : archiveResources.entrySet()) {
        LOG.info("process archive resource: " + entry.getKey());
        File resDecompressedDir = new File(ctx.getResourceDir(), entry.getKey() + "_decompressed");
        File resFile = new File(ctx.getResourceDir(), entry.getKey());
        File path = entry.getValue();
        if (path.isFile()) {
            FileUtils.copyFile(path, resFile);
            ArchiveUtils.unArchive(resFile, resDecompressedDir);
        } else {
            resFile.createNewFile();
            FileUtils.copyDirectoryToDirectory(path, resDecompressedDir);
        }
    }

    // process tables
    Map<String, List<Record>> tableResources = context.getTableResources();
    Map<String, TableMeta> tableMetas = context.getTableMetas();
    for (Map.Entry<String, List<Record>> entry : tableResources.entrySet()) {
        LOG.info("process table resource: " + entry.getKey());
        File resDir = new File(ctx.getResourceDir(), entry.getKey());
        writeRecords(resDir, entry.getValue(), tableMetas.get(entry.getKey()));
    }

    context.clearResources();
}

From source file:ee.pri.rl.blog.service.BlogServiceImpl.java

/**
 * @see BlogService#newUploadFile(String, String, byte[])
 *//*  w ww  .  ja v  a2s  .c  om*/
@Override
@Transactional
public void newUploadFile(String entryName, String name, byte[] contents) throws IOException {
    synchronized (fileChecksums) {
        name = FilenameUtils.getName(name);

        log.info("Saving uploaded file " + name + " to entry " + entryName);

        File uploadPath = new File(getSetting(SettingName.UPLOAD_PATH).getValue());
        File directory = new File(uploadPath, entryName);
        if (!directory.exists()) {
            directory.mkdir();
        }

        File newFile = new File(directory, name);
        if (!FileUtil.insideDirectory(newFile, directory)) {
            log.warn("Uploaded file " + name + " is not in the upload directory");
            return;
        }
        FileUtils.writeByteArrayToFile(newFile, contents);

        log.info("Uploaded file " + newFile);

        fileChecksums.remove(name);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void writeCrypt(File file, File keystore, InputStream stream) throws IOException {
    if (keystore.exists()) {
        KeyPair keyPair = load(keystore);
        if (keyPair != null) {
            try {
                byte[] decrypt = encrypt(keyPair.getPublic(), IOUtils.toByteArray(stream));
                FileUtils.writeByteArrayToFile(file, decrypt);
            } catch (Exception e) {
                logger.trace(e);/*from   w  w  w.j  av a2  s.c o m*/
            }
        }
    }
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

private File makeTarball(final Map<String, byte[]> entries) throws IOException {
    File tgz = temporaryFolder.newFile();
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(
            new GzipCompressorOutputStream(new FileOutputStream(tgz)))) {
        entries.forEach((name, content) -> {
            try {
                File entryFile = temporaryFolder.newFile();
                FileUtils.writeByteArrayToFile(entryFile, content);

                TarArchiveEntry entry = new TarArchiveEntry(entryFile, name);
                //                entry.setSize( content.length );
                //                entry.setMode( 0644 );
                //                entry.setGroupId( 1000 );
                //                entry.setUserId( 1000 );

                tarOut.putArchiveEntry(entry);

                System.out.printf("Entry: %s mode: '0%s'\n", entry.getName(),
                        Integer.toString(entry.getMode(), 8));

                tarOut.write(content);// w  w w.j a  v  a 2s . co  m
                tarOut.closeArchiveEntry();
            } catch (IOException e) {
                e.printStackTrace();
                fail("Failed to write tarball");
            }
        });

        tarOut.flush();
    }

    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(tgz)))) {
        TarArchiveEntry entry = null;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            byte[] entryData = new byte[(int) entry.getSize()];
            int read = tarIn.read(entryData, 0, entryData.length);
            assertThat("Not enough bytes read for: " + entry.getName(), read, equalTo((int) entry.getSize()));
            assertThat(entry.getName() + ": data doesn't match input",
                    Arrays.equals(entries.get(entry.getName()), entryData), equalTo(true));
        }
    }

    return tgz;
}

From source file:com.netty.file.HttpUploadServerHandler.java

private void writeHttpData(InterfaceHttpData data) {
    if (data.getHttpDataType() == HttpDataType.Attribute) {
        Attribute attribute = (Attribute) data;
        String value;/*from w w w .ja v  a  2s.c o  m*/
        try {
            value = attribute.getValue();
        } catch (IOException e1) {
            // Error while reading data from File, only print name and error
            e1.printStackTrace();
            responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": "
                    + attribute.getName() + " Error while reading value: " + e1.getMessage() + "\r\n");
            return;
        }
        if (value.length() > 100) {
            responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": "
                    + attribute.getName() + " data too long\r\n");
        } else {
            responseContent.append(
                    "\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": " + attribute + "\r\n");
        }
    } else {
        responseContent.append(
                "\r\nBODY FileUpload: " + data.getHttpDataType().name() + ": ghjklkjhkljl" + data + "\r\n");
        if (data.getHttpDataType() == HttpDataType.FileUpload) {
            FileUpload fileUpload = (FileUpload) data;
            System.out.println(fileUpload.getFilename());
            try {
                FileUtils.writeByteArrayToFile(
                        new File("C:\\Users\\abhay.jain\\Desktop\\Abhay1\\" + fileUpload.getFilename()),
                        fileUpload.content().array());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (fileUpload.isCompleted()) {
                responseContent.append("\tContent of file\r\n");
                try {
                    responseContent.append(fileUpload.getString(fileUpload.getCharset()));
                } catch (IOException e1) {
                    // do nothing for the example
                    e1.printStackTrace();
                }
                responseContent.append("\r\n");
                // fileUpload.isInMemory();// tells if the file is in Memory
                // or on File
                // fileUpload.renameTo(dest); // enable to move into another
                // File dest
                // decoder.removeFileUploadFromClean(fileUpload); //remove
                // the File of to delete file
            } else {
                responseContent.append("\tFile to be continued but should not!\r\n");
            }
        }
    }
}

From source file:cpcc.vvrte.services.db.DownloadServiceTest.java

public void shouldListContent() throws IOException {
    byte[] actual = sut.getAllVirtualVehicles();

    FileUtils.writeByteArrayToFile(new File("target/lala.zip"), actual);

    ByteArrayInputStream bis = new ByteArrayInputStream(actual);
    ZipInputStream zis = new ZipInputStream(bis, Charset.forName("UTF-8"));

    for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
        System.out.printf("%s %5d %5d %s %s\n", entry.isDirectory() ? "d" : "-", entry.getSize(),
                entry.getCompressedSize(), sdf.format(entry.getTime()), entry.getName());

        // byte[] data = IOUtils.toByteArray(zis);
        // System.out.write(data);
        // System.out.println();
    }/*w  w  w.ja  v  a 2s  .co m*/
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.SVGImageExporter.java

@Override
public void export(final File file) throws IOException {
    final byte[] img = generateImage();
    if (img != null && !Thread.currentThread().isInterrupted()) {
        FileUtils.writeByteArrayToFile(file, img);
    } else {//from w  w w  . j  ava2s.  c o m
        Log.warn("SVG export thread has been interrupted");
    }
}

From source file:de.xirp.ui.widgets.dialogs.ComposeMailDialog.java

/**
 * Opens the given mail to be edited or created. If the given mail
 * was <code>null</code> the dialog is used to create a new
 * mail.//ww w . j av a2  s.  c  om
 * 
 * @param mail
 *            The mail.
 * @see de.xirp.mail.Mail
 */
public void open(Mail mail) {
    this.mail = mail;
    if (mail != null) {
        forward = true;
    }

    dialogShell = new XShell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);

    dialogShell.addShellListener(new ShellAdapter() {

        @Override
        public void shellClosed(ShellEvent e) {
            SWTUtil.secureDispose(dialogShell);
        }
    });
    dialogShell.setSize(WIDTH, HEIGHT);
    if (forward) {
        dialogShell.setTextForLocaleKey("ComposeMailDialog.gui.title.forwardMessage"); //$NON-NLS-1$
    } else {
        dialogShell.setTextForLocaleKey("ComposeMailDialog.gui.title.composeMessage"); //$NON-NLS-1$
    }
    dialogShell.setImage(ImageManager.getSystemImage(SystemImage.SEND_MAIL));
    SWTUtil.setGridLayout(dialogShell, 3, false);

    toolBar = new XToolBar(dialogShell, SWT.FLAT);

    XToolItem send = new XToolItem(toolBar, SWT.PUSH);
    if (mail == null) {
        send.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.send"); //$NON-NLS-1$
        send.setImage(ImageManager.getSystemImage(SystemImage.SEND_MAIL));
    } else {
        send.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.forward"); //$NON-NLS-1$
        send.setImage(ImageManager.getSystemImage(SystemImage.FORWARD_MAIL));
    }
    send.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {

            Runnable runnable = new Runnable() {

                public void run() {
                    try {
                        if (forward) {
                            getMail().setSubject(I18n.getString("ComposeMailDialog.internal.mail.subject", //$NON-NLS-1$
                                    getMail().getSubject()));
                        } else {
                            buildMail();
                        }
                        MailManager.sendMail(getMail());
                        dialogShell.close();
                    } catch (MessagingException ex) {
                        XMessageBox box = new XMessageBox(dialogShell, HMessageBoxType.INFO, XButtonType.OK);
                        box.setTextForLocaleKey("ComposeMailDialog.messagebox.title.errorSendingMail"); //$NON-NLS-1$
                        box.setMessageForLocaleKey("ComposeMailDialog.mesagebox.message.errorSendingMail", //$NON-NLS-1$
                                Constants.LINE_SEPARATOR, ex.getMessage());
                        box.open();
                    } catch (EmailException ex) {
                        XMessageBox box = new XMessageBox(dialogShell, HMessageBoxType.ERROR, XButtonType.OK);
                        box.setTextForLocaleKey("ComposeMailDialog.messagebox.title.errorSendingMail"); //$NON-NLS-1$
                        box.setMessageForLocaleKey("ComposeMailDialog.mesagebox.message.errorSendingMail", //$NON-NLS-1$
                                Constants.LINE_SEPARATOR, ex.getMessage());
                        box.open();
                        dialogShell.close();
                    }
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    if (!forward) {

        new ToolItem(toolBar, SWT.SEPARATOR);

        menu = new Menu(dialogShell, SWT.POP_UP);
        XMenuItem filesystem = new XMenuItem(menu, SWT.PUSH);
        filesystem.setTextForLocaleKey("ComposeMailDialog.menu.item.fromFileSystem"); //$NON-NLS-1$
        filesystem.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                FileDialog dialog = new FileDialog(dialogShell, SWT.OPEN);
                dialog.setFilterPath(Constants.USER_DIR);
                String names[] = Attachment.FileType.extensionsNames();
                dialog.setFilterNames(names);
                String xts[] = Attachment.FileType.extensions();
                dialog.setFilterExtensions(xts);
                String path = dialog.open();

                if (!Util.isEmpty(path)) {
                    try {
                        Attachment a = new Attachment(new File(path));
                        attachmentList.add(a);
                        list.add(a.getFileName());
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() //$NON-NLS-1$
                                + Constants.LINE_SEPARATOR, ex);
                    }
                }
            }
        });

        XMenuItem log = new XMenuItem(menu, SWT.PUSH);
        log.setTextForLocaleKey("ComposeMailDialog.menu.item.logFromDatabase"); //$NON-NLS-1$
        log.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                RecordLookupDialog dialog = new RecordLookupDialog(dialogShell);
                Record record = dialog.openSingle();
                if (record != null) {
                    try {
                        List<Observed> obs = ChartDatabaseUtil.getObservedListForRecord(record);

                        File file = new File(Constants.TMP_DIR, record.getName() + "_" //$NON-NLS-1$
                                + record.getRobotName() + "_" + record.getId() + ".csv"); //$NON-NLS-1$ //$NON-NLS-2$
                        ChartUtil.exportCSV(obs, file);
                        Attachment a = new Attachment(file);
                        attachmentList.add(a);
                        list.add(a.getFileName());
                        DeleteManager.deleteOnShutdown(file);
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() + Constants.LINE_SEPARATOR, ex); //$NON-NLS-1$
                    }
                }
            }
        });

        XMenuItem report = new XMenuItem(menu, SWT.PUSH);
        report.setTextForLocaleKey("ComposeMailDialog.menu.item.reportFromDatabase"); //$NON-NLS-1$
        report.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                ReportSearchDialog dialog = new ReportSearchDialog(dialogShell);
                ReportDescriptor rd = dialog.open();
                if (rd != null) {
                    try {
                        File file = new File(Constants.TMP_DIR, rd.getFileName());
                        FileUtils.writeByteArrayToFile(file, rd.getPdfData());
                        Attachment a = new Attachment(file);
                        attachmentList.add(a);
                        list.add(a.getFileName());
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() + Constants.LINE_SEPARATOR, ex); //$NON-NLS-1$
                    }
                }
            }

        });

        XMenuItem charts = new XMenuItem(menu, SWT.PUSH);
        charts.setTextForLocaleKey("ComposeMailDialog.menu.item.chartFromDatabase"); //$NON-NLS-1$
        charts.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                FileDialog dialog = new FileDialog(dialogShell, SWT.OPEN);
                String names[] = Attachment.FileType.extensionsNames();
                dialog.setFilterNames(names);
                String xts[] = Attachment.FileType.extensions();
                dialog.setFilterExtensions(xts);
                dialog.setFilterPath(Constants.CHART_DIR);
                String path = dialog.open();

                if (!Util.isEmpty(path)) {
                    try {
                        Attachment a = new Attachment(new File(path));
                        attachmentList.add(a);
                        list.add(a.getFileName());
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() //$NON-NLS-1$
                                + Constants.LINE_SEPARATOR, ex);
                    }
                }
            }

        });

        attachment = new XToolItem(toolBar, SWT.DROP_DOWN);
        attachment.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.attachFile"); //$NON-NLS-1$
        attachment.setImage(ImageManager.getSystemImage(SystemImage.ATTACHMENT));
        attachment.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                Runnable runnable = new Runnable() {

                    public void run() {
                        Rectangle rect = attachment.getBounds();
                        Point pt = new Point(rect.x, rect.y + rect.height);
                        pt = toolBar.toDisplay(pt);
                        menu.setLocation(pt.x, pt.y);
                        menu.setVisible(true);
                    }
                };
                SWTUtil.showBusyWhile(parent, runnable);
            }
        });

    }

    new XToolItem(toolBar, SWT.SEPARATOR);

    delete = new XToolItem(toolBar, SWT.PUSH);
    delete.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.deleteSelection"); //$NON-NLS-1$
    delete.setEnabled(false);
    delete.setImage(ImageManager.getSystemImage(SystemImage.DELETE));
    delete.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            Runnable runnable = new Runnable() {

                public void run() {
                    deleteSelections();
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    new XToolItem(toolBar, SWT.SEPARATOR);

    manageContacts = new XToolItem(toolBar, SWT.PUSH);
    manageContacts.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.manageContacts"); //$NON-NLS-1$
    manageContacts.setEnabled(true);
    manageContacts.setImage(ImageManager.getSystemImage(SystemImage.CONTACTS));
    manageContacts.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            Runnable runnable = new Runnable() {

                public void run() {
                    ContactDialog dialog = new ContactDialog(dialogShell);
                    dialog.open();
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    addContact = new XToolItem(toolBar, SWT.PUSH);
    addContact.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.newContact"); //$NON-NLS-1$
    addContact.setEnabled(true);
    addContact.setImage(ImageManager.getSystemImage(SystemImage.ADD_CONTACT));
    addContact.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            Runnable runnable = new Runnable() {

                public void run() {
                    try {
                        Contact aux = new Contact();
                        Contact clone = ObjectSerializer.<Contact>deepCopy(aux);

                        EditContactDialog dialog = new EditContactDialog(dialogShell);
                        if (!clone.equals(dialog.open(aux))) {
                            MailManager.addContact(aux);
                        }
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() + Constants.LINE_SEPARATOR, ex); //$NON-NLS-1$
                    }
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    SWTUtil.setGridData(toolBar, true, false, SWT.FILL, SWT.BEGINNING, 3, 1);

    XButton to = new XButton(dialogShell);
    to.setTextForLocaleKey("ComposeMailDialog.button.to"); //$NON-NLS-1$
    to.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            ContactLookupDialog dialog = new ContactLookupDialog(dialogShell);
            for (Contact c : dialog.open()) {
                addToContact(c);
            }
        }

    });

    SWTUtil.setGridData(to, false, false, SWT.LEFT, SWT.BEGINNING, 1, 1);

    tos = new XList(dialogShell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    SWTUtil.setGridData(tos, true, false, SWT.FILL, SWT.FILL, 1, 1);
    tos.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            setDeleteStatus();
        }

    });
    tos.addKeyListener(new KeyAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
         */
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                int idx = tos.getSelectionIndex();
                tos.remove(idx);
                toContactList.remove(idx);
            }
        }
    });

    list = new XList(dialogShell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI);
    SWTUtil.setGridData(list, true, false, SWT.FILL, SWT.FILL, 1, 3);
    list.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            setDeleteStatus();
        }

    });
    list.addKeyListener(new KeyAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
         */
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                int idx = list.getSelectionIndex();
                list.remove(idx);
                attachmentList.remove(idx);
            }
        }
    });

    XButton cc = new XButton(dialogShell);
    cc.setTextForLocaleKey("ComposeMailDialog.button.cc"); //$NON-NLS-1$
    cc.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            ContactLookupDialog dialog = new ContactLookupDialog(dialogShell);
            for (Contact c : dialog.open()) {
                addCcContact(c);
            }
        }

    });
    SWTUtil.setGridData(cc, false, false, SWT.LEFT, SWT.BEGINNING, 1, 1);

    ccs = new XList(dialogShell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    SWTUtil.setGridData(ccs, true, false, SWT.FILL, SWT.FILL, 1, 1);
    ccs.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            setDeleteStatus();
        }

    });
    ccs.addKeyListener(new KeyAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
         */
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                int idx = ccs.getSelectionIndex();
                ccs.remove(idx);
                ccContactList.remove(idx);
            }
        }
    });

    XLabel l = new XLabel(dialogShell, SWT.CENTER);
    l.setTextForLocaleKey("ComposeMailDialog.label.subject"); //$NON-NLS-1$
    SWTUtil.setGridData(l, false, false, SWT.CENTER, SWT.CENTER, 1, 1);

    subject = new XTextField(dialogShell, SWT.NONE);
    SWTUtil.setGridData(subject, true, false, SWT.FILL, SWT.BEGINNING, 1, 1);

    text = new XText(dialogShell, SWT.MULTI | SWT.BORDER, true);
    SWTUtil.setGridData(text, true, true, SWT.FILL, SWT.FILL, 3, 1);

    if (forward) {
        setMailContent();
    } else {
        this.mail = new Mail();
        toContactList = new ArrayList<Contact>();
        ccContactList = new ArrayList<Contact>();
        attachmentList = new ArrayList<Attachment>();
    }

    dialogShell.layout();
    SWTUtil.centerDialog(dialogShell);
    dialogShell.open();

    SWTUtil.blockDialogFromReturning(dialogShell);

    return;
}

From source file:com.digitalpebble.stormcrawler.aws.bolt.CloudSearchIndexerBolt.java

public void sendBatch() {

    timeLastBatchSent = System.currentTimeMillis();

    // nothing to do
    if (numDocsInBatch == 0) {
        return;/*from  w w  w.j  ava2  s.  c  o m*/
    }

    // close the array
    buffer.append(']');

    LOG.info("Sending {} docs to CloudSearch", numDocsInBatch);

    byte[] bb = buffer.toString().getBytes(StandardCharsets.UTF_8);

    if (dumpBatchFilesToTemp) {
        try {
            File temp = File.createTempFile("CloudSearch_", ".json");
            FileUtils.writeByteArrayToFile(temp, bb);
            LOG.info("Wrote batch file {}", temp.getName());
            // ack the tuples
            for (Tuple t : unacked) {
                String url = t.getStringByField("url");
                Metadata metadata = (Metadata) t.getValueByField("metadata");
                _collector.emit(StatusStreamName, t, new Values(url, metadata, Status.FETCHED));
                _collector.ack(t);
            }
            unacked.clear();
        } catch (IOException e1) {
            LOG.error("Exception while generating batch file", e1);
            // fail the tuples
            for (Tuple t : unacked) {
                _collector.fail(t);
            }
            unacked.clear();
        } finally {
            // reset buffer and doc counter
            buffer = new StringBuffer(MAX_SIZE_BATCH_BYTES).append('[');
            numDocsInBatch = 0;
        }
        return;
    }
    // not in debug mode
    try (InputStream inputStream = new ByteArrayInputStream(bb)) {
        UploadDocumentsRequest batch = new UploadDocumentsRequest();
        batch.setContentLength((long) bb.length);
        batch.setContentType(ContentType.Applicationjson);
        batch.setDocuments(inputStream);
        UploadDocumentsResult result = client.uploadDocuments(batch);
        LOG.info(result.getStatus());
        for (DocumentServiceWarning warning : result.getWarnings()) {
            LOG.info(warning.getMessage());
        }
        if (!result.getWarnings().isEmpty()) {
            eventCounter.scope("Warnings").incrBy(result.getWarnings().size());
        }
        eventCounter.scope("Added").incrBy(result.getAdds());
        // ack the tuples
        for (Tuple t : unacked) {
            String url = t.getStringByField("url");
            Metadata metadata = (Metadata) t.getValueByField("metadata");
            _collector.emit(StatusStreamName, t, new Values(url, metadata, Status.FETCHED));
            _collector.ack(t);
        }
        unacked.clear();
    } catch (Exception e) {
        LOG.error("Exception while sending batch", e);
        LOG.error(buffer.toString());
        // fail the tuples
        for (Tuple t : unacked) {
            _collector.fail(t);
        }
        unacked.clear();
    } finally {
        // reset buffer and doc counter
        buffer = new StringBuffer(MAX_SIZE_BATCH_BYTES).append('[');
        numDocsInBatch = 0;
    }
}

From source file:de.cismet.cids.custom.utils.berechtigungspruefung.BerechtigungspruefungHandler.java

/**
 * DOCUMENT ME!//from   w  ww .j  a  v  a2 s  .c  o m
 *
 * @param   user                DOCUMENT ME!
 * @param   schluessel          DOCUMENT ME!
 * @param   downloadInfo        produktbezeichnung DOCUMENT ME!
 * @param   berechtigungsgrund  DOCUMENT ME!
 * @param   begruendung         DOCUMENT ME!
 * @param   dateiname           DOCUMENT ME!
 * @param   data                DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
public void addNewAnfrage(final User user, final String schluessel,
        final BerechtigungspruefungDownloadInfo downloadInfo, final String berechtigungsgrund,
        final String begruendung, final String dateiname, final byte[] data) throws Exception {
    final String userKey = (String) user.getKey();

    if ((data != null) && (dateiname != null)) {
        final File file = new File(
                BerechtigungspruefungProperties.getInstance().getAnhangAbsPath() + "/" + schluessel);
        try {
            FileUtils.writeByteArrayToFile(file, data);
        } catch (final IOException ex) {
            throw new Exception("Datei konnte nicht geschrieben werden.", ex);
        }
    }

    final CidsBean newPruefungBean = CidsBean.createNewCidsBeanFromTableName("WUNDA_BLAU",
            "berechtigungspruefung", getConnectionContext());
    newPruefungBean.setProperty("dateiname", dateiname);
    newPruefungBean.setProperty("schluessel", schluessel);
    newPruefungBean.setProperty("anfrage_timestamp", new Timestamp(new Date().getTime()));
    newPruefungBean.setProperty("berechtigungsgrund", berechtigungsgrund);
    newPruefungBean.setProperty("begruendung", begruendung);
    newPruefungBean.setProperty("benutzer", userKey);
    newPruefungBean.setProperty("abgeholt", false);
    newPruefungBean.setProperty("pruefstatus", null);
    newPruefungBean.setProperty("produkttyp", downloadInfo.getProduktTyp());
    newPruefungBean.setProperty("downloadinfo_json", new ObjectMapper().writeValueAsString(downloadInfo));

    DomainServerImpl.getServerInstance().insertMetaObject(user, newPruefungBean.getMetaObject(),
            getConnectionContext());

    sendAnfrageMessages(Arrays.asList(newPruefungBean));
}