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:TextFileHandler.java

public void saveGZipFile(File outFile, String content) throws Exception {
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFile));
    PrintWriter pw = new PrintWriter(out);
    pw.write(content);//from   w  ww  .j  av  a2 s  .c o  m
    pw.flush();
    pw.close();
}

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

public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String query = request.getParameter("q");
    if (query != null) {
        ServletContext context = getServlet().getServletContext();
        BeanFactory factory = (BeanFactory) context.getAttribute(Attributes.APPLICATION_CONTEXT_KEY);
        UserService us = (UserService) factory.getBean("UserService");
        Collection<User> users = us.search(query, 0, 10);

        //JSON//  w ww  .j a  v  a  2  s.c  o  m
        StringBuffer json = new StringBuffer();
        boolean first = true;
        json.append("[");
        if (users != null) {
            for (User user : users) {
                if (!first) {
                    json.append(",");
                } else {
                    first = false;
                }
                json.append("{u:'" + user.getUmtId() + "'");
                json.append(", t:'" + user.getTrueName() + "'}");
            }
        }
        json.append("]");

        //?SON
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        PrintWriter writer = response.getWriter();
        writer.print(json.toString());
        writer.flush();
        writer.close();
    }
    return null;
}

From source file:com.motorola.studio.android.utilities.TelnetFrameworkAndroid.java

/**
 * @return //ww  w .j a va2  s .co  m
 *
 */
public synchronized String write(String telnetInputText, String[] waitFor) throws IOException {
    PrintWriter commandWriter = null;
    try {
        commandWriter = new PrintWriter(telnetClient.getOutputStream());
        commandWriter.println(telnetInputText);
        commandWriter.flush();
        if (waitFor != null) {
            return waitFor(waitFor);
        }
    } finally {
        if (commandWriter != null) {
            commandWriter.close();
        }
    }

    return null;
}

From source file:com.sun.script.java.JavaCompiler.java

/**
 * compile given String source and return bytecodes as a Map.
 * /*from ww w  .  j  av  a  2s.co  m*/
 * @param fileName source fileName to be used for error messages etc.
 * @param source Java source as String
 * @param err error writer where diagnostic messages are written
 * @param sourcePath location of additional .java source files
 * @param classPath location of additional .class files
 * @return classBytes
 */
public Map<String, byte[]> compile(String fileName, String source, Writer err, String sourcePath,
        String classPath) {
    // to collect errors, warnings etc.
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    // create a new memory JavaFileManager
    MemoryJavaFileManager manager = new MemoryJavaFileManager();

    // prepare the compilation unit
    List<JavaFileObject> compUnits = new ArrayList<JavaFileObject>(1);
    compUnits.add(MemoryJavaFileManager.makeStringSource(fileName, source));

    // javac options
    List<String> options = new ArrayList<String>();
    options.add("-Xlint:all");
    options.add("-g");
    options.add("-deprecation");
    if (sourcePath != null) {
        options.add("-sourcepath");
        options.add(sourcePath);
    }

    if (classPath != null) {
        options.add("-classpath");
        options.add(classPath);
    }

    // create a compilation task
    javax.tools.JavaCompiler.CompilationTask task = tool.getTask(err, manager, diagnostics, options, null,
            compUnits);

    if (task.call() == false) {
        PrintWriter perr = new PrintWriter(err);
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            perr.println(diagnostic.getMessage(null));
        }
        perr.flush();
        return null;
    }

    Map<String, byte[]> classBytes = manager.getClassBytes();

    IOUtils.closeQuietly(manager);

    return classBytes;
}

From source file:me.tfeng.toolbox.dust.NodeEngine.java

private boolean isRegistered(Process process, String template) throws IOException {
    PrintWriter writer = new PrintWriter(process.getOutputStream());
    writer.println("[");
    printIsRegisteredExpression(writer, template);
    writer.println("]");
    writer.println("1");
    writer.flush();

    String result = readInput(process, "1");
    JsonParser parser = new JsonFactory().createParser(result).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,
            true);//from   www.  ja v  a 2  s . c  o m
    ArrayNode arrayNode = OBJECT_MAPPER.readValue(parser, ArrayNode.class);
    return arrayNode.get(0).booleanValue();
}

From source file:ch.cyberduck.cli.Console.java

public void printf(final String format, Object... args) {
    if (StringUtils.isEmpty(format)) {
        return;//from   w  w  w. j a va2s  . c  o  m
    }
    try {
        lock.acquire();
        if (console != null) {
            final PrintWriter writer = console.writer();
            if (Arrays.asList(args).isEmpty()) {
                writer.print(format);
            } else {
                writer.printf(format, args);
            }
            writer.flush();
        } else {
            if (Arrays.asList(args).isEmpty()) {
                out.printf(format);
            } else {
                out.printf(format, args);
            }
            out.flush();
        }
    } catch (InterruptedException e) {
        //
    } finally {
        lock.release();
    }
}

From source file:edu.umd.cs.submitServer.servlets.RunMoss.java

/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 *
 * @param request/*  w w w .  ja  va 2s . c o  m*/
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    SocketClient socketClient = new SocketClient();
    response.setContentType("text/plain");
    PrintWriter writer = response.getWriter();
    writer.println("Preparing to run moss");
    writer.flush();
    // set your MOSS user ID
    socketClient.setUserID("166942184");
    // socketClient.setOpt...
    String language = request.getParameter("language");
    HashSet<String> extensions = new HashSet<>();
    switch (language) {
    case "java":
        extensions.add(".java");
        break;
    case "cc":
        extensions.add(".h");
        extensions.add(".c");
        extensions.add(".cc");
        extensions.add(".C");
        extensions.add(".cxx");
        extensions.add(".c++");
        break;

    case "c":
        extensions.add(".h");
        extensions.add(".c");
        break;
    case "prolog":
        extensions.add(".pl");
        break;

    default:
        extensions.add(language);
    }
    try {
        conn = getConnection();
        // set the programming language of all student source codes

        socketClient.setLanguage(language);

        // initialize connection and send parameters
        socketClient.run();
        writer.println("Connection to moss server started");
        writer.flush();
        // get the project and all the student registrations
        Map<Integer, Submission> lastSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("lastSubmission");

        writer.println("best submissions: " + lastSubmissionMap.keySet());
        Project project = (Project) request.getAttribute("project");

        byte[] baseline = project.getBaselineZip(conn);
        if (baseline != null) {
            uploadSubmission(writer, socketClient, "baseline", baseline, true, extensions);
        }
        Set<StudentRegistration> registrationSet = (Set<StudentRegistration>) request
                .getAttribute("studentRegistrationSet");

        for (StudentRegistration registration : registrationSet) {
            Submission submission = lastSubmissionMap.get(registration.getStudentRegistrationPK());
            String classAccount = registration.getClassAccount();
            if (submission == null) {
                writer.println(
                        "No submission for #" + registration.getStudentRegistrationPK() + " " + classAccount);
            } else {
                writer.println("Uploading files for " + classAccount);
                byte[] bytes = submission.downloadArchive(conn);
                writer.flush();
                uploadSubmission(writer, socketClient, classAccount, bytes, false, extensions);
            }
        }
        writer.println("All files uploaded");

        // finished uploading, tell server to check files
        socketClient.sendQuery(5000, () -> {
            writer.println("waiting...");
            writer.flush();
        });
        URL results = socketClient.getResultURL();
        writer.println("Moss results at " + results);
        writer.flush();
        writer.close();

    } catch (SQLException e) {
        handleSQLException(e);
        throw new ServletException(e);
    } catch (MossException e) {
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);

    }
}

From source file:com.naver.timetable.interceptor.EditAuthorizationInterceptor.java

/**
 * ?  ?  ? ? ? ?  //  www.  j a  v  a  2s.com
 * @param request
 * @param response
 * @param handler
 * @return
 * @throws Exception
 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    User user = (User) request.getSession().getAttribute("user");
    if (user.getStudentNum().equals(request.getParameter("studentNum")) || (user.getUserLevel() == 1)) {
        return true;
    } else {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        out.println("<script type=\"text/javascript\">");
        out.println("alert('no permission');");
        out.println("location.href='" + request.getHeader("Referer") + "'");
        out.println("</script>");
        out.flush();
        return false;
    }
}

From source file:com.funambol.json.coredb.CoreDBServlet.java

private void sendHtmlPage(HttpServletResponse response, String result) throws IOException {
    PrintWriter writer = response.getWriter();
    writer.write(result);//  ww w  .j  av a 2 s  . co  m
    writer.flush();
}

From source file:io.mxnet.caffetranslator.Launcher.java

private void writeToOutFile(String code) {
    PrintWriter out;
    try {//from   w  ww .j  a  v a 2 s. c  om
        out = new PrintWriter(outFile);
    } catch (FileNotFoundException e) {
        System.err.println(String.format("Unable to open %s for writing", outFile.getAbsoluteFile()));
        return;
    }

    out.print(code);
    out.flush();
}