Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.iwethey.forums.web.json.FastJsonView.java

public void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    try {//from  w  ww . ja v  a 2  s.c om
        OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());

        Object data = model.get("json");

        Object serTmp = model.get("serializer");
        JacksonSerializer ser = null;
        if (serTmp != null && JacksonSerializer.class.isAssignableFrom(serTmp.getClass())) {
            ser = (JacksonSerializer) serTmp;
        } else {
            ser = new JacksonSerializer();
        }

        if (data != null) {
            ser.serialize(data, out);
        }

        out.flush();
    } catch (IOException ie) {
        throw new ServletException(ie);
    } catch (JsonException e) {
        throw new ServletException(e);
    }
}

From source file:com.google.samples.quickstart.signin.MainActivity.java

private String downloadUrl(String myurl, String tokenid) throws IOException {
    InputStream is = null;//from   w w w  .java2s  .com
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        JSONObject cred = new JSONObject();
        cred.put("tokenid", tokenid);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(cred.toString());
        wr.flush();
        //con.setRequestMethod("POST");
        //conn.setRequestProperty("tokenid",tokenid);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response);

        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.gephi.ui.components.ReportSelection.java

private boolean saveReport(String html, File destinationFolder) throws IOException {
    if (!destinationFolder.exists()) {
        destinationFolder.mkdir();//  w w w  .j av  a 2 s . c o  m
    } else {
        if (!destinationFolder.isDirectory()) {
            return false;
        }
    }

    //Find images location
    String imgRegex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
    Pattern pattern = Pattern.compile(imgRegex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(html);
    StringBuffer replaceBuffer = new StringBuffer();
    while (matcher.find()) {
        String fileAbsolutePath = matcher.group(1);
        if (fileAbsolutePath.startsWith("file:")) {
            fileAbsolutePath = fileAbsolutePath.replaceFirst("file:", "");
        }
        File file = new File(fileAbsolutePath);
        if (file.exists()) {
            copy(file, destinationFolder);
        }

        //Replace temp path
        matcher.appendReplacement(replaceBuffer, "<IMG SRC=\"" + file.getName() + "\">");
    }
    matcher.appendTail(replaceBuffer);

    //Write HTML file
    File htmlFile = new File(destinationFolder, "report.html");
    FileOutputStream outputStream = new FileOutputStream(htmlFile);
    OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8");
    out.append(replaceBuffer.toString());
    out.flush();
    out.close();
    outputStream.close();

    return true;
}

From source file:com.cubusmail.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   ww w  . j  a  v a  2 s  .com
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                log.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.apache.uima.ruta.resource.TreeWordList.java

private void writeCompressedTWLFile(TextNode root, String path, String encoding) throws IOException {
    FileOutputStream fos = new FileOutputStream(path);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zos = new ZipOutputStream(bos);
    OutputStreamWriter writer = new OutputStreamWriter(zos, encoding);
    zos.putNextEntry(new ZipEntry(path));
    writeTWLFile(root, writer);/*  ww w  .j a  v  a  2 s .c o m*/
    writer.flush();
    zos.closeEntry();
    writer.close();
}

From source file:com.cubusmail.gwtui.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from   w  w  w.  ja v a  2  s .  co m*/
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.amastigote.xdu.query.module.EduSystem.java

@Override
public boolean login(String username, String password) throws IOException {
    preLogin();/*  w w  w  .j  a  v  a  2 s  . co  m*/
    URL url = new URL(LOGIN_HOST + LOGIN_SUFFIX);
    HttpURLConnection httpURLConnection_a = (HttpURLConnection) url.openConnection();
    httpURLConnection_a.setRequestMethod("POST");
    httpURLConnection_a.setUseCaches(false);
    httpURLConnection_a.setInstanceFollowRedirects(false);
    httpURLConnection_a.setDoOutput(true);

    String OUTPUT_DATA = "username=";
    OUTPUT_DATA += username;
    OUTPUT_DATA += "&password=";
    OUTPUT_DATA += password;
    OUTPUT_DATA += "&submit=";
    OUTPUT_DATA += "&lt=" + LOGIN_PARAM_lt;
    OUTPUT_DATA += "&execution=" + LOGIN_PARAM_execution;
    OUTPUT_DATA += "&_eventId=" + LOGIN_PARAM__eventId;
    OUTPUT_DATA += "&rmShown=" + LOGIN_PARAM_rmShown;

    httpURLConnection_a.setRequestProperty("Cookie",
            "route=" + ROUTE
                    + "; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN; JSESSIONID="
                    + LOGIN_JSESSIONID + "; BIGipServeridsnew.xidian.edu.cn=" + BIGIP_SERVER_IDS_NEW + ";");

    httpURLConnection_a.connect();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection_a.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(OUTPUT_DATA);
    outputStreamWriter.flush();
    outputStreamWriter.close();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection_a.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("a");
    if (elements.size() == 0)
        return false;
    String SYS_LOCATION = elements.get(0).attr("href");

    URL sys_location = new URL(SYS_LOCATION);
    HttpURLConnection httpUrlConnection_b = (HttpURLConnection) sys_location.openConnection();
    httpUrlConnection_b.setInstanceFollowRedirects(false);
    httpUrlConnection_b.connect();
    List<String> cookies_to_set = httpUrlConnection_b.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(11, e.indexOf(";"));
    httpURLConnection_a.disconnect();
    httpUrlConnection_b.disconnect();
    return checkIsLogin(username);
}

From source file:org.apache.ranger.audit.provider.hdfs.HdfsLogDestination.java

@Override
public boolean flush() {
    mLogger.debug("==> HdfsLogDestination.flush()");

    boolean ret = false;

    OutputStreamWriter writer = mWriter;

    if (writer != null) {
        try {/*from   w  ww . j av  a 2s  . c  o m*/
            writer.flush();

            ret = true;
        } catch (IOException excp) {
            logException("HdfsLogDestination: flush() failed", excp);
        }
    }

    FSDataOutputStream ostream = mFsDataOutStream;

    if (ostream != null) {
        try {
            ostream.hflush();

            ret = true;
        } catch (IOException excp) {
            logException("HdfsLogDestination: hflush() failed", excp);
        }
    }

    if (ret) {
        mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
    }

    mLogger.debug("<== HdfsLogDestination.flush()");

    return ret;
}

From source file:org.guanxi.sp.engine.service.saml2.WebBrowserSSOAuthConsumerService.java

private String processGuardConnection(String acsURL, String entityID, String keystoreFile,
        String keystorePassword, String truststoreFile, String truststorePassword,
        ResponseDocument responseDocument, String guardSession) throws GuanxiException, IOException {
    EntityConnection connection;//from   w ww.j a v  a 2s  . c  o  m

    Bag bag = getBag(responseDocument, guardSession);

    // Initialise the connection to the Guard's attribute consumer service
    connection = new EntityConnection(acsURL, entityID, keystoreFile, keystorePassword, truststoreFile,
            truststorePassword, EntityConnection.PROBING_OFF);
    connection.setDoOutput(true);
    connection.connect();

    // Send the data to the Guard in an explicit POST variable
    String json = URLEncoder.encode(Guanxi.REQUEST_PARAMETER_SAML_ATTRIBUTES, "UTF-8") + "="
            + URLEncoder.encode(bag.toJSON(), "UTF-8");

    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();

    //os.close();

    // ...and read the response from the Guard
    return new String(Utils.read(connection.getInputStream()));
}

From source file:com.gu.management.logging.Log4JManagerServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    OutputStreamWriter fileWriter = new OutputStreamWriter(response.getOutputStream());

    fileWriter.write(MANAGEMENT_PAGE_HEAD);

    @SuppressWarnings({ "unchecked" })
    List<Logger> loggers = sortLoggers(LogManager.getCurrentLoggers());

    for (Logger logger : loggers) {
        fileWriter.write(String.format(LOGGER_TABLE_ROW, logger.getName(), generateOptionsFor(logger),
                logger.getEffectiveLevel()));
    }//from w w  w  .  j  a v  a 2s. co  m

    fileWriter.write(MANAGEMENT_PAGE_FOOT);

    fileWriter.flush();
}