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.netxforge.oss2.config.PollerConfigFactory.java

/** {@inheritDoc} */
protected void saveXml(final String xml) throws IOException {
    if (xml != null) {
        getWriteLock().lock();/*from w  w  w .j av  a  2  s  . co  m*/
        try {
            final long timestamp = System.currentTimeMillis();
            final File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONFIG_FILE_NAME);
            LogUtils.debugf(this, "saveXml: saving config file at %d: %s", timestamp, cfgFile.getPath());
            final Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
            fileWriter.write(xml);
            fileWriter.flush();
            fileWriter.close();
            LogUtils.debugf(this, "saveXml: finished saving config file: %s", cfgFile.getPath());
        } finally {
            getWriteLock().unlock();
        }
    }
}

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

private Object request(String path, Map<String, Object> params, Set<String> fields, String method)
        throws StreamClientException {
    HttpURLConnection conn = null;

    try {/*from www. j a  va  2s .  c  o m*/
        String query = "sessionID=" + sessionID + "&method=" + method;

        if (params != null) {
            for (String key : params.keySet()) {
                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);

        // Send request
        Writer out = new OutputStreamWriter(conn.getOutputStream());
        out.write(query);
        out.flush();
        out.close();

        // 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 (Exception e) {
        throw new StreamClientException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.ewcms.publication.freemarker.directive.PropertyDirective.java

@Override
@SuppressWarnings("rawtypes")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {

    String propertyName = getPropertyName(env, params);
    Object objectValue = getObjectValue(env, params);

    if (EmptyUtil.isNull(propertyName)) {
        logger.error("\"name\" parameter must set");
        throw new TemplateModelException("\"name\" parameter must set");
    }//from   w  ww  . j  a v  a2  s .c  o  m

    try {
        if (EmptyUtil.isArrayNotEmpty(loopVars)) {
            Object value = loopValue(objectValue, propertyName, env, params);
            if (EmptyUtil.isNotNull(value)) {
                loopVars[0] = env.getObjectWrapper().wrap(value);
                if (EmptyUtil.isNull(body)) {
                    logger.warn("body is empty");
                } else {
                    body.render(env.getOut());
                }
            }
        } else if (EmptyUtil.isNotNull(body)) {
            Object value = loopValue(objectValue, propertyName, env, params);
            if (EmptyUtil.isNotNull(value)) {
                FreemarkerUtil.setVariable(env, defaultLoop, value);
                body.render(env.getOut());
                FreemarkerUtil.removeVariable(env, defaultLoop);
            }
        } else {
            String outValue = constructOut(objectValue, propertyName, env, params);
            if (EmptyUtil.isNotNull(outValue)) {
                Writer out = env.getOut();
                out.write(outValue.toString());
                out.flush();
            }
        }
    } catch (NoSuchMethodException e) {
        Writer out = env.getOut();
        out.write(e.toString());
        out.flush();
        throw new TemplateModelException(e.getMessage());
    }
}

From source file:com.googlecode.jsfFlexPlugIn.parser.velocity.JsfFlexVelocityParser.java

public synchronized void mergeCollectionToTemplate(String template, Map<String, Object> contextInfo,
        Writer targetWriter, String fileMerged) {

    for (String currKey : contextInfo.keySet()) {
        _context.put(currKey, contextInfo.get(currKey));
    }//from ww  w . j av  a2  s.co m

    try {
        _velocityEngine.mergeTemplate(template, _context, targetWriter);
        targetWriter.flush();

    } catch (Exception exceptionWhileMerging) {
        throw new RuntimeException(exceptionWhileMerging);
    } finally {
        try {
            if (targetWriter != null) {
                targetWriter.close();
            }
        } catch (IOException closerException) {
            _log.debug("Error in closing the writer within mergeCollectionToTemplate", closerException);
        }
    }

    mergeCollectionToTemplateFinished(fileMerged);
}

From source file:com.cpjit.swagger4j.support.internal.DefaultApiViewWriter.java

@Deprecated
@Override/* ww w  .  ja v a 2 s  . c o  m*/
public void writeIndex(HttpServletRequest request, HttpServletResponse response, String lang, Properties props)
        throws IOException {
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("lang", lang);
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    root.put("basePath", basePath);
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    root.put("getApisUrl", "http://" + host + "/api" + suffix);
    root.put("apiDescription", props.getProperty("apiDescription"));
    root.put("apiTitle", props.getProperty("apiTitle"));
    root.put("apiVersion", props.getProperty("apiVersion"));
    root.put("suffix", suffix);
    Template template = FreemarkerUtils.getTemplate(getTemplateName());
    response.setContentType("text/html;charset=utf-8");
    Writer out = response.getWriter();
    try {
        template.process(root, out);
    } catch (TemplateException e) {
        throw new IOException(e);
    }
    out.flush();
    out.close();
}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {// w  w  w.j  a  va 2  s  .  c  o  m
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

        while ((entry = zipIn.getNextEntry()) != null) {

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:org.hobsoft.symmetry.spring.SymmetryHttpMessageConverter.java

@Override
protected void writeInternal(T component, HttpOutputMessage outputMessage) throws IOException {
    OutputStream bodyStream = outputMessage.getBody();
    Charset charset = getCharset(outputMessage);
    Writer bodyWriter = new OutputStreamWriter(bodyStream, charset);

    try {/*from w w w  .ja  va2s .c  om*/
        reflector.reflect(component, bodyWriter);
    } catch (ReflectorException exception) {
        throw new HttpMessageNotWritableException("Error writing component", exception);
    }

    bodyWriter.flush();
}

From source file:com.oauth.servlet.AuthorizationCallbackServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from ww  w. jav  a 2 s.c o  m*/
        System.err.println(req.getQueryString());
        System.err.println(req.getRequestURI());
        String token = null;
        String responseBody = null;
        if (req.getParameter("code") != null) {
            HttpClient httpclient = new DefaultHttpClient();
            String authCode = req.getParameter("code");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try {
                if (req.getRequestURI().indexOf("git") > 0) {
                    HttpGet httpget = new HttpGet(client.getAccessTokenUrl(authCode));

                    responseBody = httpclient.execute(httpget, responseHandler);
                    int accessTokenStartIndex = responseBody.indexOf("access_token=")
                            + "access_token=".length();
                    token = responseBody.substring(accessTokenStartIndex,
                            responseBody.indexOf("&", accessTokenStartIndex));

                } else if (req.getRequestURI().indexOf("isam") > 0) {
                    System.err.println(iSAMClient.getAccessTokenUrl());
                    HttpPost httpPost = new HttpPost(iSAMClient.getAccessTokenUrl());
                    httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

                    System.err.println("Post Params--------");
                    for (Iterator<NameValuePair> postParamIter = iSAMClient.getPostParams(authCode)
                            .iterator(); postParamIter.hasNext();) {
                        NameValuePair postParam = postParamIter.next();
                        System.err.println(postParam.getName() + "=" + postParam.getValue());
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(iSAMClient.getPostParams(authCode)));
                    System.err.println("Post Params--------");
                    responseBody = httpclient.execute(httpPost, responseHandler);
                    token = parseJsonString(responseBody);
                } else {
                    resp.sendError(HttpStatus.SC_FORBIDDEN);
                }
                System.err.println(responseBody);
                req.setAttribute("Response", responseBody);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
            resp.sendRedirect("userDetails.jsp?token=" + token);
        } /*else if(req.getParameter("access_token") != null) {
           Writer w = resp.getWriter();
                    
            w.write("<html><body><center>");
            w.write("<h3>");
            w.write("User Code [" + req.getParameter("access_token") + "] has successfully logged in!");
            w.write("</h3>");
            w.write("</center></body></html>");
                    
            w.flush();
            w.close();   
          } */else {
            Writer w = resp.getWriter();

            w.write("<html><body><center>");
            w.write("<h3>");
            w.write("UNAUTHORIZED Access!");
            w.write("</h3>");
            w.write("</center></body></html>");

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

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ste.web.http.velocity.VelocityHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    String view = (String) context.getAttribute(ATTR_VIEW);
    if (view == null) {
        return;/*from  ww w.  j  a  v  a 2s .  c  om*/
    }

    view = getViewPath(request.getRequestLine().getUri(), view);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(baos);
    try {
        Template t = engine.getTemplate(view);
        t.merge(buildContext(request, (HttpSessionContext) context), out);
        out.flush();
    } catch (ResourceNotFoundException e) {
        response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "View " + view + " not found.");
        return;
    } catch (ParseErrorException e) {
        throw new HttpException("Parse error evaluating " + view + ": " + e, e);
    } catch (MethodInvocationException e) {
        throw new HttpException("Method invocation error evaluating " + view + ": " + e, e);
    }

    BasicHttpEntity body = (BasicHttpEntity) response.getEntity();
    body.setContentLength(baos.size());
    body.setContent(new ByteArrayInputStream(baos.toByteArray()));
    if ((body.getContentType() == null) || StringUtils.isBlank(body.getContentType().getValue())) {
        body.setContentType(ContentType.TEXT_HTML.getMimeType());
    }
}

From source file:com.webguys.djinn.marid.util.BuiltinAnnotationProcessor.java

private void writeSourceFile(ST st) throws Exception {
    ErrorBuffer writeErrorBuffer = new ErrorBuffer();
    Writer writer = null;
    try {//from  w  w  w. j a v a2 s.  c o m
        writer = this.sourceFile.openWriter();

        st.write(new AutoIndentWriter(writer), writeErrorBuffer);
    } finally {
        if (null != writer) {
            writer.flush();
        }
        IOUtils.closeQuietly(writer);
    }

    if (!writeErrorBuffer.errors.isEmpty()) {
        throw new Exception(writeErrorBuffer.toString());
    }
}