Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

In this page you can find the example usage for java.io Writer flush.

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:com.wavemaker.tools.project.AbstractDeploymentManager.java

/**
 * @param deploymentId/* w  w w.j a va 2s . c  om*/
 * @return
 */
@Override
public void deleteDeploymentInfo(String deploymentId) {
    org.springframework.core.io.Resource deploymentsResource;
    Writer writer = null;
    try {
        Deployments deployments = readDeployments();
        deployments.remove(this.projectManager.getCurrentProject().getProjectName(), deploymentId);
        deploymentsResource = this.fileSystem.getCommonDir().createRelative(DEPLOYMENTS_FILE);
        writer = new OutputStreamWriter(this.fileSystem.getOutputStream(deploymentsResource));
        JSONMarshaller.marshal(writer, deployments, new JSONState(), false, true);
        writer.flush();
    } catch (IOException e) {
        throw new WMRuntimeException("An error occurred while trying to save deployment.", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.wavemaker.tools.project.AbstractDeploymentManager.java

/**
 * @param deploymentInfo/*from www.j av  a 2 s.  co m*/
 * @return
 */
@Override
public String saveDeploymentInfo(DeploymentInfo deploymentInfo) {
    org.springframework.core.io.Resource deploymentsResource;
    Writer writer = null;
    try {
        Deployments deployments = readDeployments();
        deployments.save(this.projectManager.getCurrentProject().getProjectName(), deploymentInfo);

        deploymentsResource = this.fileSystem.getCommonDir().createRelative(DEPLOYMENTS_FILE);
        writer = new OutputStreamWriter(this.fileSystem.getOutputStream(deploymentsResource));
        JSONMarshaller.marshal(writer, deployments, new JSONState(), false, true);
        writer.flush();
    } catch (IOException e) {
        throw new WMRuntimeException("An error occurred while trying to save deployment.", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return deploymentInfo.getDeploymentId();
}

From source file:PropsToXML.java

/**
 * <p> This will output the properties in this object
 *   as XML to the supplied output writer. </p>
 *
 * @param writer the writer to output XML to.
 * @param header comment to add at top of file
 * @throws <code>IOException</code> - when writing errors occur.
 *//*from ww w. j  av a  2  s  .c  o m*/
public void store(Writer writer, String header) throws IOException {

    // Create a new JDOM Document with a root element "properties"
    Element root = new Element("properties");
    Document doc = new Document(root);

    // Add in header information
    Comment comment = new Comment(header);
    doc.getContent().add(0, comment);

    // Get the property names
    Enumeration propertyNames = propertyNames();
    while (propertyNames.hasMoreElements()) {
        String propertyName = (String) propertyNames.nextElement();
        String propertyValue = getProperty(propertyName);
        createXMLRepresentation(root, propertyName, propertyValue);
    }

    // Output document to supplied filename
    XMLOutputter outputter = new XMLOutputter("  ", true);
    outputter.output(doc, writer);
    writer.flush();
}

From source file:com.openkm.util.impexp.RepositoryChecker.java

/**
 * Performs a recursive repository document check
 *///from w  ww.j a  v  a2  s. co  m
private static ImpExpStats checkDocumentsHelper(String token, Node baseNode, boolean versions, Writer out,
        InfoDecorator deco)
        throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException,
        IOException, DatabaseException, javax.jcr.PathNotFoundException, javax.jcr.RepositoryException {
    log.debug("checkDocumentsHelper({}, {}, {}, {}, {})",
            new Object[] { token, baseNode, versions, out, deco });
    ImpExpStats stats = new ImpExpStats();

    for (NodeIterator ni = baseNode.getNodes(); ni.hasNext();) {
        Node child = ni.nextNode();

        if (child.isNodeType(Document.TYPE)) {
            ImpExpStats tmp = readDocument(token, child.getPath(), versions, out, deco);
            stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
            stats.setFolders(stats.getFolders() + tmp.getFolders());
            stats.setSize(stats.getSize() + tmp.getSize());
            stats.setOk(stats.isOk() && tmp.isOk());
        } else if (child.isNodeType(Folder.TYPE)) {
            ImpExpStats tmp = readFolder(token, child, versions, out, deco);
            stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
            stats.setFolders(stats.getFolders() + tmp.getFolders());
            stats.setSize(stats.getSize() + tmp.getSize());
            stats.setOk(stats.isOk() && tmp.isOk());
        } else if (child.isNodeType(Mail.TYPE)) {
            ImpExpStats tmp = readFolder(token, child, versions, out, deco);
            stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
            stats.setFolders(stats.getFolders() + tmp.getFolders());
            stats.setSize(stats.getSize() + tmp.getSize());
            stats.setOk(stats.isOk() && tmp.isOk());
        } else {
            log.error("Unknown node type: {} ({})", child.getPrimaryNodeType().getName(), child.getPath());
            stats.setOk(false);
            out.write(deco.print(child.getPath(), 0,
                    "Unknown node type: " + child.getPrimaryNodeType().getName()));
            out.flush();
        }
    }

    log.debug("checkDocumentsHelper: {}", stats);
    return stats;
}

From source file:com.ikon.util.impexp.RepositoryExporter.java

/**
 * Export mail from openkm repository to filesystem.
 *//*  ww  w  .  j  a v a2 s  .co  m*/
public static ImpExpStats exportMail(String token, String mailPath, String destPath, String metadata,
        Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException,
        IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException {
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Mail mailChild = mm.getProperties(token, mailPath);
    Gson gson = new Gson();
    ImpExpStats stats = new ImpExpStats();
    MimeMessage msg = MailUtils.create(token, mailChild);
    FileOutputStream fos = new FileOutputStream(destPath);
    msg.writeTo(fos);
    IOUtils.closeQuietly(fos);
    FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath());

    // Metadata
    if (metadata.equals("JSON")) {
        MailMetadata mmd = ma.getMetadata(mailChild);
        String json = gson.toJson(mmd);
        fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT);
        IOUtils.write(json, fos);
        IOUtils.closeQuietly(fos);
    } else if (metadata.equals("XML")) {
        fos = new FileOutputStream(destPath + ".xml");

        MailMetadata mmd = ma.getMetadata(mailChild);
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(MailMetadata.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(mmd, fos);
        } catch (JAXBException e) {
            log.error(e.getMessage(), e);
            FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
        }
    }

    if (out != null) {
        out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null));
        out.flush();
    }

    // Stats
    stats.setSize(stats.getSize() + mailChild.getSize());
    stats.setMails(stats.getMails() + 1);

    return stats;
}

From source file:com.github.rvesse.airline.help.html.HtmlCommandUsageGenerator.java

@Override
public <T> void usage(String programName, String[] groupNames, String commandName, CommandMetadata command,
        ParserMetadata<T> parserConfig, OutputStream output) throws IOException {

    if (parserConfig == null) {
        parserConfig = MetadataLoader.loadParser(command.getType());
    }/*from  w  ww.ja v  a  2  s.  c o  m*/

    Writer writer = new OutputStreamWriter(output);

    // Header
    outputHtmlHeader(writer);
    writer.append("<body>\n");

    // Page Header i.e. <h1>
    outputPageHeader(writer, programName, groupNames, command);

    // Name and description of command
    outputDescription(writer, programName, groupNames, command);

    // TODO Output pre help sections

    // Synopsis
    List<OptionMetadata> options = outputSynopsis(writer, programName, groupNames, command);

    // Options
    if (options.size() > 0 || command.getArguments() != null) {
        options = sortOptions(options);
        outputOptions(writer, options, command.getArguments(), parserConfig);
    }

    // TODO Output post help sections

    writer.append("</body>\n");
    writer.append("</html>\n");

    // Flush the output
    writer.flush();
    output.flush();
}

From source file:net.solarnetwork.node.settings.ca.CASettingsService.java

@Override
public SettingsBackup backupSettings() {
    final Date mrd = settingDao.getMostRecentModificationDate();
    final SimpleDateFormat sdf = new SimpleDateFormat(BACKUP_DATE_FORMAT);
    final String lastBackupDateStr = settingDao.getSetting(SETTING_LAST_BACKUP_DATE);
    final Date lastBackupDate;
    try {/*from ww w.j  a v  a  2  s.c o  m*/
        lastBackupDate = (lastBackupDateStr == null ? null : sdf.parse(lastBackupDateStr));
    } catch (ParseException e) {
        throw new RuntimeException("Unable to parse backup last date: " + e.getMessage());
    }
    if (mrd == null || (lastBackupDate != null && lastBackupDate.after(mrd))) {
        log.debug("Settings unchanged since last backup on {}", lastBackupDateStr);
        return null;
    }
    final Date backupDate = new Date();
    final String backupDateKey = sdf.format(backupDate);
    final File dir = new File(backupDestinationPath);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    final File f = new File(dir, BACKUP_FILENAME_PREFIX + backupDateKey + '.' + BACKUP_FILENAME_EXT);
    log.info("Backing up settings to {}", f.getPath());
    Writer writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(f));
        exportSettingsCSV(writer);
        settingDao.storeSetting(new Setting(SETTING_LAST_BACKUP_DATE, null, backupDateKey,
                EnumSet.of(SettingFlag.IgnoreModificationDate)));
    } catch (IOException e) {
        log.error("Unable to create settings backup {}: {}", f.getPath(), e.getMessage());
    } finally {
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            // ignore
        }
    }

    // clean out older backups
    File[] files = dir.listFiles(new RegexFileFilter(BACKUP_FILENAME_PATTERN));
    if (files != null && files.length > backupMaxCount) {
        // sort array 
        Arrays.sort(files, new FilenameReverseComparator());
        for (int i = backupMaxCount; i < files.length; i++) {
            if (!files[i].delete()) {
                log.warn("Unable to delete old settings backup file {}", files[i]);
            }
        }
    }
    return new SettingsBackup(backupDateKey, backupDate);
}

From source file:com.matthewmitchell.peercoin_android_wallet.ui.WalletActivity.java

private void backupWallet(@Nonnull final String password) {

    Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.mkdirs();

    final File file = new File(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR,
            Constants.Files.EXTERNAL_WALLET_BACKUP + "-" + getFileDate());
    final Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(application.getWallet());

    Writer cipherOut = null;

    try {//from  ww w.ja v  a 2  s.  c  o  m
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        walletProto.writeTo(baos);
        baos.close();
        final byte[] plainBytes = baos.toByteArray();

        cipherOut = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
        cipherOut.write(Crypto.encrypt(plainBytes, password.toCharArray()));
        cipherOut.flush();

        final DialogBuilder dialog = new DialogBuilder(this);
        dialog.setMessage(Html.fromHtml(getString(R.string.export_keys_dialog_success, file)));
        dialog.setPositiveButton(WholeStringBuilder.bold(getString(R.string.export_keys_dialog_button_archive)),
                new OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        archiveWalletBackup(file);
                    }
                });
        dialog.setNegativeButton(R.string.button_dismiss, null);
        dialog.show();

        log.info("backed up wallet to: '" + file + "'");
    } catch (final IOException x) {
        final DialogBuilder dialog = DialogBuilder.warn(this, R.string.import_export_keys_dialog_failure_title);
        dialog.setMessage(getString(R.string.export_keys_dialog_failure, x.getMessage()));
        dialog.singleDismissButton(null);
        dialog.show();

        log.error("problem backing up wallet", x);
    } finally {
        try {
            cipherOut.close();
        } catch (final IOException x) {
            // swallow
        }
    }
}

From source file:cz.lbenda.dataman.db.ExportTableData.java

/** Write SQL query as insert sql
 * @param sqlQueryRows rows which will be store as INSERT sql
 * @param writer writer to which is write inserts */
public static void writeSqlQueryRowsToSQL(SQLQueryRows sqlQueryRows, Writer writer) {
    final Map<String, List<ColumnDesc>> columnsByTables = new HashMap<>();
    sqlQueryRows.getMetaData().getColumns().forEach(columnDesc -> {
        String table = String.format("\"%s\".\"%s\"", columnDesc.getSchema().trim(),
                columnDesc.getTable().trim());
        List<ColumnDesc> columns = columnsByTables.get(table);
        if (columns == null) {
            columns = new ArrayList<>();
            columnsByTables.put(table, columns);
        }//  www  .  ja va 2 s.  c  o m
        columns.add(columnDesc);
    });
    final Map<String, String> columnsByTableNames = new HashMap<>();
    columnsByTables.entrySet().forEach(entry -> {
        StringBuilder sb = new StringBuilder();
        entry.getValue().forEach(columnDesc -> {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append('"').append(columnDesc.getName()).append('"');
        });
        columnsByTableNames.put(entry.getKey(), sb.toString());
    });
    sqlQueryRows.getRows().forEach(rowDesc -> columnsByTables.entrySet().forEach(entry -> {
        StringBuilder row = new StringBuilder();
        entry.getValue().forEach(columnDesc -> {
            if (row.length() > 0) {
                row.append(", ");
            }
            row.append(sqlValue(sqlQueryRows.getDialect(), columnDesc, rowDesc));
        });
        try {
            writer.write(String.format("insert into %s (%s) values(%s);\n", entry.getKey(),
                    columnsByTableNames.get(entry.getKey()), row.toString()));
            writer.flush();
        } catch (IOException e) {
            LOG.error("Problem with write SQL insert", e);
            throw new RuntimeException("Problem with write SQL insert", e);
        }
    }));
}

From source file:eu.planets_project.tb.utils.ExperimentUtils.java

/**
 * //ww  w .  java 2s  .co m
 * @param os
 * @param expId
 * @throws IOException 
 */
public static void outputResults(OutputStream os, String expId, DATA_FORMAT format) throws IOException {
    log.info("Writing out experiment " + expId + " as " + format);

    Writer out = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    CSVWriter writer = new CSVWriter(out);

    long id = Long.parseLong(expId);

    ExperimentPersistencyRemote edao = ExperimentPersistencyImpl.getInstance();
    Experiment exp = edao.findExperiment(id);

    // The string array 
    String sa[] = new String[8];
    sa[0] = "Name";
    sa[1] = "Run #";
    sa[2] = "Date";
    sa[3] = "Digital Object #";
    sa[4] = "Digital Object Source";
    sa[5] = "Stage";
    sa[6] = "Property Identifier";
    sa[7] = "Property Value";
    // write the headers out:
    writer.writeNext(sa);

    // Loop through:
    int bi = 1;
    for (BatchExecutionRecordImpl batch : exp.getExperimentExecutable().getBatchExecutionRecords()) {
        // log.info("Found batch... "+batch);
        int doi = 1;
        for (ExecutionRecordImpl exr : batch.getRuns()) {
            // log.info("Found Record... "+exr+" stages: "+exr.getStages());
            if (exr != null && exr.getStages() != null) {
                for (ExecutionStageRecordImpl exsr : exr.getStages()) {
                    // log.info("Found Stage... "+exsr);
                    for (MeasurementImpl m : exsr.getMeasurements()) {
                        // log.info("Looking at result for property "+m.getIdentifier());
                        sa[0] = exp.getExperimentSetup().getBasicProperties().getExperimentName();
                        sa[1] = "" + bi;
                        sa[2] = batch.getStartDate().getTime().toString();
                        sa[3] = "" + doi;
                        sa[4] = exr.getDigitalObjectSource();
                        sa[5] = exsr.getStage();
                        sa[6] = m.getIdentifier();
                        sa[7] = m.getValue();
                        // Write out CSV:
                        writer.writeNext(sa);
                    }
                }
            }
            // Increment, for the next DO.
            doi++;
            out.flush();
        }
        // Increment to the next batch:
        bi++;
    }

}