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.eyeq.pivot4j.ui.AbstractHtmlTableTestCase.java

/**
 * @see com.eyeq.pivot4j.AbstractIntegrationTestCase#setUp()
 *///from www  .java 2  s . c  o  m
@Override
public void setUp() throws Exception {
    super.setUp();

    PivotModel model = getPivotModel();
    model.setMdx(readTestResource(getQueryName() + ".txt"));
    model.initialize();

    Writer writer = null;

    File file = File.createTempFile("pivot4j-", ".html");

    if (deleteTestFile) {
        file.deleteOnExit();
    }

    try {
        writer = new FileWriter(file);

        HtmlRenderer renderer = new HtmlRenderer(writer);
        renderer.setTableId("pivot");
        renderer.setBorder(1);

        configureRenderer(renderer);

        renderer.render(model);
    } finally {
        writer.flush();
        IOUtils.closeQuietly(writer);
    }

    WebClient webClient = new WebClient();
    HtmlPage page = webClient.getPage(file.toURI().toURL());

    this.table = page.getHtmlElementById("pivot");

    assertThat("Table element is not found.", table, is(notNullValue()));
}

From source file:org.eclipse.virgo.ide.runtime.internal.core.ServerPublishOperation.java

/**
 * Creates a dummy manifest for WTP Dynamic Web Projects only
 *///  www. ja  v a  2  s  .co m
private void publishManifest(IModule module, IPath path) {

    if (FacetUtils.hasProjectFacet(module.getProject(), FacetCorePlugin.WEB_FACET_ID)) {
        File manifestFile = path.append(BundleManifestCorePlugin.MANIFEST_FOLDER_NAME)
                .append(BundleManifestCorePlugin.MANIFEST_FILE_NAME).toFile();
        if (manifestFile.exists()) {
            return;
        }
        BundleManifest manifest = BundleManifestFactory.createBundleManifest();
        Writer writer = null;
        try {
            manifestFile.getParentFile().mkdirs();
            writer = new FileWriter(manifestFile);
            manifest.write(writer);
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.comcast.cns.util.Util.java

/**
 * Generate the Json message to send to all the endpoints except email
 * @param arn The topic arn for the topic the user is subscribing to.
 * @param message the message to send//  w  w  w.java2 s  .c om
 * @param subject the subject to send, also included as the subject in email-json
 * @return the Json String 
 */
public static String generateMessageJson(CNSMessage cnsMessage, CnsSubscriptionProtocol prot) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new PrintWriter(out);
    JSONWriter jw = new JSONWriter(writer);
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); //Time is in UTC zone. i,e no offset
    String timestamp = df.format(cnsMessage.getTimestamp());

    try {
        String message = cnsMessage.getProtocolSpecificMessage(prot);
        jw = jw.object();
        jw.key("Message").value(message);
        jw.key("MessageId").value(cnsMessage.getMessageId());
        jw.key("Signature").value("");
        jw.key("SignatureVersion").value("1");
        jw.key("SigningCertURL").value("");
        jw.key("Subject").value(cnsMessage.getSubject());
        jw.key("Timestamp").value(timestamp);
        jw.key("TopicArn").value(cnsMessage.getTopicArn());
        jw.key("Type").value(cnsMessage.getMessageType().toString());
        String unsubscribeUrl = CMBProperties.getInstance().getCmbUnsubscribeUrl();
        if (unsubscribeUrl.contains("%a")) {
            unsubscribeUrl = unsubscribeUrl.replace("%a", cnsMessage.getSubscriptionArn());
        } else {
            unsubscribeUrl += "?Action=Unsubscribe&SubscriptionArn=" + cnsMessage.getSubscriptionArn();
        }
        jw.key("UnSubscribeURL").value(unsubscribeUrl);
        jw.endObject();
        writer.flush();
    } catch (Exception e) {
        return "";
    }

    return out.toString();
}

From source file:com.norconex.importer.ImporterConfig.java

private void writeResponseProcessors(Writer out, String listTagName, IImporterResponseProcessor[] processors)
        throws IOException {
    if (ArrayUtils.isEmpty(processors)) {
        return;/*from  w ww . j  a va2s  .  c o  m*/
    }
    out.write("<" + listTagName + ">");
    for (IImporterResponseProcessor processor : processors) {
        writeObject(out, null, processor);
    }
    out.write("</" + listTagName + ">");
    out.flush();
}

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * Obtains the tags list for each profile.
 * @param req/*  www.j av a2 s . c o  m*/
 * @param resp
 * @throws java.io.IOException
 */
public void profileTagList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String profile = req.getParameter("profileselected");
    File tagsFile = new File(Config.PROFILES_DIR + profile + "/tags");
    String tagsForProfile = "";
    if (tagsFile.exists() && tagsFile.length() > 0) {
        tagsForProfile = FileHelper.readContentFromFile(tagsFile).trim();
    }
    Writer w = resp.getWriter();
    w.write(tagsForProfile);
    w.flush();
    w.close();
}

From source file:org.psidnell.omnifocus.Main.java

private void run() throws Exception {
    Writer out;
    if (outputFile != null) {
        out = new BufferedWriter(new FileWriter(outputFile));
    } else {/*from   w w  w. j  av a  2 s.  c  o m*/
        out = new BufferedWriter(IOUtils.systemOutWriter());
    }

    if (format != null) {
        ofexport.setFormat(format.toLowerCase());
    } else if (outputFile != null && outputFile.contains(".")) {
        int dot = outputFile.indexOf('.');
        ofexport.setFormat(outputFile.substring(dot + 1).toLowerCase());
    }

    ofexport.process();
    ofexport.write(out);

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

    if (open) {
        String[] cmdargs = { "open", outputFile };
        Process p = Runtime.getRuntime().exec(cmdargs);
        try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            org.apache.commons.io.IOUtils.copy(input, System.out);
        }
    }
}

From source file:com.morty.podcast.writer.PodCastGenerator.java

private void generateCompleteFeed(List podcastFiles) throws Exception {

    try {//  w  w w  .  ja  v a2  s.c  om

        //Get the default info file from the podcast directory, and see if there are any overrides
        File defaultInfo = new File(m_directoryToTraverse + File.separator + PodCastConstants.INFO_FILE);
        HashMap defaultFeedValues = new HashMap();
        if (defaultInfo.exists())
            defaultFeedValues = PodCastUtils.parseInfoFile(defaultInfo);

        final SyndFeed feed = new SyndFeedImpl();
        feed.setFeedType(PodCastConstants.FEED_TYPE);

        feed.setTitle(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_TITLE_KEY,
                PodCastConstants.DEFAULT_FEED_TITLE));
        if (m_feedLink == null)
            feed.setLink(PodCastUtils.generateHttpLink(m_httpRoot, m_fileToCreate, m_urlSuffix));
        else
            feed.setLink(m_feedLink);
        feed.setDescription(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_DESCRIPTION_KEY,
                PodCastConstants.DEFAULT_FEED_DESCRIPTION));
        feed.setCopyright(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_COPYRIGHT_KEY,
                PodCastConstants.DEFAULT_FEED_COPYRIGHT));

        //Set the image on the Feed.
        SyndImage img = new SyndImageImpl();
        img.setDescription(feed.getDescription());
        img.setLink(feed.getLink());
        img.setTitle(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_IMAGE_TITLE,
                PodCastConstants.DEFAULT_IMAGE_TITLE));
        img.setUrl(PodCastUtils.generateHttpLink(m_httpRoot, PodCastUtils.getMapValue(defaultFeedValues,
                PodCastConstants.FEED_IMAGE_NAME, PodCastConstants.DEFAULT_IMAGE_NAME), m_urlSuffix));
        feed.setImage(img);

        //Set image on all episodes.
        FeedInformation episodeFeed = new FeedInformationImpl();
        episodeFeed.setImage(new URL(img.getUrl()));

        Iterator it = podcastFiles.iterator();
        while (it.hasNext()) {
            SyndEntry podcastEntry = (SyndEntry) it.next();
            podcastEntry.getModules().add(episodeFeed);
        }

        //Generate the itunes image!
        FeedInformation itunesFeed = new FeedInformationImpl();
        itunesFeed.setImage(new URL(img.getUrl()));
        itunesFeed.setSummary(feed.getDescription());
        feed.getModules().add(itunesFeed);

        feed.setEntries(podcastFiles);

        final Writer fileWriter = new FileWriter(m_fileToCreate);
        final SyndFeedOutput feedOutput = new SyndFeedOutput();
        feedOutput.output(feed, fileWriter);
        fileWriter.flush();
        fileWriter.close();

        m_logger.info("Podcast created [" + m_fileToCreate + "]");

    } catch (Exception ex) {
        m_logger.error("ERROR: " + ex.getMessage());
        throw ex;
    }

}

From source file:com.kolich.havalo.io.stores.MetaObjectStore.java

@Override
public void save(final StoreableEntity entity) {
    FileOutputStream fos = null;/*from w ww.java2  s.c o m*/
    GZIPOutputStream gos = null;
    Writer writer = null;
    try {
        fos = new FileOutputStream(getCanonicalFile(entity));
        gos = new GZIPOutputStream(fos) {
            // Ugly anonymous constructor hack to set the compression
            // level on the underlying Deflater to "max compression".
            {
                def.setLevel(BEST_COMPRESSION);
            }
        };
        writer = new OutputStreamWriter(gos, UTF_8);
        // Call the entity to write itself to the output stream.
        entity.toWriter(writer);
        writer.flush(); // Muy importante
        gos.finish(); // Muy importante mucho!
    } catch (Exception e) {
        throw new ObjectFlushException("Failed to save entity: " + entity.getKey(), e);
    } finally {
        closeQuietly(writer);
        closeQuietly(gos);
        closeQuietly(fos);
    }
}

From source file:com.workfront.api.StreamClient.java

private Object request(String path, Map<String, Object> params, Set<String> fields, String method,
        int retryCount, File file) throws StreamClientException {
    HttpURLConnection conn = null;
    int responseCode = -1;

    try {// w w w.  jav  a 2  s  .c  o m
        String authenticationParam = "";
        if (apiKey != null) {
            authenticationParam += "apiKey=" + apiKey;
        } else if (sessionID != null) {
            authenticationParam += "sessionID=" + sessionID;
        }
        String methodParam = "method=" + method;
        String query = authenticationParam + "&" + methodParam;

        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof String[]) {
                    String[] paramVal = (String[]) params.get(key);
                    for (int i = 0; i < paramVal.length; i++) {
                        String val = paramVal[i];
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(val, "UTF-8");
                    }
                } else {
                    query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                            + URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8");
                }
            }
        }

        if (fields != null) {
            query += "&fields=";
            for (String field : fields) {
                query += URLEncoder.encode(field, "UTF-8") + ",";
            }
            query = query.substring(0, query.lastIndexOf(","));
        }

        conn = createConnection(hostname + path, method);

        String boundary = Long.toHexString(System.currentTimeMillis());

        if (file != null) {
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("User-Agent", "Workfront Java StreamClient");
        }

        // Send request
        OutputStream outputStream = conn.getOutputStream();
        Writer out = new OutputStreamWriter(outputStream);
        if (file != null) {
            addFileToRequest(boundary, out, outputStream, file);
        } else {
            out.write(query);
        }

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

        // Get response code
        responseCode = conn.getResponseCode();

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();

        // Decode JSON
        JSONObject result = new JSONObject(response.toString());

        // Verify result
        if (result.has("error")) {
            throw new StreamClientException(result.getJSONObject("error").getString("message"));
        } else if (!result.has("data")) {
            throw new StreamClientException("Invalid response from server");
        }

        // Manage the session
        if (path.equals(PATH_LOGIN)) {
            sessionID = result.getJSONObject("data").getString("sessionID");
        } else if (path.equals(PATH_LOGOUT)) {
            sessionID = null;
        }

        return result.get("data");
    } catch (ConnectException connectException) {
        throw new StreamClientException("Unable to connect to " + hostname + path);
    } catch (IOException e) {
        //getErrorStream() can return null if no error data was sent back
        if (conn.getErrorStream() != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            try {
                copyStream(conn.getErrorStream(), out);
            } catch (IOException e1) {
                // Removed printStackTrace call
            }

            throw new StreamClientException(new String(out.toByteArray()));
        } else {
            //I believe this use case happens when the we are sending to many requests at one time...
            if (retryCount < 3) {
                return request(path, params, fields, method, ++retryCount);
            } else {
                throw new StreamClientException(
                        "An error happened but no error data was sent... 3 time... Response Code = "
                                + responseCode);
            }
        }
    } catch (Exception e) {
        throw new StreamClientException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}