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.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;

    try {/*from w  w w.  j  av  a2s.c  om*/
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.java

/**
 *
 *///w  w  w  .  j av  a2 s . c om
public static void writeFontExtensionsProperties(String fontRegistryFactoryPropertyName,
        String fontRegistryFactoryPropertyValue, String fontFamiliesPropertyName,
        String fontFamiliesPropertyValue, OutputStream outputStream) throws JRException {
    Writer out = null;
    try {
        out = new OutputStreamWriter(outputStream, DEFAULT_ENCODING);
        out.write(fontRegistryFactoryPropertyName + "=" + fontRegistryFactoryPropertyValue + "\n");
        out.write(fontFamiliesPropertyName + "=" + fontFamiliesPropertyValue + "\n");
        out.flush();
    } catch (Exception e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_OUTPUT_STREAM_WRITER_ERROR, null, e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform PUT request against an RTC server
 * @param serverURI The RTC server//from   w w w.j ava2 s  .co  m
 * @param uri The relative URI for the PUT. It is expected that it is already encoded if necessary.
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param json The JSON object to put to the RTC server
 * @param httpContext The context from the login if cycle is being managed by the caller
 * Otherwise <code>null</code> and this call will handle the login.
 * @param listener The listener to report errors to.
 * May be <code>null</code> if there is no listener.
 * @return The HttpContext for the request. May be reused in subsequent requests
 * for the same user
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException
 * @throws GeneralSecurityException 
 */
public static HttpClientContext performPut(String serverURI, String uri, String userId, String password,
        int timeout, final JSONObject json, HttpClientContext httpContext, TaskListener listener)
        throws IOException, InvalidCredentialsException, GeneralSecurityException {

    CloseableHttpClient httpClient = getClient();
    // How to fill the request body (Clone doesn't work)
    ContentProducer cp = new ContentProducer() {
        public void writeTo(OutputStream outstream) throws IOException {
            Writer writer = new OutputStreamWriter(outstream, UTF_8);
            json.write(writer);
            writer.flush();
        }
    };
    HttpEntity entity = new EntityTemplate(cp);
    String fullURI = getFullURI(serverURI, uri);
    HttpPut put = getPUT(fullURI, timeout);
    put.setEntity(entity);

    if (httpContext == null) {
        httpContext = createHttpContext();
    }

    LOGGER.finer("PUT: " + put.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(put, httpContext);
    try {
        // based on the response do any authentication. If authentication requires
        // the request to be performed again (i.e. Basic auth) re-issue request
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, listener);

        // retry put request if we have to do authentication
        if (response == null) {
            put = getPUT(fullURI, timeout);
            put.setEntity(entity);
            response = httpClient.execute(put, httpContext);
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            // It is an unusual case to get here (in our current work flow) because it means
            // the user has become unauthenticated since the previous request 
            // (i.e. the get of the value about to put back)
            throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));

        } else {
            int responseClass = statusCode / 100;
            if (responseClass != 2) {
                if (listener != null) {
                    listener.fatalError(Messages.HttpUtils_PUT_failed(fullURI, statusCode));
                }

                throw logError(fullURI, response, Messages.HttpUtils_PUT_failed(fullURI, statusCode));
            }
            return httpContext;
        }
    } finally {
        closeResponse(response);
    }
}

From source file:org.opennms.ng.services.snmpconfig.SnmpPeerFactory.java

public static void saveToFile(final File file)
        throws UnsupportedEncodingException, FileNotFoundException, IOException {
    // Marshal to a string first, then write the string to the file. This
    // way the original config
    // isn't lost if the XML from the marshal is hosed.
    final String marshalledConfig = marshallConfig();

    SnmpPeerFactory.getWriteLock().lock();
    FileOutputStream out = null;//  w ww .  ja  v a  2  s  .  com
    Writer fileWriter = null;
    try {
        if (marshalledConfig != null) {
            out = new FileOutputStream(file);
            fileWriter = new OutputStreamWriter(out, "UTF-8");
            fileWriter.write(marshalledConfig);
            fileWriter.flush();
            fileWriter.close();
        }
    } finally {
        IOUtils.closeQuietly(fileWriter);
        IOUtils.closeQuietly(out);
        SnmpPeerFactory.getWriteLock().unlock();
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.CommonsHTTPSender.java

private static String getResponseBodyAsString(BackgroundHTTPThread methodThread)
        throws IOException, InterruptedException, HttpException {
    InputStream is = methodThread.getSafeInputStream();
    if (is != null) {
        try {/*from  ww w.j  a v a2s . c  om*/
            String charSet = methodThread.getCharSet();
            if (charSet == null)
                charSet = "utf-8";
            char[] buffer = new char[65536];
            Reader r = new InputStreamReader(is, charSet);
            Writer w = new StringWriter();
            try {
                while (true) {
                    int amt = r.read(buffer);
                    if (amt == -1)
                        break;
                    w.write(buffer, 0, amt);
                }
            } finally {
                w.flush();
            }
            return w.toString();
        } finally {
            is.close();
        }
    }
    return "";
}

From source file:org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.java

private static String getResponseBodyAsString(BackgroundHTTPThread methodThread)
        throws IOException, InterruptedException, HttpException {
    InputStream is = methodThread.getSafeInputStream();
    if (is != null) {
        try {//from  ww w. ja  v a2s  . co  m
            Charset charSet = methodThread.getCharSet();
            if (charSet == null)
                charSet = StandardCharsets.UTF_8;
            char[] buffer = new char[65536];
            Reader r = new InputStreamReader(is, charSet);
            Writer w = new StringWriter();
            try {
                while (true) {
                    int amt = r.read(buffer);
                    if (amt == -1)
                        break;
                    w.write(buffer, 0, amt);
                }
            } finally {
                w.flush();
            }
            return w.toString();
        } finally {
            is.close();
        }
    }
    return "";
}

From source file:com.chen.emailcommon.internet.Rfc822Output.java

/**
 * Write the body text.//from  ww  w .j  a  v a  2 s  .c  om
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer
 * @param out the output stream inside the writer (used for byte[] access)
 * @param bodyText Plain text and HTML versions of the original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText)
        throws IOException {
    boolean html = false;
    String text = bodyText[INDEX_BODY_TEXT];
    if (text == null) {
        text = bodyText[INDEX_BODY_HTML];
        html = true;
    }
    if (text == null) {
        writer.write("\r\n"); // a truly empty message
    } else {
        // first multipart element is the body
        String mimeType = "text/" + (html ? "html" : "plain");
        writeHeader(writer, "Content-Type", mimeType + "; charset=utf-8");
        writeHeader(writer, "Content-Transfer-Encoding", "base64");
        writer.write("\r\n");
        byte[] textBytes = text.getBytes("UTF-8");
        writer.flush();
        out.write(Base64.encode(textBytes, Base64.CRLF));
    }
}

From source file:nl.flotsam.calendar.web.CalendarIcalView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Calendar calendar = getCalendarToBeRendered(model);
    if (calendar == null) {
        throw new ServletException("Failed to locate Calendar to be rendered.");
    }//  w w  w.  j  a  va 2 s.  c om
    response.setContentType("text/calendar");
    // TODO: We can leverage data from the Calendar here
    response.setHeader("Cache-Control", "no-cache");
    response.setCharacterEncoding("UTF-8");
    Writer writer = response.getWriter();
    calendar.toIcal(writer);
    writer.flush();
}

From source file:com.kingdee.eas.bos.pureflex.manager.sce.SCEContentProvider.java

public void writeTo(OutputStream outstream) throws IOException {
    Writer writer = new OutputStreamWriter(outstream, "UTF-8"); //$NON-NLS-1$
    writer.write(content);/*from w w w .  j  a v a 2s.co m*/
    writer.flush();
}

From source file:cn.vlabs.umt.ui.tags.RequestCount.java

public int doStartTag() throws JspException {
    BeanFactory factory = (BeanFactory) pageContext.getServletContext()
            .getAttribute(Attributes.APPLICATION_CONTEXT_KEY);
    RequestService us = (RequestService) factory.getBean("RequestService");
    int count = us.getRequestCount(UserRequest.INIT);
    try {/*  w  w  w  .  ja va2s . c  o  m*/
        Writer writer = pageContext.getOut();
        writer.write(Integer.toString(count));
        writer.flush();
    } catch (IOException e) {
        throw new JspException(e);
    }
    return SKIP_BODY;
}