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.mockey.ui.InjectRealUrlPerServiceServlet.java

/**
 * Injects real URLs per service. For example, if real url is
 * //from  w  w  w.ja  va2s .co m
 * <pre>
 * http://qa1.google.com/search
 * </pre>
 * 
 * and match is
 * 
 * <pre>
 * http://qa3.google.com/
 * </pre>
 * 
 * then this method builds URL as
 * 
 * <pre>
 * http://qa3.google.com/search
 * </pre>
 * 
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String matchPattern = req.getParameter("match");
    String[] replacementArray = req.getParameterValues("replacement[]");
    JSONObject successOrFail = new JSONObject();
    if (matchPattern != null && replacementArray != null) {

        for (Long serviceId : store.getServiceIds()) {
            Service service = store.getServiceById(serviceId);
            List<Url> newUrlList = new ArrayList<Url>();
            // Build a list of real Url objects.
            for (Url realUrl : service.getRealServiceUrls()) {
                for (String replacement : replacementArray) {
                    // We don't want to inject empty string match
                    if (replacement.trim().length() > 0) {
                        Url newUrl = new Url(realUrl.getFullUrl().replaceAll(matchPattern, replacement));
                        if (!service.hasRealServiceUrl(newUrl)) {
                            newUrlList.add(newUrl);
                            // Note: you should not save or update
                            // the realServiceUrl or service while
                            // iterating through the list itself, or you'll
                            // get
                            // a java.util.ConcurrentModificationException
                            // Wait until 'after'
                        }
                    }
                }
            }
            // Save/update this new Url object list.
            for (Url newUrl : newUrlList) {
                service.saveOrUpdateRealServiceUrl(newUrl);
            }

            // Now update the service.
            store.saveOrUpdateService(service);
        }

        try {
            successOrFail.put("success", "URL injecting complete.");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        try {
            successOrFail.put("fail", "You didn't pass any match or inject URL arguments.  ");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    JSONObject responseObject = new JSONObject();

    try {
        responseObject.put("result", successOrFail);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    PrintWriter out = resp.getWriter();
    out.println(responseObject.toString());
    out.flush();
    out.close();
    return;
}

From source file:cn.vlabs.umt.ui.actions.ManageApplicationAction.java

public ActionForward loadApp(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String idStr = request.getParameter("q");
    AppService service = getAppService();
    int appid = Integer.parseInt(idStr);
    Application app = service.getApplication(appid);
    String json = "";
    if (app != null) {
        json = "[{" + "appname:'" + escape(app.getName()) + "'" + ",url:'" + escape(app.getUrl()) + "'"
                + ",description:'" + escape(app.getDescription()) + "'" + ",serverType:'"
                + escape(app.getServerType()) + "'" + ",allowOperate:" + app.isAllowOperate() + "}]";
    }//from w w w  .  j a  va2 s.c om
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    writer.write(json);
    writer.close();
    writer.flush();
    return null;
}

From source file:org.freelectron.leobel.testlwa.models.AlertsFileDataStore.java

@Override
public synchronized void writeToDisk(final List<Alert> alerts, final ResultListener listener) {
    sExecutor.execute(new Runnable() {
        @Override//from  ww  w.j av  a2s .  com
        public void run() {
            ObjectWriter writer = ObjectMapperFactory.getObjectWriter();
            PrintWriter out = null;
            try {
                out = new PrintWriter(ALARM_FILE);
                out.print(writer.writeValueAsString(alerts));
                out.flush();
                listener.onSuccess();
            } catch (IOException e) {
                Log.d("Failed to write to disk", e.getMessage(), e);
                listener.onFailure();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    });
}

From source file:com.amazon.alexa.avs.AlertsFileDataStore.java

@Override
public synchronized void writeToDisk(List<Alert> alerts, final ResultListener listener) {
    sExecutor.execute(new Runnable() {
        @Override/*from   w  w w . j  av a2s .  c o  m*/
        public void run() {
            ObjectWriter writer = ObjectMapperFactory.getObjectWriter();
            PrintWriter out = null;
            try {
                out = new PrintWriter(ALARM_FILE);
                out.print(writer.writeValueAsString(alerts));
                out.flush();
                listener.onSuccess();
            } catch (IOException e) {
                log.error("Failed to write to disk", e);
                listener.onFailure();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    });
}

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

private void saveDatabase() throws Exception {
    if (!db.exists() && !db.createNewFile()) {
        throw new Exception(String.format("Unable to create the db file: %s", DB_PATHNAME));
    }/* w  ww  . ja v  a  2 s.c  o  m*/

    PrintWriter writer = new PrintWriter(db, "UTF-8");
    IOUtils.writeLines(this.builtins, IOUtils.LINE_SEPARATOR_UNIX, writer);
    writer.flush();
    IOUtils.closeQuietly(writer);
}

From source file:com.fengduo.spark.commons.component.ComponentController.java

@ExceptionHandler(Throwable.class)
public ModelAndView handleIOException(Throwable e) throws Throwable {

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;//  w w  w.j  a v  a  2  s  .co m
    }

    if (request == null && response == null) {
        throw e;
    }

    if (request == null && response != null) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
        pw.println("{\"code\":1,\"msg\":\",?!\",\"data\":\"\"}");
        pw.flush();
        pw.close();
    }

    ModelAndView mav = new ModelAndView();
    // if (InvokeTypeTools.isAjax(request)) {
    // return createJsonMav("server exceptin or error", ResultCode.ERROR, e.getMessage());
    // }

    mav.addObject("exception", e.getCause() == null ? StringUtils.EMPTY : e.getCause().toString());
    mav.addObject("msg", StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage());
    mav.addObject("stackTrace", e.getStackTrace().toString());
    if (request.getRequestURI() != null) {
        mav.addObject("url", request.getRequestURI().toString());
    }
    mav.setViewName("error");
    return mav;
}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

private void processQuery(HttpServletRequest request, HttpServletResponse response) {
    try {//ww w  .jav a2 s.  com
        System.out.println("--------------------------------------------");
        for (Enumeration<String> en = request.getParameterNames(); en.hasMoreElements();) {
            String name = en.nextElement();
            System.out.println(name + "=" + request.getParameter(name));
        }
        // these are parameters I pass from my ProjectDataSource on all calls.  Change to meet your needs.
        String context = request.getParameter("context");
        String model = request.getParameter("model");
        String xq = request.getParameter("xq");
        String op = request.getParameter("_operationType");
        response.setContentType("text/xml");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");

        PrintWriter out = response.getWriter();
        getResponse(out, context, model, xq, op);
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//w w  w .  j  a v a 2s .c om
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}

From source file:business.controllers.UploadImageController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();
        return;//from   ww w . j  a  va2  s  . c  om
    }
    String oauthCode = "";
    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);
    List formItems = new ArrayList();
    try {
        // parses the request's content to extract file data
        formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();
        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (item.getFieldName().equals("oauthcode")) {
                oauthCode = item.getString();
            }

        }

    } catch (FileUploadException ex) {
        logger.error("Write image:" + ex);
    }

    //checkLogin
    BusinessChatHandler handler = new BusinessChatHandler();
    try {
        if (handler.isLogin(oauthCode)) {
            uploadImage(request, response, formItems);
        }
    } catch (TException ex) {
        java.util.logging.Logger.getLogger(UploadImageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:it.delli.mwebc.servlet.MWebCManager.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w  w w  .  j  av a  2s.co  m*/
        response.setContentType("text/xml");
        String action = request.getParameter("action");
        JsonObject data = new GsonBuilder()
                .registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
                    public JsonObject deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2)
                            throws JsonParseException {
                        return json.getAsJsonObject();
                    }
                }).create().fromJson(request.getParameter("data"), JsonObject.class);

        log.info("Begin managing client event request");

        log.debug("Client event request data: " + data.toString());

        Application application = (Application) request.getSession().getAttribute("application");
        application.setHttpServletRequest(request);
        application.setHttpServletResponse(response);

        Page page = application.getPage(data.get("pageName").getAsString());

        JsonElement widgets = data.get("widgets");
        if (widgets != null) {
            for (int i = 0; i < widgets.getAsJsonArray().size(); i++) {
                updateServerWidget(page, widgets.getAsJsonArray().get(i).getAsJsonObject());
            }
        }

        Command command = application.getCommand(action);
        command.execute(page, data);

        PrintWriter out = response.getWriter();
        application.printJavaScriptStream(out);
        out.flush();
        out.close();

        cleanRemovedWidgets(page);

        log.info("End managing client event request");
    } catch (Exception e) {
        log.error("Exception in forwarding control to server", e);
        throw new ServletException(e);
    }
}