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.boundlessgeo.geoserver.json.JSONArr.java

@Override
void write(Writer out) throws IOException {
    if (raw == null) {
        out.write("null");
    } else {/*from  w w  w .j  av a 2s.  com*/
        boolean first = true;
        Iterator iter = iterator();
        out.write('[');
        while (iter.hasNext()) {
            if (first)
                first = false;
            else
                out.write(',');

            Object value = iter.next();
            if (value == null) {
                out.write("null");
                continue;
            }
            value = wrapOrSelf(value);
            JSONWrapper.write(value, out);
        }
        out.write(']');

    }
    out.flush();
}

From source file:com.norconex.collector.core.crawler.AbstractCrawlerConfig.java

protected void writeArray(Writer out, String listTagName, String objectTagName, Object[] array)
        throws IOException {
    if (ArrayUtils.isEmpty(array)) {
        return;/*from w ww . java  2  s  .co  m*/
    }
    out.write("<" + listTagName + ">");
    for (Object obj : array) {
        writeObject(out, objectTagName, obj);
    }
    out.write("</" + listTagName + ">");
    out.flush();
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

private void doKill(String[] reqC, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    if (reqC.length < 2) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId.");
        return;//from   w w w . java  2s.  c  o  m
    }
    RunId runId = new RunId(reqC[1]);
    String user = request.getParameter("sun");
    String password = request.getParameter("sp");

    // Check the status of the run
    boolean found = false;
    boolean queued = false;
    String terminateStatus = null;
    RunResult result = RunResult.getInstance(runId);
    if (result != null) {
        found = true;
        if ("COMPLETED".equals(result.status) || "FAILED".equals(result.status)
                || "KILLED".equals(result.status)) {
            terminateStatus = result.status;
        }
    } else { // If not found, look in queue
        String[] pending = RunQ.listPending();
        if (pending != null) {
            for (String run : pending) {
                if (run.equals(runId.toString())) {
                    found = true;
                    queued = true;
                    break;
                }
            }
        }
    }

    if (found && terminateStatus == null) { // not yet terminated

        // First authenticate the user and make sure he/she is the CLI user.
        boolean hasPermission = true;
        if (Config.SECURITY_ENABLED) {
            if (Config.CLI_SUBMITTER == null || Config.CLI_SUBMITTER.length() == 0
                    || !Config.CLI_SUBMITTER.equals(user)) {
                hasPermission = false;
            }
            if (Config.SUBMIT_PASSWORD == null || Config.SUBMIT_PASSWORD.length() == 0
                    || !Config.SUBMIT_PASSWORD.equals(password)) {
                hasPermission = false;
            }
            if (AccessController.isKillAllowed(user, runId.toString())) {
                hasPermission = false;
            }
        }

        if (hasPermission) {

            // No matter of status, the run may be running by now.
            // So check for active runs first.
            if (RunQ.getHandle().killCurrentRun(runId.toString(), user) != null) {
                terminateStatus = "KILLING";
            } else { // Or the run may have already terminated...
                result = RunResult.getInstance(runId);
                if (result != null) {
                    if ("COMPLETED".equals(result.status) || "FAILED".equals(result.status)
                            || "KILLED".equals(result.status)) {
                        terminateStatus = result.status;
                    }
                } else if (queued) { // Or it still is in the queue
                    RunQ.getHandle().deleteRun(runId.toString());
                    terminateStatus = "DELETED";
                }
            }
        } else {
            if (queued) // Run was removed in the meantime
                terminateStatus = "DELETED";
            else
                terminateStatus = "DENIED";
        }
    }

    if (!found) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "No such runId: " + runId);
    } else {
        Writer w = response.getWriter();
        w.write(terminateStatus + '\n');
        w.flush();
        w.close();
    }
}

From source file:com.sun.faban.harness.webclient.Deployer.java

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

    try {/*from w w  w . jav  a  2  s .c o m*/
        List<String> deployNames = new ArrayList<String>();
        List<String> cantDeployNames = new ArrayList<String>();
        List<String> errDeployNames = new ArrayList<String>();
        List<String> invalidNames = new ArrayList<String>();
        List<String> errHeaders = new ArrayList<String>();
        List<String> errDetails = new ArrayList<String>();

        String user = null;
        String password = null;
        boolean clearConfig = false;
        boolean hasPermission = true;

        // Check whether we have to return text or html
        boolean acceptHtml = false;
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0)
            acceptHtml = true;

        DiskFileUpload fu = new DiskFileUpload();
        // No maximum size
        fu.setSizeMax(-1);
        // maximum size that will be stored in memory
        fu.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        fu.setRepositoryPath(Config.TMP_DIR);

        StringWriter messageBuffer = new StringWriter();
        PrintWriter messageWriter = new PrintWriter(messageBuffer);

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }
        // assume we know there are two files. The first file is a small
        // text file, the second is unknown and is written to a file on
        // the server
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                if ("user".equals(fieldName)) {
                    user = item.getString();
                } else if ("password".equals(fieldName)) {
                    password = item.getString();
                } else if ("clearconfig".equals(fieldName)) {
                    String value = item.getString();
                    clearConfig = Boolean.parseBoolean(value);
                }
                continue;
            }

            if (!"jarfile".equals(fieldName))
                continue;

            String fileName = item.getName();

            if (fileName == null) // We don't process files without names
                continue;

            if (Config.SECURITY_ENABLED) {
                if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0
                        || !Config.DEPLOY_USER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0
                        || !Config.DEPLOY_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }
            // Now, this name may have a path attached, dependent on the
            // source browser. We need to cover all possible clients...

            char[] pathSeparators = { '/', '\\' };
            // Well, if there is another separator we did not account for,
            // just add it above.

            for (int j = 0; j < pathSeparators.length; j++) {
                int idx = fileName.lastIndexOf(pathSeparators[j]);
                if (idx != -1) {
                    fileName = fileName.substring(idx + 1);
                    break;
                }
            }

            // Ignore all non-jarfiles.
            if (!fileName.toLowerCase().endsWith(".jar")) {
                invalidNames.add(fileName);
                continue;
            }

            String deployName = fileName.substring(0, fileName.length() - 4);

            if (deployName.indexOf('.') > -1) {
                invalidNames.add(deployName);
                continue;
            }

            // Check if we can deploy benchmark or service.
            // If running or queued, we won't deploy benchmark.
            // If service being used by current run,we won't deploy service.
            if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) {
                cantDeployNames.add(deployName);
                continue;
            }

            File uploadFile = new File(Config.BENCHMARK_DIR, fileName);
            if (uploadFile.exists())
                FileHelper.recursiveDelete(uploadFile);

            try {
                item.write(uploadFile);
            } catch (Exception e) {
                throw new ServletException(e);
            }

            try {
                DeployUtil.processUploadedJar(uploadFile, deployName);
            } catch (Exception e) {
                messageWriter.println("\nError deploying " + deployName + ".\n");
                e.printStackTrace(messageWriter);
                errDeployNames.add(deployName);
                continue;
            }
            deployNames.add(deployName);
        }

        if (clearConfig)
            for (String benchName : deployNames)
                DeployUtil.clearConfig(benchName);

        if (!hasPermission)
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        else if (cantDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        else if (errDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (invalidNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (deployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CREATED);
        else
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        StringBuilder b = new StringBuilder();

        if (deployNames.size() > 0) {
            if (deployNames.size() > 1)
                b.append("Benchmarks/services ");
            else
                b.append("Benchmark/service ");

            for (int i = 0; i < deployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) deployNames.get(i));
            }

            b.append(" deployed.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (invalidNames.size() > 0) {
            if (invalidNames.size() > 1)
                b.append("Invalid deploy files ");
            else
                b.append("Invalid deploy file ");
            for (int i = 0; i < invalidNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) invalidNames.get(i));
            }
            b.append(". Deploy files must have .jar extension.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (cantDeployNames.size() > 0) {
            if (cantDeployNames.size() > 1)
                b.append("Cannot deploy benchmarks/services ");
            else
                b.append("Cannot deploy benchmark/services ");
            for (int i = 0; i < cantDeployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) cantDeployNames.get(i));
            }
            b.append(". Benchmark/services being used or " + "queued up for run.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (errDeployNames.size() > 0) {
            if (errDeployNames.size() > 1) {
                b.append("Error deploying benchmarks/services ");
                for (int i = 0; i < errDeployNames.size(); i++) {
                    if (i > 0)
                        b.append(", ");
                    b.append((String) errDeployNames.get(i));
                }
            }

            errDetails.add(messageBuffer.toString());
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (!hasPermission)
            errHeaders.add("Permission denied!");

        Writer writer = response.getWriter();
        if (acceptHtml)
            writeHtml(request, writer, errHeaders, errDetails);
        else
            writeText(writer, errHeaders, errDetails);
        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:com.aurel.track.user.LogoffAction.java

private void loginForm(HttpServletResponse response, String customLoginFullPath) throws Exception {
    Writer writer = null;
    BufferedReader reader = null;
    try {// w w  w.j  a  va  2s . co  m
        URL url = new URL(customLoginFullPath);
        URLConnection conn = url.openConnection();
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        writer = response.getWriter();
        String line;
        while ((line = reader.readLine()) != null) {
            writer.append(line);
        }
    } finally {
        if (writer != null) {
            writer.flush();
        }
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars, Writer writer)
        throws ScriptException {
    try {/* w w w .ja va 2 s. c o  m*/
        ScriptEngine scriptEngine = getEngine();
        SimpleScriptContext simpleScriptContext = new SimpleScriptContext();
        Bindings bindings = scriptEngine.createBindings();
        bindings.putAll(contextVars);
        simpleScriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        executePreExecuteScripts(simpleScriptContext);
        simpleScriptContext.setWriter(writer);
        CompiledScript compiledScript = getCachedScript(script);
        Object object = compiledScript.eval(simpleScriptContext);
        writer.flush();
        if (object == null)
            return bindings;
        return object;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:business.services.ExcerptListService.java

/**
 * Write the excerpt list as a file./*from w  w w.  ja v a  2  s.  c  o  m*/
 * @param list - the list
 * @param selectedOnly - writes only selected excerpts if true; all excerpts otherwise.
 * @return the resource holding selected excerpts or all (depends on the value of {@value selected}
 * in CSV format.
 */
public HttpEntity<InputStreamResource> writeExcerptList(ExcerptList list, boolean selectedOnly) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out, EXCERPT_LIST_CHARACTER_ENCODING);
        CSVWriter csvwriter = new CSVWriter(writer, ';', '"');
        csvwriter.writeNext(list.getCsvColumnNames());
        for (ExcerptEntry entry : list.getEntries()) {
            if (!selectedOnly || entry.isSelected()) {
                csvwriter.writeNext(entry.getCsvValues());
            }
        }
        csvwriter.flush();
        writer.flush();
        out.flush();
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        csvwriter.close();
        writer.close();
        out.close();
        InputStreamResource resource = new InputStreamResource(in);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/csv;charset=" + EXCERPT_LIST_CHARACTER_ENCODING));
        String filename = (selectedOnly ? "selection" : "excerpts") + "_" + list.getProcessInstanceId()
                + ".csv";
        headers.set("Content-Disposition", "attachment; filename=" + filename);
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        log.info("Returning reponse.");
        return response;
    } catch (IOException e) {
        log.error(e.getStackTrace());
        log.error(e.getMessage());
        throw new ExcerptListDownloadError();
    }
}

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

private void addFileToRequest(String boundary, Writer out, OutputStream binaryStream, File file)
        throws IOException {
    out.append("--" + boundary).append(NEW_LINE);
    out.append("Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"" + file.getName() + "\"")
            .append(NEW_LINE);/*from w w  w .  j a  v  a2s  . c o m*/
    out.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(NEW_LINE);
    out.append("Content-Transfer-Encoding: binary").append(NEW_LINE).append(NEW_LINE);
    out.flush();

    FileInputStream inputStream = new FileInputStream(file);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        binaryStream.write(buffer, 0, bytesRead);
    }
    binaryStream.flush();
    inputStream.close();

    out.append(NEW_LINE);
    out.flush();
    out.append("--").append(boundary).append("--").append(NEW_LINE);
}

From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTask.java

/**
 * {@inheritDoc}//  w  w  w  .  ja  v a2 s .  c  om
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final JobRequest jobRequest = jobExecEnv.getJobRequest();
        final String user = jobRequest.getUser();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobRequest.getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue."));
        log.info("Starting Job Kickoff Task for job {}", jobId);

        // At this point all contents are written to the run script and we call an explicit flush and close to write
        // the contents to the file before we execute it.
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new GenieServerException("Failed to execute job with exception." + e);
        }
        // Create user, if enabled
        if (isUserCreationEnabled) {
            createUser(user, jobRequest.getGroup().orElse(null));
        }
        // Set the ownership to the user and run as the user, if enabled
        final List<String> command = new ArrayList<>();
        if (isRunAsUserEnabled) {
            changeOwnershipOfDirectory(jobWorkingDirectory, user);

            // This is needed because the genie.log file is still generated as the user running Genie system.
            makeDirGroupWritable(jobWorkingDirectory + "/genie/logs");
            command.add("sudo");
            command.add("-u");
            command.add(user);
        }

        // If the OS is linux use setsid to launch the process so that the entire process tree
        // is launched in process group id which is the same as the pid of the parent process
        if (SystemUtils.IS_OS_LINUX) {
            command.add("setsid");
        }

        final String runScript = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_JOB_LAUNCHER_SCRIPT;
        command.add(runScript);

        // Cannot convert to executor because it does not provide an api to get process id.
        final ProcessBuilder pb = new ProcessBuilder(command).directory(jobExecEnv.getJobWorkingDir())
                .redirectOutput(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH))
                .redirectError(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH));

        //
        // Check if file can be executed. This is to fix issue where execution of the run script fails because
        // the file may be used by some other program
        //
        canExecute(runScript);
        try {
            final Process process = pb.start();
            final int processId = this.getProcessId(process);
            final Calendar calendar = Calendar.getInstance(UTC);
            calendar.add(Calendar.SECOND, jobRequest.getTimeout().orElse(JobRequest.DEFAULT_TIMEOUT_DURATION));
            final JobExecution jobExecution = new JobExecution.Builder(this.hostname).withId(jobId)
                    .withProcessId(processId).withCheckDelay(jobExecEnv.getCommand().getCheckDelay())
                    .withTimeout(calendar.getTime()).withMemory(jobExecEnv.getMemory()).build();
            context.put(JobConstants.JOB_EXECUTION_DTO_KEY, jobExecution);
        } catch (final IOException ie) {
            throw new GenieServerException("Unable to start command " + String.valueOf(command), ie);
        }
        log.info("Finished Job Kickoff Task for job {}", jobId);
    } finally {
        final long finish = System.nanoTime();
        this.timer.record(finish - start, TimeUnit.NANOSECONDS);
    }
}