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.jsmartframework.web.manager.WebContext.java

/**
 * Write response directly as JSON from Object. Note that by using this method the response
 * as HTML will not be generated and the response will be what you have defined.
 *
 * @param object Object to convert into JSON to write in the response.
 * @param gson Gson instance to be used to convert object into JSON.
 * @throws IOException//from   w ww.  j a v a  2  s.  c  om
 */
public static void writeResponseAsJson(Object object, Gson gson) throws IOException {
    WebContext context = getCurrentInstance();
    if (context != null) {
        context.responseWritten = true;
        context.response.setContentType("application/json");
        PrintWriter writer = context.response.getWriter();
        writer.write(gson.toJson(object));
        writer.flush();
    }
}

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

/**
 * Write response directly as XML from Object. Note that by using this method the response
 * as HTML will not be generated and the response will be what you have defined.
 *
 * @param object Object to convert into XML to write in the response.
 * @param marshaller JAXBContext marshaller to write object as XML.
 * @throws IOException//from w  w  w .j  a  va  2  s . c  om
 */
public static void writeResponseAsXml(Object object, Marshaller marshaller) throws IOException, JAXBException {
    WebContext context = getCurrentInstance();
    if (context != null) {
        context.responseWritten = true;
        context.response.setContentType("application/xml");
        PrintWriter writer = context.response.getWriter();
        marshaller.marshal(object, writer);
        writer.flush();
    }
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

/**
 * Writes the class information as <a href="http://databionic-esom.sourceforge.net/user.html#File_formats">ESOM
 * cls</a> file./*  w  ww . j  a va  2 s.  c  o m*/
 */
public static void writeAsESOM(SOMLibClassInformation classInfo, String fileName)
        throws IOException, SOMLibFileFormatException {
    PrintWriter writer = FileUtils.openFileForWriting("ESOM class info", fileName);
    writer.println("% " + classInfo.numData);
    // write class index => class name mapping in header
    for (int i = 0; i < classInfo.numClasses(); i++) {
        writer.println("% " + i + " " + classInfo.getClassName(i));
    }
    for (String element : classInfo.getDataNames()) {
        writer.println(element + "\t" + classInfo.getClassIndexForInput(element));
    }
    writer.flush();
    writer.close();
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicProperties.java

/**
 * If the regex file do not exists, build it using the passed configuration and return the
 * corresponding properties object/*from  www. j av  a2s.c  o  m*/
 * 
 * @param regexFile
 * @param configuration
 * @return
 * @throws NullPointerException
 * @throws IOException 
 */
private static Properties createRegexFile(File regexFile, String regex)
        throws NullPointerException, IOException {

    if (!regexFile.exists()) {
        FileWriter outFile = null;
        PrintWriter out = null;
        if (regex != null) {
            try {
                outFile = new FileWriter(regexFile);
                out = new PrintWriter(outFile);

                // Write text to file
                out.println("regex=" + regex);
            } catch (IOException e) {
                if (LOGGER.isErrorEnabled())
                    LOGGER.error("Error occurred while writing " + regexFile.getAbsolutePath() + " file!", e);
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }

                outFile = null;
                out = null;
            }
        } else
            throw new NullPointerException("Unable to build the property file using a null regex string");

        return getPropertyFile(regexFile);
    }
    return null;
}

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Writes a text String into a file//from  ww  w .j a v  a  2s . c  om
 * 
 * @param contentString
 *        The String to be written into the file
 * @param filename
 *        The name of the file
 * @param append
 *        If true the data are appended to existent file
 * @throws IOException
 */
public static void writeFile(String contentString, String filename, boolean append) throws IOException {
    PrintWriter out = null;
    try {
        filename = adjustPath(filename);
        out = new PrintWriter(new FileWriter(filename, append));
        out.print(contentString);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Writes a XML response to the client. 
 * The message must be a text which will be wrapped in an XML structure.
 * //  w w w .j  a  va 2s  .co  m
 * Note: if the request is a POST, the response should set the content type 
 *  to text/html or text/plain in order to be able in the client side to
 *  read the iframe body (submitCompletEvent.getResults()), otherwise the
 *  method returns null 
 * 
 * @param request
 * @param response
 * @param message
 * @param post
 *        specify whether the request is post or not.   
 * @throws IOException
 */
protected static void renderXmlResponse(HttpServletRequest request, HttpServletResponse response,
        String message, boolean post) throws IOException {

    //json????

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out;
    try {
        out = response.getWriter();
        out.write("<html><body><textarea>" + message + "</textarea></body></html>");
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.iitb.cse.Utils.java

public static boolean startExperiment(int expId, String timeout, String logBgTraffic) {

    File file = null;/* www. ja v a2  s  .  c o  m*/
    File file1 = null;

    if (Constants.experimentDetailsDirectory.endsWith("/")) {
        file = new File(Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()
                + "/" + Constants.configFile);
        file1 = new File(
                Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId());
    } else {
        file = new File(Constants.experimentDetailsDirectory + "/"
                + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile);
        file1 = new File(
                Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId());
    }

    if (file.exists()) {
        Charset charset = Charset.forName("UTF-8");
        String line = null;

        String[] data = new String[1000];//
        int index = 0;
        data[index] = "";
        try {
            BufferedReader reader = Files.newBufferedReader(file.toPath(), charset);
            Calendar cal = Calendar.getInstance();
            while ((line = reader.readLine()) != null) {

                System.out.println("\nLENGTH : " + line.length());

                if (line.isEmpty() || line.trim().equals("")) {
                    System.out.println("\nCASE1");
                    continue;
                } else if (line.trim().equals("*****\n")) {
                    System.out.println("\nCASE2");
                    data[index] = expId + "\n" + data[index];
                    index++;
                    data[index] = "";
                    continue;
                } else if (line.trim().equals("*****")) {
                    System.out.println("\nCASE3");
                    data[index] = expId + "\n" + data[index];
                    index++;
                    data[index] = "";
                    continue;
                }

                String[] lineVariables = line.split(" ");

                //   int offset = Integer.parseInt(lineVariables[1]);
                //   cal.add(Calendar.SECOND, offset);
                //****************************************************
                double time = Double.parseDouble(lineVariables[1]);

                int sec = (int) time;
                double rem = time % 1;
                int remainder = (int) (rem * 1000);
                //       Calendar cal = Calendar.getInstance();
                //   System.out.println("\nSec : " + sec + "\nMiSec : " + remainder + "\nTime : " + cal.getTime());
                int flag = 0;
                if (remainder < 100) {
                    flag = 1;
                    remainder = remainder + 100;
                    cal.add(Calendar.SECOND, sec);
                    cal.add(Calendar.MILLISECOND, remainder);
                    cal.add(Calendar.MILLISECOND, -100);
                } else {
                    cal.add(Calendar.SECOND, sec);
                    cal.add(Calendar.MILLISECOND, remainder);
                }

                //****************************************************
                if (lineVariables.length == 5) {
                    //       System.out.println("\nINSIDE");
                    data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3],
                            lineVariables[4]);
                } else {
                    //    System.out.println("\nOUTSIDE");
                    data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3]);
                }

                if (flag == 1) {
                    cal.add(Calendar.SECOND, -1 * sec);
                    cal.add(Calendar.MILLISECOND, -1 * remainder);
                    cal.add(Calendar.MILLISECOND, 100);
                } else {
                    cal.add(Calendar.SECOND, -1 * sec);
                    cal.add(Calendar.MILLISECOND, -1 * remainder);
                }

            }

            data[index] = expId + "\n" + data[index];

        } catch (IOException ex) {
            System.out.println(ex.toString());
            return false;
        }

        int controlFileIndex = 0;
        for (DeviceInfo d : Constants.currentSession.getFilteredClients()) {

            if (controlFileIndex >= Constants.currentSession.getFilteredClients().size()) {
                break;
            } else if (data[controlFileIndex] != null) {

                String jsonString = Utils.getControlFileJson(data[controlFileIndex], timeout, logBgTraffic);
                System.out.println("\njsonString : " + jsonString);
                System.out.println("\nControl FIle : " + data[controlFileIndex]);

                /* Locally keep the corresponding control file to each client*/
                PrintWriter writer;
                try {
                    writer = new PrintWriter(file1 + "/" + d.macAddress + "_confFile");
                    writer.write(data[controlFileIndex]);
                    writer.flush();
                    writer.close();
                } catch (FileNotFoundException ex) {
                    System.out.println("\nException : " + ex.toString());
                }

                //writer.close();
                System.out.println("\nDevice Info : IP " + d.ip + " Port " + d.port + " Mac " + d.macAddress);
                Thread sendData = new Thread(new SendData(expId, d, 0, jsonString, data[controlFileIndex]));
                sendData.start();
            } else {
                break;
            }
            controlFileIndex++;
        }
    } else {
        System.out.println("\nConfig FIle not found in location : " + Constants.experimentDetailsDirectory
                + Constants.currentSession.getCurrentExperimentId());
    }

    return true;
}

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Writes a text String into a file/*from  w w w  .j  a  v a  2s .c om*/
 * 
 * @param contentString
 *        The StringBuffer to be written into the file
 * @param filename
 *        The name of the file
 * @param append
 *        If true the data are appended to existent file
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public static void writeFile(StringBuffer contentString, String filename, boolean append) throws IOException {
    PrintWriter out = null;
    try {
        filename = adjustPath(filename);
        out = new PrintWriter(new FileWriter(filename, append));
        IOUtils.write(contentString, out);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

/** Writes the class information to a file in SOMLib format. */
public static void writeAsSOMLib(HashMap<String, String> classInfo, HashSet<String> classNames, String fileName)
        throws IOException, SOMLibFileFormatException {
    ArrayList<String> classNamesList = new ArrayList<String>(classNames);
    Collections.sort(classNamesList);

    PrintWriter writer = FileUtils.openFileForWriting("SOMLib class info", fileName);
    writer.println("$TYPE class_information");

    writer.println("$NUM_CLASSES " + classNames.size());
    writer.println("$CLASS_NAMES " + StringUtils.toString(classNamesList, "", "", " "));
    writer.println("$XDIM 2");
    writer.println("$YDIM " + classInfo.size());
    for (String key : classInfo.keySet()) {
        writer.println(key + " " + classNamesList.indexOf(classInfo.get(key)));
    }/*from w ww . j ava  2s  . co m*/

    writer.flush();
    writer.close();
}

From source file:io.selendroid.android.impl.DefaultAndroidEmulator.java

private static Map<String, Integer> mapDeviceNamesToSerial() {
    Map<String, Integer> mapping = new HashMap<String, Integer>();
    CommandLine command = new CommandLine(AndroidSdk.adb());
    command.addArgument("devices");
    Scanner scanner;/*from  ww w .j  a v a2  s. c o m*/
    try {
        scanner = new Scanner(ShellCommand.exec(command));
    } catch (ShellCommandException e) {
        return mapping;
    }
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            String serial = matcher.group(0);

            Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
            TelnetClient client = null;
            try {
                client = new TelnetClient(port);
                String avdName = client.sendCommand("avd name");
                mapping.put(avdName, port);
            } catch (AndroidDeviceException e) {
                // ignore
            } finally {
                if (client != null) {
                    client.close();
                }
            }
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    throw new AndroidDeviceException("error");
                }

                out.write("avd name\r\n");
                out.flush();
                in.readLine();// OK
                String avdName = in.readLine();
                mapping.put(avdName, port);
            } catch (Exception e) {
                // ignore
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }
    scanner.close();

    return mapping;
}