Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java

/**
 * This API is used to process uploaded file .
 * //from  w ww.  ja va 2 s  .c om
 * @param upload {@link ServletFileUpload} uploaded file.
 * @param req {@link HttpServletRequest}.
 * @param printWriter {@link PrintWriter}.
 * @param parentDirPath {@link String} to copy the file in directory path.
 * @return {@link File} temporary file after copy.
 */
private String processUploadedFile(final ServletFileUpload upload, final HttpServletRequest req,
        final PrintWriter printWriter, final String parentDirPath) {
    String tableFileName = "";
    String tablePathname = "";
    File tempTableFile = null;
    List<FileItem> items;

    try {
        items = upload.parseRequest(req);
        for (final FileItem item : items) {

            if (!item.isFormField()) {// && "importFile".equals(item.getFieldName())) {
                tablePathname = getTablePath(item, parentDirPath);

                tableFileName = getTableFileName(item);

                tempTableFile = copyItemContentInFile(item, tablePathname, printWriter);

            }
        }
    } catch (final FileUploadException e) {
        printWriter.write("Unable to read the form contents.Please try again.");
    }

    return tempTableFile.getAbsolutePath();
}

From source file:com.photon.maven.plugins.android.AbstractEmulatorMojo.java

/**
 * Sends a user command to the running emulator via its telnet interface.
 *
 * @param port The emulator's telnet port.
 * @param command The command to execute on the emulator's telnet interface.
 * @return Whether sending the command succeeded.
 *///from w  w w  . j  ava  2s .c  o m
private boolean sendEmulatorCommand(
        //final Launcher launcher, 
        //final PrintStream logger,
        final int port, final String command) {
    Callable<Boolean> task = new Callable<Boolean>() {
        public Boolean call() throws IOException {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = 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) {
                    return false;
                }

                out.write(command);
                out.write("\r\n");
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // Do nothing
                }
            }

            return true;
        }

        private static final long serialVersionUID = 1L;
    };

    boolean result = false;
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(task);
        result = future.get();
    } catch (Exception e) {
        getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e));
    }

    return result;
}

From source file:com.sshdemo.common.report.manage.web.ParameterSetAction.java

private void buildText() {
    PrintWriter pw = null;
    InputStream in = null;//from   ww  w . j  av  a2 s. c o  m
    try {
        TextReport report = reportFac.findTextReportById(reportId);
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();

        pw = response.getWriter();
        response.reset();// 
        response.setContentLength(0);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        byte[] bytes = textFactory.export(paraMap, report, fileFormat, response, request);
        in = new ByteArrayInputStream(bytes);
        int len = 0;
        while ((len = in.read()) > -1) {
            pw.write(len);
        }
        pw.flush();
    } catch (Exception e) {
        // log.error(e.toString());
    } finally {
        if (pw != null) {
            try {
                pw.close();
                pw = null;
            } catch (Exception e) {
            }
        }
        if (in != null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
            }
        }
    }
}

From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java

public void writeJSONResponse(HttpServletResponse response, JSONObject obj) {
    PrintWriter writer = null;
    try {//  www  .j a  v a2  s. c o m
        //IE???text/html?
        response.setContentType("text/html");
        writer = response.getWriter();
        writer.write(obj.toString());
    } catch (IOException e) {
        LOG.error("JSONHelper write json object IOException:" + e.getMessage());
        LOG.debug(e.getStackTrace());
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}

From source file:org.ala.spatial.web.services.GDMWSController.java

private String generateSpeciesFile(String outputdir, String speciesdata) {
    try {//from  w  w w  .  ja  va 2  s. c om

        File fDir = new File(outputdir);
        fDir.mkdir();

        File spFile = new File(fDir, "species_points.csv");
        PrintWriter spWriter = new PrintWriter(new BufferedWriter(new FileWriter(spFile)));

        spWriter.write(speciesdata);
        spWriter.close();

        return spFile.getAbsolutePath();

    } catch (Exception e) {
        System.out.println("error generating species file");
        e.printStackTrace(System.out);
    }

    return null;
}

From source file:csg.files.CSGFiles.java

public void saveRecitationData(AppDataComponent recData, String filePath) throws IOException {

    RecitationData recDataManager = (RecitationData) recData;
    JsonArrayBuilder recArrayBuilder = Json.createArrayBuilder();
    ObservableList<Recitation> recitations = recDataManager.getRecitations();

    for (Recitation recitation : recitations) {
        JsonObject recitationJson = Json.createObjectBuilder().add(JSON_SECTION, recitation.getSection())
                .add(JSON_INSTRUCTOR, recitation.getInstructor()).add(JSON_DAYTIME, recitation.getDayTime())
                .add(JSON_LOCATION, recitation.getLocation()).add(JSON_FIRSTTA, recitation.getFirstTA())
                .add(JSON_SECONDTA, recitation.getSecondTA()).build();
        recArrayBuilder.add(recitationJson);
    }/*from   w  w  w  .ja  v a  2 s. com*/
    JsonArray recitaitonArray = recArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_RECITATION, recitaitonArray).build();

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:de.ifgi.lodum.sparqlfly.SparqlFly.java

/**
 * Entry point for the server, handles all incoming requests. 
 *///from w  w w  . ja v  a  2s . com
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    this.logger = LoggerFactory.getLogger(SparqlFly.class);

    //handle all static file requests
    if (request.getRequestURI().startsWith("/files"))
        return;

    //prepare html templates
    header.setAttribute("baseURL", getRequestBaseURL(request));

    PrintWriter writer = response.getWriter();
    accept = new SparqlAcceptHeader(request);

    // change post requests to get requests
    if (request.getMethod().equals("POST")) {
        try {
            response.sendRedirect(getRequestBaseURL(request) + request.getParameter("query")
                    + request.getParameter("accept"));
        } catch (Exception e) {
            logger.error(e.toString());
            error.setAttribute("error", escapeHtml3(e.toString()));
            writer.write(header.toString() + error.toString() + footer.toString());
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    } else {
        if (request.getParameter("query") != null) {
            try {
                executeQuery(request.getParameter("query"), baseRequest, request, writer, response);
            } catch (Exception e) {
                response.setContentType("text/html");
                logger.error(e.toString());
                error.setAttribute("error", escapeHtml3(e.toString()));
                writer.write(header.toString() + error.toString() + footer.toString());
            }
        } else if (request.getParameter("queryString") != null) {
            response.setContentType("text/html");
            form.setAttribute("query",
                    URLDecoder.decode(request.getParameter("queryString").replace("+", "%2B"), "UTF-8")
                            .replace("%2B", "+"));
            writer.write(header.toString() + form.toString() + footer.toString());
            form.reset();
        } else if (request.getParameter("queryFrom") != null) {
            response.setContentType("text/html");
            Model m = null;
            try {
                m = getModelFromURL(request.getParameter("queryFrom"),
                        getFormat(request.getParameter("queryFrom")));
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (!m.isEmpty()) {
                try {
                    String q = "";
                    for (Entry<String, String> pre : m.getNsPrefixMap().entrySet()) {
                        if (!pre.getKey().contains("j."))
                            q += "PREFIX " + pre.getKey() + ": <" + pre.getValue() + ">\n";
                    }
                    q += "\nSELECT * \nFROM <" + request.getParameter("queryFrom") + ">\n"
                            + "WHERE {\n?a ?b ?c\n} LIMIT 10";
                    form.setAttribute("query", q);
                    writer.write(header.toString() + form.toString() + footer.toString());
                    form.reset();
                } catch (Exception e) {
                    logger.error(e.toString());
                    error.setAttribute("error", e.toString());
                    writer.write(header.toString() + error.toString() + footer.toString());
                }
            }
        } else {
            response.setContentType("text/html");
            form.setAttribute("query", defaultQuery.toString());
            writer.write(header.toString() + form.toString() + footer.toString());
            form.reset();
            header.reset();
        }
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
    }
}

From source file:csg.files.CSGFiles.java

public void saveTAData(AppDataComponent data, String filePath) throws IOException {
    TAData dataManager = (TAData) data;/*  w w w .  ja  v  a2s .co  m*/

    // NOW BUILD THE TA JSON OBJCTS TO SAVE
    JsonArrayBuilder taArrayBuilder = Json.createArrayBuilder();
    ObservableList<TeachingAssistant> tas = dataManager.getTeachingAssistants();
    for (TeachingAssistant ta : tas) {
        JsonObject taJson = Json.createObjectBuilder().add(JSON_NAME, ta.getName())
                .add(JSON_EMAIL, ta.getEmail()).add(JSON_UG, ta.isUndergrad().get()).build();
        taArrayBuilder.add(taJson);
    }
    JsonArray undergradTAsArray = taArrayBuilder.build();

    // NOW BUILD THE TIME SLOT JSON OBJCTS TO SAVE
    JsonArrayBuilder timeSlotArrayBuilder = Json.createArrayBuilder();
    ArrayList<TimeSlot> officeHours = TimeSlot.buildOfficeHoursList(dataManager);
    for (TimeSlot ts : officeHours) {
        JsonObject tsJson = Json.createObjectBuilder().add(JSON_DAY, ts.getDay()).add(JSON_TIME, ts.getTime())
                .add(JSON_NAME, ts.getName()).build();
        timeSlotArrayBuilder.add(tsJson);
    }
    JsonArray timeSlotsArray = timeSlotArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_START_HOUR, "" + dataManager.getStartHour())
            .add(JSON_END_HOUR, "" + dataManager.getEndHour()).add(JSON_UNDERGRAD_TAS, undergradTAsArray)
            .add(JSON_OFFICE_HOURS, timeSlotsArray).build();

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java

/**
 * This API is used to process uploaded file and unzip file in export-batch-folder .
 * //  w  ww.  j  a v a  2 s .c  o m
 * @param upload {@link ServletFileUpload} uploaded file.
 * @param req {@link HttpServletRequest}.
 * @param printWriter {@link PrintWriter}.
 * @param parentDirPath {@link String} to create absolute unzip directory path.
 * @return {@link File} temporary file after unzip.
 */
private String processUploadedFile(final ServletFileUpload upload, final HttpServletRequest req,
        final PrintWriter printWriter, final String parentDirPath) {
    String tempUnZipDir = "";
    String zipFileName = "";
    String zipPathname = "";
    File tempZipFile = null;
    List<FileItem> items;

    try {
        items = upload.parseRequest(req);
        for (final FileItem item : items) {

            if (!item.isFormField()) {// && "importFile".equals(item.getFieldName())) {
                zipPathname = getZipPath(item, parentDirPath);

                zipFileName = getZipFileName(item);

                tempZipFile = copyItemContentInFile(item, zipPathname, printWriter);

            }
        }
    } catch (final FileUploadException e) {
        printWriter.write("Unable to read the form contents.Please try again.");
    }

    tempUnZipDir = parentDirPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.'))
            + System.nanoTime();

    try {
        FileUtils.unzip(tempZipFile, tempUnZipDir);
    } catch (final Exception e) {
        printWriter.write("Unable to unzip the file.Please try again.");
        tempZipFile.delete();
    }
    return tempUnZipDir;
}

From source file:csg.files.CSGFiles.java

public void saveTeamsAndStudentsData(AppDataComponent projectData, String filePath) throws IOException {
    ProjectData projectDataManager = (ProjectData) projectData;
    JsonArrayBuilder teamArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder studentArrayBuilder = Json.createArrayBuilder();
    ObservableList<Team> teams = projectDataManager.getTeams();
    ObservableList<Student> students = projectDataManager.getStudents();

    for (Team team : teams) {
        JsonObject teamsJson = Json.createObjectBuilder().add(JSON_NAME, team.getName())
                .add(JSON_RED, (Integer.parseInt(team.getColor().toString().substring(0, 2), 16)))
                .add(JSON_GREEN, (Integer.parseInt(team.getColor().toString().substring(2, 4), 16)))
                .add(JSON_BLUE, (Integer.parseInt(team.getColor().toString().substring(4, 6), 16)))
                .add(JSON_TEXTCOLOR, "#" + team.getTextColor()).build();
        teamArrayBuilder.add(teamsJson);
    }/*from w  w w  .  ja  v  a  2 s  .  co m*/
    JsonArray teamArray = teamArrayBuilder.build();

    for (Student student : students) {
        JsonObject studentsJson = Json.createObjectBuilder().add(JSON_LASTNAME, student.getLastName())
                .add(JSON_FIRSTNAME, student.getFirstName()).add(JSON_TEAM, student.getTeam())
                .add(JSON_ROLE, student.getRole()).build();
        studentArrayBuilder.add(studentsJson);
    }
    JsonArray studentArray = studentArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_TEAMS, teamArray)
            .add(JSON_STUDENTS, studentArray).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}