Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:com.poscoict.license.web.controller.PhotoUploadController.java

@RequestMapping(value = { "PhotoUploadHTML5" }, method = { RequestMethod.POST })
public void PhotoUploadHTML5(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {//w w  w . java 2s .c  om
        System.out.println("________PhotoUploadHTML5");
        //?
        String sFileInfo = "";
        String filename = request.getHeader("file-name");
        String filename_ext = filename.substring(filename.lastIndexOf(".") + 1);
        filename_ext = filename_ext.toLowerCase();

        String[] allow_file = { "jpg", "png", "bmp", "gif" };

        int cnt = 0;
        for (int i = 0; i < allow_file.length; i++) {
            if (filename_ext.equals(allow_file[i])) {
                cnt++;
            }
        }

        if (cnt == 0) {
            PrintWriter print = response.getWriter();
            print.print("NOTALLOW_" + filename);
            print.flush();
            print.close();
        } else {
            String dftFilePath = request.getSession().getServletContext().getRealPath("/");
            String folderPath = new SimpleDateFormat("yyyyMMdd").format(new java.util.Date());
            String filePath = dftFilePath + "editor" + File.separator + "multiupload" + File.separator
                    + folderPath + File.separator;
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            String realFileNm = "";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String today = formatter.format(new java.util.Date());
            realFileNm = today + UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
            String rlFileNm = filePath + realFileNm;

            InputStream is = request.getInputStream();
            OutputStream os = new FileOutputStream(rlFileNm);
            int numRead;
            byte b[] = new byte[Integer.parseInt(request.getHeader("file-size"))];
            while ((numRead = is.read(b, 0, b.length)) != -1) {
                os.write(b, 0, numRead);
            }
            if (is != null) {
                is.close();
            }
            os.flush();
            os.close();

            //backup
            file = new File(backupFolderHTML5 + folderPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileCopy(rlFileNm, backupFolderHTML5 + folderPath + File.separator + realFileNm);
            System.out.println("___________rlFileNm: " + rlFileNm);
            System.out.println("____________backupFolderHTML5: " + backupFolderHTML5 + folderPath
                    + File.separator + realFileNm);

            String serverPath = request.getContextPath();
            sFileInfo += "&bNewLine=true";
            sFileInfo += "&sFileName=" + filename;
            sFileInfo += "&sFileURL=" + serverPath + "/editor/multiupload/" + folderPath + "/" + realFileNm;
            PrintWriter print = response.getWriter();
            print.print(sFileInfo);
            print.flush();
            print.close();
        }
    } catch (Exception e) {
        e.getStackTrace();
    }
}

From source file:adminpackage.adminview.ProductAddition.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/plain;charset=UTF-8");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    AdminViewProduct product = new AdminViewProduct();
    List<FileItem> items = upload.parseRequest(request);
    Iterator itr = items.iterator();
    String value = "defa";
    String url = "";
    while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
            String name = item.getFieldName();
            value = item.getString();//  w  w w.  ja  v a  2 s. c o m
            switch (name) {
            case "pname":
                product.setName(value);
                break;
            case "quantity":
                product.setQuantity(Integer.parseInt(value));
                break;
            case "author":
                product.setAuthor(value);
                break;
            case "isbn":
                product.setISBN(Long.parseLong(value));
                break;
            case "description":
                product.setDescription(value);
                break;
            case "category":
                product.setCategory(value);
                break;
            case "price":
                product.setPrice(Integer.parseInt(value));
                break;
            }
        } else {

            //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName());
            //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName();
            UUID idOne = UUID.randomUUID();
            product.setImage(idOne.toString() + item.getName().substring(item.getName().length() - 4));
            item.write(new File(context.getRealPath("/pages/images/")
                    .replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp")
                    + idOne.toString() + item.getName().substring(item.getName().length() - 4)));
        }
    }

    PrintWriter out = response.getWriter();

    if (adminFacadeHandler.addBook(product)) {
        out.print("true");
    } else {
        //out.println("false");
        out.print("false");
    }
}

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request/*from  ww  w  . ja v  a2  s.c o  m*/
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        String serverUrl = request.getHeader("serverUrl");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = new PostMethod(serverUrl);

            // Transfer bytes from in to out
            log.info("HTTP POST transfering..." + serverUrl);
            String body = inputStreamAsString(request.getInputStream());

            HttpClient client = new HttpClient();

            httppost.setRequestBody(body);
            if (0 == httppost.getParameters().length) {
                log.debug("No Name/Value pairs found ... pushing as raw_post_data");
                httppost.setParameter("raw_post_data", body);
            }
            if (log.isDebugEnabled()) {
                log.debug("Body = " + body);
                NameValuePair[] nameValuePairs = httppost.getParameters();
                log.debug("NameValuePairs found: " + nameValuePairs.length);
                for (int i = 0; i < nameValuePairs.length; ++i) {
                    log.debug("parameters:" + nameValuePairs[i].toString());
                }
            }
            //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);

            client.executeMethod(httppost);
            if (log.isDebugEnabled()) {
                Header[] respHeaders = httppost.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                response.setContentType("text/xml");
                String responseBody = httppost.getResponseBodyAsString();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
            } else {
                log.error("Unexpected failure: " + httppost.getStatusLine().toString());
            }
            httppost.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:ca.nrc.cadc.caom2.pkg.TarWriter.java

public void close() throws IOException {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, List<TarContent>> me : map.entrySet()) {
        for (TarContent tc : me.getValue()) {
            if (tc.emsg != null)
                sb.append("ERROR ").append(tc.emsg);
            else/*from  w  w  w.ja v  a2s .  co m*/
                sb.append("OK ").append(tc.filename).append(" ").append(tc.contentMD5).append(" ")
                        .append(tc.url);
            sb.append("\n");
        }
        boolean openEntry = false;
        try {
            String filename = me.getKey() + "/README";
            tout.putArchiveEntry(new DynamicTarEntry(filename, sb.length(), new Date()));
            openEntry = true;
            PrintWriter pw = new PrintWriter(new TarStreamWrapper(tout));
            pw.print(sb.toString());
            pw.flush();
            pw.close(); // safe
        } finally {
            if (openEntry)
                tout.closeArchiveEntry();
        }
    }

    tout.finish();
    tout.close();
}

From source file:com.portfolio.data.attachment.ConvertCSV.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try {//w ww  .j  a v a  2  s .c o  m
            request.getInputStream().close();
            response.setStatus(417);
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    initialize(request);
    response.setContentType("application/json");

    JSONObject data = new JSONObject();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        List<String[]> meta = new ArrayList<String[]>();
        List<List<String[]>> linesData = new ArrayList<List<String[]>>();

        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                if ("uploadfile".equals(fieldname)) // name="uploadfile"
                {
                    InputStreamReader isr = new InputStreamReader(item.getInputStream());
                    CSVReader reader = new CSVReader(isr, ';');
                    String[] headerLine;
                    String[] dataLine;

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    dataLine = reader.readNext();
                    if (dataLine == null)
                        break;

                    for (int i = 0; i < headerLine.length; ++i) {
                        data.put(headerLine[i], dataLine[i]);
                    }

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    JSONArray lines = new JSONArray();
                    while ((dataLine = reader.readNext()) != null) {
                        JSONObject lineInfo = new JSONObject();
                        for (int i = 0; i < headerLine.length; ++i) {
                            lineInfo.put(headerLine[i], dataLine[i]);
                        }
                        lines.put(lineInfo);
                    }

                    data.put("lines", lines);

                    isr.close();
                }
            }
        }
    } catch (Exception e) {

    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
        out.print(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }

}

From source file:org.simbasecurity.core.service.http.DBViewer.java

private void printForm(PrintWriter out, String uri, String selectedTable, boolean asSQL, String query) {
    out.print("<form action='");
    out.print(uri);/* www . ja va  2  s .  co  m*/
    out.println("' method='post'>");

    out.println("<select name='table' onchange='this.form.submit()'>");
    out.println("<option value=''></option>");
    List<String> tables = getDBTables();
    for (String table : tables) {
        out.print("<option value='");
        out.print(table);
        out.print("'");
        if (table.equals(selectedTable)) {
            out.print(" selected");
        }
        out.print(">");
        out.print(table);
        out.println("</option>");
    }

    out.println("</select>");
    out.println("<input name='asSQL' type='checkbox' onchange='this.form.submit()' " + (asSQL ? " checked" : "")
            + ">As SQL?</input>");
    out.println("<br/>");
    out.println("<input type='submit' value='Refresh' />");
    out.println("</form>");

    out.println("<br/>");

    out.print("<form action='");
    out.print(uri);
    out.println("' method='post'>");
    out.print("<textarea name='query' type='textarea' cols='120' rows='5'>");
    if (query != null) {
        out.print(query);
    }
    out.println("</textarea>");
    out.println("<br/>");
    out.println("<input type='submit' value='Execute Query' />");
    out.println("</form>");
}

From source file:com.google.appinventor.server.GalleryServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    setDefaultHeader(resp);//  w ww  .  j  a  v a 2  s.  c om
    UploadResponse uploadResponse;

    String uri = req.getRequestURI();
    // First, call split with no limit parameter.
    String[] uriComponents = uri.split("/");

    if (true) {
        String requestType = uriComponents[REQUEST_TYPE_INDEX];
        LOG.info("######### GOT IN URI");
        LOG.info(requestType);

        long project_Id = -1;
        String user_Id = "-1";
        if (requestType.equalsIgnoreCase("apps")) {
            project_Id = Long.parseLong(uriComponents[GALLERY_OR_USER_ID_INDEX]);
        } else if (requestType.equalsIgnoreCase("user")) {
            //the code below doesn't check if user_Id is the id of current user
            //user_Id = uriComponents[GALLERY_OR_USER_ID_INDEX];
            user_Id = userInfoProvider.getUserId();
        }
        InputStream uploadedStream;
        try {
            if (req.getContentLength() < MAX_IMAGE_FILE_SIZE) {
                uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT);

                // Converts the input stream to byte array
                byte[] buffer = new byte[8000];
                int bytesRead = 0;
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                while ((bytesRead = uploadedStream.read(buffer)) != -1) {
                    bao.write(buffer, 0, bytesRead);
                }
                // Set up the cloud file (options)
                String key = "";
                GallerySettings settings = galleryService.loadGallerySettings();
                if (requestType.equalsIgnoreCase("apps")) {
                    key = settings.getProjectImageKey(project_Id);
                } else if (requestType.equalsIgnoreCase("user")) {
                    key = settings.getUserImageKey(user_Id);
                }

                // setup cloud
                GcsService gcsService = GcsServiceFactory.createGcsService();
                GcsFilename filename = new GcsFilename(settings.getBucket(), key);
                GcsFileOptions options = new GcsFileOptions.Builder().mimeType("image/jpeg").acl("public-read")
                        .cacheControl("no-cache").build();
                GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options);
                writeChannel.write(ByteBuffer.wrap(bao.toByteArray()));

                // Now finalize
                writeChannel.close();

                uploadResponse = new UploadResponse(UploadResponse.Status.SUCCESS);
            } else {
                /*file exceeds size of MAX_IMAGE_FILE_SIZE*/
                uploadResponse = new UploadResponse(UploadResponse.Status.FILE_TOO_LARGE);
            }

            // Now, get the PrintWriter for the servlet response and print the UploadResponse.
            // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
            // UploadResponse value will be retrieved as a String via the
            // FormSubmitCompleteEvent.getResults() method.
            PrintWriter out = resp.getWriter();
            out.print(uploadResponse.formatAsHtml());

        } catch (Exception e) {
            throw CrashReport.createAndLogError(LOG, req, null, e);
        }
        // Set http response information
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    // Now, get the PrintWriter for the servlet response and print the UploadResponse.
    // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
    // UploadResponse value will be retrieved as a String via the
    // FormSubmitCompleteEvent.getResults() method.
    //    PrintWriter out = resp.getWriter();
    //    out.print(uploadResponse.formatAsHtml());

    // Set http response information
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:de.viaboxx.nlstools.formats.BundleWriterFlexClass.java

/**
 * Write the static beginning of the interface file.
 *
 * @param pw writer to write to//w  w  w  . j a v a 2 s  .c  o  m
 */
void writeStaticIntro(PrintWriter pw) {
    String str = getIPackage();
    if (str != null && str.length() > 0) {
        pw.print("package ");
        pw.print(str);
        pw.println("{");
    }
    pw.println();
    writeDoNotAlter(pw);
    pw.print("public class ");
    pw.print(getIClass());
    pw.println(" {");
    pw.print("  public static const _BUNDLE_NAME:String = \"");
    pw.print(currentBundle.getBaseName());
    pw.println("\";");
    pw.println();
}

From source file:de.viaboxx.nlstools.formats.BundleWriterJavaInterface.java

protected void writeDoNotAlter(PrintWriter pw) {
    pw.println("/**");//from  ww  w .java2  s . c  o m
    pw.print(" * contains keys of resource bundle ");
    pw.print(currentBundle.getBaseName());
    pw.println('.');
    pw.println(" * THIS FILE HAS BEEN GENERATED AUTOMATICALLY - DO NOT ALTER!");
    pw.println(" */");
}

From source file:com.healthcit.analytics.servlet.DataExportServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType(Constants.PLAIN_TEXT);
    resp.addHeader(Constants.PRAGMA_HEADER, Constants.NO_CACHE);
    resp.setHeader(Constants.CACHE_CONTROL_HEADER, Constants.NO_CACHE);
    String token = req.getParameter("token");
    PrintWriter writer = resp.getWriter();
    try {//from   ww  w .  j  a v a  2  s .co  m
        if (token != null) {
            DownloadStatus status = TOKENS_MAP.get(token);
            if (status != null) {
                writer.print(status.name());
                if (DownloadStatus.FINISHED.equals(status)) {
                    TOKENS_MAP.remove(token);
                }
            } else {
                writer.print(DownloadStatus.ERROR.name());
            }
        } else {
            writer.print(DownloadStatus.ERROR.name());
        }
    } finally {
        writer.close();
    }
}