Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .touchosc file
 * /*w w  w.  j  av  a 2s.  co m*/
 * @param zipTouchoscFilePath a .touchosc file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML2(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        URL url = TouchOSCUtils.class.getClassLoader().getResource(".");

        FileInputStream touchoscFile = new FileInputStream(url.getPath() + "../samples/" + zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            }
            FileOutputStream os = new FileOutputStream(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:com.photon.phresco.framework.actions.applications.Build.java

public String stopServer() {
    if (debugEnabled)
        S_LOGGER.debug("Entering Method Build.javaStopServer()");
    try {//from www.  j av  a 2s  .com
        StringBuilder builder = new StringBuilder(Utility.getProjectHome());
        builder.append(projectCode);
        builder.append(File.separator);
        builder.append(FOLDER_DOT_PHRESCO);
        builder.append(File.separator);
        builder.append(RUN_AGS_ENV_FILE);
        File envFile = new File(builder.toString());
        ProjectRuntimeManager runtimeManager = PhrescoFrameworkFactory.getProjectRuntimeManager();
        ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator();
        Project project = administrator.getProject(projectCode);
        String projectCode = project.getProjectInfo().getCode();
        environments = (String) getHttpSession()
                .getAttribute(project.getProjectInfo().getCode() + SESSION_ENV_NAME);
        Map<String, String> javaMap = new HashMap<String, String>(2);
        javaMap.put(ENVIRONMENT_NAME, environments);
        ActionType serverStop = ActionType.STOP_SERVER;
        BufferedReader reader = runtimeManager.performAction(project, serverStop, javaMap, null);
        String line;
        line = reader.readLine();
        while (!line.startsWith("[INFO] BUILD SUCCESS")) {
            line = reader.readLine();
        }

        File dir = new File(javaLogFileDir());

        File javaReadLogFile = null;
        if (dir.isDirectory() && dir.list().length != 0) {
            for (File child : dir.listFiles()) {
                if (child.getName().startsWith(CATALINA_FILE_START_NAME)) {
                    javaReadLogFile = child;
                }
            }
        } else {
            javaReadLogFile = null;
        }
        if (javaReadLogFile != null && javaReadLogFile.exists()) {
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(javaReadLogFile));
                bw.write("");
                bw.flush();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (envFile.exists()) {
            envFile.delete();
        }
        getHttpSession().removeAttribute(project.getProjectInfo().getCode() + SESSION_JAVA_SERVER_STATUS);
        getHttpSession().removeAttribute(project.getProjectInfo().getCode() + IMPORT_SQL);
        getHttpSession().setAttribute(projectCode + REQ_JAVA_STOP,
                new BufferedReader(new StringReader("Server stopped successfully")));
        getHttpRequest().setAttribute(REQ_PROJECT_CODE, projectCode);
        getHttpRequest().setAttribute(REQ_TEST_TYPE, REQ_JAVA_STOP);
        getHttpRequest().setAttribute(REQ_PROJECT_CODE, projectCode);
    } catch (Exception e) {
        if (debugEnabled) {
            S_LOGGER.error("Entered into catch block of Build.javaStopServer()"
                    + FrameworkUtil.getStackTraceAsString(e));
        }
        new LogErrorReport(e, "Java stop server");
    }
    return APP_ENVIRONMENT_READER;
}

From source file:com.alta189.cyborg.api.util.config.ini.IniConfiguration.java

protected void saveFromNodes(Map<String, ConfigurationNode> nodes) throws ConfigurationException {
    Writer rawWriter = null;//from  w  w w .  j av  a 2  s . c o m
    BufferedWriter writer = null;
    try {
        rawWriter = getWriter();
        writer = new BufferedWriter(rawWriter);

        List<ConfigurationNode> childlessNodes = new ArrayList<ConfigurationNode>(),
                sectionNodes = new ArrayList<ConfigurationNode>();
        for (ConfigurationNode node : nodes.values()) {
            if (node.hasChildren()) {
                sectionNodes.add(node);
            } else {
                childlessNodes.add(node);
            }
        }

        if (childlessNodes.size() > 0) {
            writeNodeSection(writer, childlessNodes);
        }

        for (Iterator<ConfigurationNode> i = sectionNodes.iterator(); i.hasNext();) {
            ConfigurationNode node = i.next();
            String[] comment = getComment(node);
            if (comment != null) {
                for (String line : comment) {
                    writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR);
                }
            }
            writer.append('[').append(node.getPathElements()[0]).append(']').append(LINE_SEPARATOR);
            writeNodeSection(writer, node.getChildren().values());
            if (i.hasNext()) {
                writer.append(LINE_SEPARATOR);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationException(e);
    } finally {
        if (writer != null) {
            try {
                writer.flush();
            } catch (IOException ignore) {
            }
        }
        if (rawWriter != null) {
            try {
                rawWriter.flush();
                rawWriter.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:net.jeremybrooks.readsy.bo.ReadsyDataFile.java

/**
 * Write the file.//from w ww .  j  a  v a 2s.  c o m
 * The current contents of this object will be written to the file specified
 * when the object was created.  If the file already exists, it will be
 * replaced.
 *
 * @throws IOException if any errors occur.
 */
public void write() throws IOException {
    // force version 1, which is the version this method writes
    this.root.setVersion(1);

    File f = this.root.getFile();
    BufferedWriter out = null;
    logger.debug("File is " + f.getAbsolutePath());
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));

        // THE FIRST PART OF THE FILE
        out.write(XML_ELEMENT);
        out.write('\n');
        out.write("<document description=\"");
        out.write(this.root.getDescription());
        out.write("\" shortDescription=\"");
        out.write(this.root.getShortDescription());
        out.write("\" year=\"");
        out.write((new Integer(this.root.getYear())).toString());
        out.write("\" version=\"");
        out.write((new Integer(this.root.getVersion())).toString());
        out.write("\">");
        out.write('\n');
        logger.debug("Ready to write " + this.entryList.size() + " records.");
        for (ReadsyEntryElement entry : this.entryList) {
            out.write("<entry date=\"");
            out.write(entry.getDate());
            out.write("\">");
            out.write('\n');
            out.write("<heading>");
            out.write(StringEscapeUtils.escapeXml(entry.getHeading()));
            out.write("</heading>");
            out.write('\n');
            out.write("<text>");
            out.write(StringEscapeUtils.escapeXml(entry.getText()));
            out.write("</text>");
            out.write('\n');
            out.write("</entry>");
            out.write('\n');
        }

        logger.debug("Wrote entry list successfully.");

        out.write("</document>");
        out.write('\n');

        out.flush();

    } catch (Exception e) {
        logger.error("ERROR WRITING FILE " + f.getAbsolutePath(), e);
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        throw new IOException("Error writing file " + f.getAbsolutePath() + sw.toString());

    } finally {
        IOUtil.close(out);
    }
}

From source file:com.flowpowered.cerealization.config.ini.IniConfiguration.java

@Override
protected void saveFromNodes(Map<String, ConfigurationNode> nodes) throws ConfigurationException {
    Writer rawWriter = null;//  www.j av  a  2  s  . c o m
    BufferedWriter writer = null;
    try {
        rawWriter = getWriter();
        writer = new BufferedWriter(rawWriter);

        List<ConfigurationNode> childlessNodes = new ArrayList<ConfigurationNode>(),
                sectionNodes = new ArrayList<ConfigurationNode>();
        for (ConfigurationNode node : nodes.values()) {
            if (node.hasChildren()) {
                sectionNodes.add(node);
            } else {
                childlessNodes.add(node);
            }
        }

        if (childlessNodes.size() > 0) {
            writeNodeSection(writer, childlessNodes);
        }

        for (Iterator<ConfigurationNode> i = sectionNodes.iterator(); i.hasNext();) {
            ConfigurationNode node = i.next();
            String[] comment = getComment(node);
            if (comment != null) {
                for (String line : comment) {
                    writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR);
                }
            }
            writer.append('[').append(node.getPathElements()[0]).append(']').append(LINE_SEPARATOR);
            writeNodeSection(writer, node.getChildren().values());
            if (i.hasNext()) {
                writer.append(LINE_SEPARATOR);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationException(e);
    } finally {
        if (writer != null) {
            try {
                writer.flush();
            } catch (IOException ignore) {
            }
        }
        if (rawWriter != null) {
            try {
                rawWriter.flush();
                rawWriter.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:com.uwyn.jhighlight.renderer.XhtmlRenderer.java

/**
 * Transforms source code that's provided through an
 * <code>InputStream</code> to highlighted syntax in XHTML and writes it
 * back to an <code>OutputStream</code>.
 * <p>If the highlighting has to become a fragment, no CSS styles will be
 * generated.//from   w  w  w.j  a  v  a  2s .  co m
 * <p>For complete documents, there's a collection of default styles that
 * will be included. It's possible to override these by changing the
 * provided <code>jhighlight.properties</code> file. It's best to look at
 * this file in the JHighlight archive and modify the styles that are
 * there already.
 *
 * @param name     The name of the source file.
 * @param in       The input stream that provides the source code that needs to
 *                 be transformed.
 * @param out      The output stream to which to resulting XHTML should be
 *                 written.
 * @param encoding The encoding that will be used to read and write the
 *                 text.
 * @param fragment <code>true</code> if the generated XHTML should be a
 *                 fragment; or <code>false</code> if it should be a complete page
 * @see #highlight(String, String, String, boolean)
 * @since 1.0
 */
@Override
public void highlight(String name, InputStream in, OutputStream out, String encoding, boolean fragment)
        throws IOException {
    ExplicitStateHighlighter highlighter = getHighlighter();

    Reader isr;
    Writer osw;
    if (null == encoding) {
        isr = new InputStreamReader(in);
        osw = new OutputStreamWriter(out);
    } else {
        isr = new InputStreamReader(in, encoding);
        osw = new OutputStreamWriter(out, encoding);
    }

    BufferedReader r = new BufferedReader(isr);
    BufferedWriter w = new BufferedWriter(osw);

    if (fragment) {
        w.write(getXhtmlHeaderFragment(name));
    } else {
        w.write(getXhtmlHeader(name));
    }

    String line;
    String token;
    int length;
    int style;
    String css_class;
    int previous_style = -1;
    boolean newline = false;
    while ((line = r.readLine()) != null) {
        line += "\n";
        line = StringUtils.convertTabsToSpaces(line, 4);

        // should be optimized by reusing a custom LineReader class
        Reader lineReader = new StringReader(line);
        highlighter.setReader(lineReader);
        int index = 0;
        while (index < line.length()) {
            style = highlighter.getNextToken();
            length = highlighter.getTokenLength();
            token = line.substring(index, index + length);

            if (style != previous_style || newline) {
                css_class = getCssClass(style);

                if (css_class != null) {
                    if (previous_style != -1 && !newline) {
                        w.write("</span>");
                    }
                    w.write("<span class=\"" + css_class + "\">");

                    previous_style = style;
                }
            }
            newline = false;
            w.write(StringEscapeUtils.escapeHtml4(token.replace("\n", "")).replace(" ", "&nbsp;"));

            index += length;
        }

        w.write("</span><br />\n");
        newline = true;
    }

    if (!fragment)
        w.write(getXhtmlFooter());

    w.flush();
    w.close();
}

From source file:org.balloon_project.overflight.task.indexing.IndexingTask.java

private File getOrCreateDumpFile() throws IOException {
    // create file if it not already exists
    File dir = new File(configuration.getTripleDumpStoreDirectory());
    dir.mkdirs();//from   w  ww.j a  va2  s.  c  o m
    File dumpFile = new File(dir, filename);
    boolean newFile = dumpFile.createNewFile();

    // adding header to new file
    if (newFile) {
        BufferedWriter writer = new BufferedWriter(new FileWriter(dumpFile));
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            writer.append(
                    "# ---------------------------------------------------------------------------------------------------------------------------\n");
            writer.append(
                    "# Triples indexed by Balloon Overflight (https://www.dimis.fim.uni-passau.de/balloon/)\n");
            writer.append("# " + KEY_ENDPOINT + ": ").append(endpoint.getEndpointID()).append("\n");
            writer.append("# URL: ").append(endpoint.getUrl()).append("\n");
            writer.append("# SPARQL: ").append(endpoint.getSparqlEndpoint()).append("\n");
            writer.append("# Information: http://datahub.io/dataset/").append(endpoint.getEndpointID())
                    .append("\n");
            writer.append("# " + KEY_PREDICATE + ": ").append(relEntity.getPredicate()).append("\n");
            writer.append("# PredicateIdentifier: ").append(relEntity.getShortname()).append("\n");
            writer.append("# PredicateType: ").append(relEntity.getType().toString()).append("\n");
            writer.append("# " + KEY_DATE + ": ").append(dateFormat.format(new Date())).append("\n");
            writer.append(
                    "# ---------------------------------------------------------------------------------------------------------------------------\n");
            writer.append(BEGIN_DATA);
            writer.append("\n");
        } finally {
            writer.flush();
            writer.close();
        }
    }

    return dumpFile;
}

From source file:adams.data.io.output.AbstractSpreadSheetWriter.java

/**
 * Writes the spreadsheet in CSV format to the given file.
 * Handles compression automatically, if the filename ends with ".gz",
 * {@link #supportsCompressedOutput()} returns true and file is not
 * being appended.//from w  w w .  j  a v  a  2  s  .  c o m
 *
 * @param content   the spreadsheet to write
 * @param filename   the file to write the spreadsheet to
 * @return      true if successfully written
 * @see      #supportsCompressedOutput()
 * @see      AppendableSpreadSheetWriter
 */
@Override
public boolean write(SpreadSheet content, String filename) {
    boolean result;
    BufferedWriter writer;
    OutputStream output;
    boolean append;
    AppendableSpreadSheetWriter appendable;

    result = true;

    preWriteFile(filename);

    append = false;
    if (this instanceof AppendableSpreadSheetWriter) {
        appendable = (AppendableSpreadSheetWriter) this;
        append = appendable.isAppending();
        if (append) {
            appendable.setFileExists(new File(filename).exists());
            append = appendable.canAppend(content);
        }
    }

    writer = null;
    output = null;
    try {
        switch (getOutputType()) {
        case FILE:
            result = doWrite(content, filename);
            break;
        case STREAM:
            output = new FileOutputStream(filename, append);
            if (!append && canCompress(filename))
                output = new GZIPOutputStream(output);
            result = doWrite(content, output);
            output.flush();
            break;
        case WRITER:
            output = new FileOutputStream(filename, append);
            if (!append && canCompress(filename))
                output = new GZIPOutputStream(output);
            if (m_Encoding != null)
                writer = new BufferedWriter(new OutputStreamWriter(output, m_Encoding.charsetValue()));
            else
                writer = new BufferedWriter(new OutputStreamWriter(output));
            result = doWrite(content, writer);
            writer.flush();
            break;
        default:
            throw new IllegalStateException("Unhandled output type: " + getOutputType());
        }
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
    } finally {
        FileUtils.closeQuietly(writer);
        FileUtils.closeQuietly(output);
    }

    return result;
}

From source file:com.mgmtp.jfunk.common.util.ExtendedProperties.java

/**
 * Writes the properties to the specified writer, including defaults.
 * //from  w  ww. j  a  v a  2  s . c  om
 * @param writer
 *            The writer
 * @param comments
 *            The header comment written to the writer
 * @param sorted
 *            If {@code true}, the properties are written sorted by key
 * @param process
 *            If {@code true}, place holders are resolved
 */
public void store(final Writer writer, final String comments, final boolean sorted, final boolean process)
        throws IOException {
    BufferedWriter bw = writer instanceof BufferedWriter ? (BufferedWriter) writer : new BufferedWriter(writer);

    if (comments != null) {
        for (Scanner scanner = new Scanner(comments); scanner.hasNextLine();) {
            bw.write("#");
            bw.write(scanner.nextLine());
            bw.newLine();
        }
    }

    bw.write("#" + new Date());
    bw.newLine();
    Set<String> keys = keySet();
    if (sorted) {
        keys = Sets.newTreeSet(keys);
    }

    for (String key : keys) {
        /*
         * No need to escape embedded and trailing spaces for value, hence pass false to flag.
         */
        bw.write(saveConvert(key, true) + "=" + saveConvert(get(key, process), false));
        bw.newLine();
    }
    bw.flush();
}

From source file:de.csw.expertfinder.mediawiki.api.MediaWikiAPI.java

/**
 * Reads the redirect data gathered with {@link #getAllRedirects()} and retrieves all missing data
 * necessary to restore the redirects in the local MediaWiki db. In particular, it retrieves the
 * titles of the redirect (pseudo) pages, because {@link #getAllRedirects()} only gives us page ids
 * which do not correspsond to the page ids in our local db.
 * @throws Exception //www  .j a  v a  2  s  .c  o  m
 */
private void repairRedirects() throws Exception {
    List<String> lines = FileUtils.readLines(new File("D:\\Evaluierung\\AllRedirects.txt"));
    BufferedWriter out = new BufferedWriter(
            new FileWriter("D:\\Evaluierung\\AllRedirectsWithPageNames.txt", true));

    for (String line : lines) {
        StringTokenizer tok = new StringTokenizer(line, ";");
        Integer pageId = Integer.parseInt(tok.nextToken());
        String ns = tok.nextToken();
        String pageTitle = tok.nextToken();

        Document doc = queryMediaWiki("query",
                new BasicNameValuePair[] { new BasicNameValuePair("prop", "info"),
                        new BasicNameValuePair("titles", pageTitle), new BasicNameValuePair("redirects", "") });

        Element redirectElement = (Element) doc.getElementsByTagName("r").item(0);
        if (redirectElement == null)
            continue;

        String targetPageTitle = redirectElement.getAttribute("to");

        out.write(pageTitle);
        out.write(";");
        out.write(ns);
        out.write(";");
        out.write(targetPageTitle);
        out.write("\n");

    }
    out.flush();
    out.close();
}