Example usage for java.io PrintWriter flush

List of usage examples for java.io PrintWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:com.att.api.speech.controller.TextToSpeechController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final JSONObject jresponse = new JSONObject();
    try {//from  w w  w . j  av  a2s.c o  m

        final OAuthToken token = this.getFileToken();
        final TtsService srvc = new TtsService(appConfig.getApiFQDN(), token);

        final String contentType = request.getParameter("contentType");
        final String plaintext = request.getParameter("plaintext");
        final String ssml = request.getParameter("ssml");
        final String xArg = request.getParameter("x_arg");
        String speechText = null;
        if (contentType.equals("text/plain")) {
            speechText = plaintext;
            if (speechText.length() > 250) {
                throw new Exception("Character limited of 250 reached");
            }
        } else {
            speechText = ssml;
        }
        final byte[] wavBytes = srvc.sendRequest(contentType, speechText, xArg);

        JSONObject jaudio = new JSONObject().put("type", "audio/wav").put("base64",
                new String(Base64.encodeBase64(wavBytes)));
        jresponse.put("success", true).put("audio", jaudio);
    } catch (Exception e) {
        jresponse.put("success", false).put("text", e.getMessage());
    }

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.print(jresponse);
    writer.flush();
}

From source file:com.att.api.immn.controller.SendMsgController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final HttpSession session = request.getSession();
    OAuthToken token = (OAuthToken) session.getAttribute("token");

    final String addr = request.getParameter("address");
    final String[] addrs = addr.split(",");
    for (int i = 0; i < addrs.length; ++i)
        addrs[i] = addrs[i].trim();//from w w w .j a  va  2 s  .  c  o m

    final String msg = request.getParameter("sendMsgInput");
    final String subject = request.getParameter("sendSubjectInput");
    final boolean group = request.getParameter("groupCheckbox") != null;
    // TODO: handle attachments

    IMMNService srvc = new IMMNService(appConfig.getApiFQDN(), token);
    JSONObject jresponse = new JSONObject();
    try {
        SendResponse sendResponse = null;
        if (!subject.isEmpty() || group) {
            sendResponse = srvc.sendMessage(addrs, msg, subject, group, /* TODO: finish attachments */ null);
        } else {
            sendResponse = srvc.sendMessage(addrs, msg);
        }
        final String id = sendResponse.getId();
        jresponse.put("success", true).put("text", "id: " + id);
    } catch (RESTException re) {
        jresponse.put("success", false).put("text", re.getMessage());
    }

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.print(jresponse);
    writer.flush();
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Write response directly as Event-Stream for Server Sent Events.
 *
 * @param asyncContext - Asynchronous Context.
 * @param event - Name of event to be written on response.
 * @param data - Content of event ot be written on response.
 * @param retry - Time in (milliseconds) for client retry opening connection.
 *              after asynchronous context is closed.
 * @throws IOException/*from   ww  w  . j a  v  a 2  s .  c  o  m*/
 */
public static void writeResponseAsEventStream(AsyncContext asyncContext, String event, Object data, Long retry)
        throws IOException {
    if (asyncContext != null && event != null && data != null) {
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
        response.setContentType("text/event-stream");
        PrintWriter printWriter = response.getWriter();

        if (retry != null) {
            printWriter.write("retry:" + retry + "\n");
        }
        printWriter.write("event:" + event + "\n");
        printWriter.write("data:" + data + "\n\n");
        printWriter.flush();
    }
}

From source file:bookUtilities.RemoveBookServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from www  .  j  ava  2  s.  co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    JSONObject message = removeBook(request.getParameter("bookId"));
    PrintWriter printout = response.getWriter();
    printout.print(message);
    printout.flush();
}

From source file:com.att.api.immn.controller.LoadController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final HttpSession session = request.getSession();
    OAuthToken token = (OAuthToken) session.getAttribute("token");
    final Boolean authenticated = (token != null && !token.isAccessTokenExpired());

    final String FQDN = appConfig.getOauthFQDN();
    final String clientId = appConfig.getClientId();
    final String scope = appConfig.getProperty("scope");
    final String redirectUri = appConfig.getProperty("redirectUri");
    final String redirect_url = FQDN + "/oauth/v4/authorize?client_id=" + clientId + "&scope=" + scope
            + "&redirect_uri=" + redirectUri;
    final boolean subscriptionActive = session.getAttribute("subscriptionId") != null;

    JSONObject jchannel = new JSONObject().put("channelId", appConfig.getProperty("channelId"))
            .put("channelType", appConfig.getProperty("channelType"))
            .put("maxEvents", appConfig.getProperty("maxEvents"))
            .put("contentType", appConfig.getProperty("contentType"));

    JSONObject jresponse = new JSONObject().put("authenticated", authenticated)
            .put("redirect_url", redirect_url).put("server_time", DateUtil.getTime())
            .put("download", this.appConfig.getProperty("linkDownload"))
            .put("github", this.appConfig.getProperty("linkGithub")).put("notificationChannel", jchannel)
            .put("subscriptionActive", subscriptionActive);

    final String savedData = (String) session.getAttribute("savedData");
    if (savedData != null) {
        final JSONObject jsavedData = new JSONObject(savedData);
        jresponse.put("savedData", jsavedData);
    }// w  w  w . java  2s .  co  m

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.print(jresponse);
    writer.flush();
}

From source file:org.tec.webapp.web.view.JSONView.java

/**
 * {@inheritDoc}/*  w  w w  .ja v a2s. c o  m*/
 */
@Override()
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {
        JSONSerializable json = (JSONSerializable) model.get(JSONModelAndView.ERROR_KEY);

        if (json != null) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "failed to process response");
        } else {
            json = (JSONSerializable) model.get(JSONModelAndView.JSON_KEY);

            if (json != null) {
                if (mLogger.isDebugEnabled()) {
                    mLogger.debug("JSON Response\n" + json.toJSON());
                }
                response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
                PrintWriter pw = response.getWriter();
                pw.write(json.toJSON());
                pw.flush();
            } else // null json for controllers that usurp the response or didn't intend to
            {
                mLogger.warn("null json object");
            }
        }
    } catch (Exception e) {
        mLogger.error("error", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "failed to process response");
    }
}

From source file:bookUtilities.BookListServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w .j a  va  2s  . c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    JSONArray books = getBooks();
    PrintWriter printout = response.getWriter();
    printout.print(books);
    printout.flush();
}

From source file:model.settings.ReadSettings.java

/**
 * Writes text _text to path _path. // ww  w.j a v  a 2  s .  c  om
 * @param _path location of file.
 * @param _text text to be written into the file.
 * 
 * @throws IOException is thrown in case of error.
 */
private static void writeToFile(final String _path, final String _text) throws IOException {

    //create writer
    PrintWriter pWriter = new PrintWriter(new FileWriter(_path));

    //print text
    pWriter.println(_text);
    pWriter.flush();

    //close writer
    pWriter.close();
}

From source file:com.ict.nasc.tasc.app.module.screen.simple.Download.java

/**
 * /*from   w ww .  j  a  v  a2  s  .  c  o  m*/
 * 
 * @param filename
 * @throws Exception
 */
public void execute(@Param("filename") String filename) throws Exception {
    // buffering? ???  
    brc.setBuffering(false);

    // headers?????us-ascii???? 
    filename = defaultIfNull(trimToNull(filename), "image") + ".txt";
    filename = "\"" + escapeURL(filename) + "\"";

    response.setHeader("Content-disposition", "attachment; filename=" + filename);

    // ??content type?
    // HTML?JSON?JavaScript?JPG?PDF?EXCEL 
    response.setContentType("text/plain");

    PrintWriter out = response.getWriter();

    for (int i = 0; i < 100; i++) {
        out.flush(); // ???

        for (int j = 0; j < 100000; j++) {
            out.print(i);
        }

        out.println();

        Thread.sleep(100); // ??
    }
}

From source file:com.alibaba.dubbo.governance.web.home.module.screen.Servicestatus.java

public void execute(Map<String, Object> context) throws Exception {
    String uri = request.getRequestURI();
    String contextPath = request.getContextPath();
    if (contextPath != null && !"/".equals(contextPath)) {
        uri = uri.substring(contextPath.length());
    }/*from   w w  w  . j a  v a2s.com*/
    if (uri.startsWith("/status/")) {
        uri = uri.substring("/status/".length());
    }
    //        Map<String, String> providers = registryCache.getServices().get(uri);
    //        if (providers == null || providers.size() == 0) {
    //            providers = providerDAO.lookup(uri);
    //        }
    //        if (providers == null || providers.size() == 0) {
    //            context.put("message", "ERROR"
    //                        + new SimpleDateFormat(" [yyyy-MM-dd HH:mm:ss] ").format(new Date())
    //                        + Status.filterOK("No such any provider for service " + uri));
    //        } else {
    //            context.put("message", "OK");
    //        }
    PrintWriter writer = response.getWriter();
    writer.print(context.get("message").toString());
    writer.flush();
}