Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

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

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:photosharing.api.conx.UploadFileDefinition.java

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * // w  w w.  j ava  2s . co  m
 * @param bearer token
 * @param nonce 
 * @param request
 * @param response
 */
public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) {

    // Extracts from the Request Parameters
    String visibility = request.getParameter("visibility");
    String title = request.getParameter("title");
    String share = request.getParameter("share");
    String tagsUnsplit = request.getParameter("q");

    // Check for the Required Parameters
    if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);

    } else {

        /*
         * Builds the URL Parameters 
         */
        StringBuilder builder = new StringBuilder();
        builder.append("visibility=" + visibility + "&");
        builder.append("title=" + title + "&");

        // The Share parameters for the URL
        if (share != null && !share.isEmpty()) {
            builder.append("shared=true&");
            builder.append("shareWith=" + share + "&");
        }

        if (visibility.compareTo("private") == 0 && share == null) {
            builder.append("shared=false&");
        }

        // Splits the TagString into Indvidual Tags
        // - Technically this API is limited to 3 tags at most. 
        String[] tags = tagsUnsplit.split(",");
        for (String tag : tags) {
            logger.info("Tag-> " + tag);
            builder.append("tag=" + tag + "&");
        }

        // Build the apiURL
        String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString();

        //API Url
        logger.info(apiUrl);

        // Add the Headers
        String length = request.getHeader("X-Content-Length");
        String contentType = request.getHeader("Content-Type");
        String fileext = contentType.split("/")[1].split(";")[0];
        String slug = title + "." + fileext;

        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Slug", slug);
        post.addHeader("Content-Type", contentType);

        logger.info("Authorization: Bearer " + bearer);
        logger.info("X-Update-Nonce: " + nonce);
        logger.info("Slug: " + slug);
        logger.info("Content-Type: " + contentType);

        try {
            //
            InputStream in = request.getInputStream();
            Base64InputStream bis = new Base64InputStream(in);

            long len = Long.parseLong(length);
            InputStreamEntity entity = new InputStreamEntity(bis, len);

            post.body(entity);

            post.removeHeaders("Cookie");

            Executor exec = ExecutorUtil.getExecutor();

            Response apiResponse = exec.execute(post);
            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            logger.info("code is " + code);

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Duplicate Item
            else if (code == HttpStatus.SC_CONFLICT) {
                response.setStatus(HttpStatus.SC_CONFLICT);
            }

            // Checks if Created
            else if (code == HttpStatus.SC_CREATED) {
                response.setStatus(HttpStatus.SC_OK);
                /**
                 * Do Extra Processing Here to process the body
                 */
                InputStream inRes = hr.getEntity().getContent();

                // Converts XML to JSON String
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes);
                JSONObject obj = new JSONObject(jsonString);

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.append(obj.toString());
                writer.close();

            } else {
                // Catch All
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                InputStream inRes = hr.getEntity().getContent();
                String out = IOUtils.toString(inRes);
                logger.info("Content: " + out);
                logger.info("Content Type of Response: " + response.getContentType());

                Collection<String> coll = response.getHeaderNames();
                Iterator<String> iter = coll.iterator();

                while (iter.hasNext()) {
                    String header = iter.next();
                    logger.info(header + " " + response.getHeader(header));
                }

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("IOException " + e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("SAXException " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

            logger.severe("JSONException " + e.toString());
        }
    }
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.writer.HydrotopeWriter.java

private void writeCatchment(final PrintWriter writer, final CatchmentInfo info) {
    final Catchment catchment = info.getCatchment();
    final int catchmentAsciiID = m_idManager.getAsciiID(catchment);

    final Sealing totalSealing = info.getTotalSealing();

    final Collection<HydrotopeInfo> hydrotops = info.getHydrotops();

    writer.print(catchmentAsciiID);/*from   w  w  w.jav a  2 s.  c  om*/
    writer.append(' ');
    writer.print(hydrotops.size());
    writer.append(' ');
    writer.format(Locale.US, "%.3f %.3f %.3f", totalSealing.getSealedArea(), totalSealing.getNaturalArea(), //$NON-NLS-1$
            totalSealing.getArea());

    writer.append('\n');

    for (final HydrotopeInfo hydrotopInfo : hydrotops)
        writeHydrotope(writer, catchment, hydrotopInfo);
}

From source file:com.github.rabid_fish.proxy.servlet.SoapServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter writer = response.getWriter();

    if (request.getQueryString() != null && request.getQueryString().equals("wsdl")) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/xml");
        writeWsdl(writer);/* w w w. ja  v  a 2  s  . co  m*/
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentType("text/html");
        writer.append("404: page not found");
    }

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

From source file:foam.starwisp.NetworkManager.java

public List<String> PostFile(String requestURL, File uploadFile) throws IOException {

    // creates a unique boundary based on time stamp
    String boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);//from w ww. j a  v  a2s .  co  m
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    OutputStream outputStream = httpConn.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"binary\";" + "filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

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

    writer.append(LINE_FEED);
    writer.flush();

    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}

From source file:com.threewks.analytics.client.AnalyticsClient.java

/**
 * Post JSON a URL. Ignore (but log) any errors.
 * /*  w  w w . j  a va  2s  .c o  m*/
 * @param url the URL to post the data to.
 * @param json the JSON data to post.
 */
void postJson(String url, String json) {
    PrintWriter writer = null;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setDoOutput(true);
        connection.setRequestProperty(API_KEY_HEADER, apiKey);
        connection.setRequestProperty(CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE);
        writer = new PrintWriter(connection.getOutputStream(), true);
        writer.append(json);
        writer.close();

        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            logger.warning(String.format(
                    "Analytics server returned HTTP response code: %s when posting data to url: %s",
                    responseCode, url));
        }
    } catch (Exception e) {
        logger.warning(String.format("Error sending data to url: %s, error: %s", url, e.getMessage()));
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

/**
 * Processes requests for both HTTP//w w w.j a  v  a 2 s.  c o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    log("isMultipartContent: " + isMultiPart);
    log("Content-Type: " + request.getContentType());
    if (isMultiPart) {

        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        PrintWriter out = response.getWriter();
        out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>");

        ListIterator li = items.listIterator();
        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                processFormField(fileItem);
            } else {
                out.append(processUploadedFile(fileItem));
            }
        }
        out.print("</body></html>");
        out.flush();
        out.close();

    }
}

From source file:HttpClient1.java

/**
 * Methode to upload a data file.//from ww w.  j av a 2  s  . c om
 * 
 * @param uploadFile
 */
public void putData(File uploadFile) {
    String fileName = uploadFile.getName();
    String fieldName = "data";
    String boundary = "" + System.currentTimeMillis() + "";

    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("file", fileName);

    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    logger.info("PUT Data file on " + url);
    logger.info("Uploading Data file: " + uploadFile);
    logger.info("Writing header:" + httpConn.getRequestProperties());
    try {
        httpConn.setRequestMethod("PUT");
    } catch (ProtocolException e1) {
        e1.printStackTrace();
    }

    OutputStream outputStream = null;
    try {
        outputStream = (httpConn.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String LINE_FEED = "\r\n";
    logger.debug("Writing body");
    writer.append("--" + boundary).append(LINE_FEED);
    logger.debug("Boundary: " + boundary);
    writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    logger.debug("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"");
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    logger.debug("Content-Type: " + URLConnection.guessContentTypeFromName(fileName));
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    logger.debug("Content-Transfer-Encoding: binary");
    writer.append(LINE_FEED);

    writer.flush();

    fileToOutputStream(uploadFile, outputStream);
    try {
        outputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

    writer.append(LINE_FEED);
    writer.flush();
    writer.close();
    httpConn.disconnect();

    try {
        logger.info(
                "Server respond: " + httpConn.getResponseCode() + " , " + httpConn.getResponseMessage() + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java

/**
 * Method to download Series dicoms/* w ww  .  j  a v  a  2 s .  c om*/
 * 
 * @param stream - true if file should stream, otherwise placed on disk to be picked (should be deleted after use)
 * @param httpResponse
 * @param seriesReference
 * @param username
 * @param sessionID
 * @throws Exception
 */
public static void downloadSeries(boolean stream, HttpServletResponse httpResponse,
        SeriesReference seriesReference, String username, String sessionID, boolean includeAIMs)
        throws Exception {
    log.info("Downloading series:" + seriesReference.seriesUID + " stream:" + stream);
    EpadOperations epadOperations = DefaultEpadOperations.getInstance();
    EPADSeries series = epadOperations.getSeriesDescription(seriesReference, username, sessionID);
    String downloadDirPath = EPADConfig.getEPADWebServerResourcesDir() + downloadDirName + "temp"
            + Long.toString(System.currentTimeMillis());
    File downloadDir = new File(downloadDirPath);
    downloadDir.mkdirs();
    List<String> fileNames = new ArrayList<String>();
    if (series.isNonDicomSeries) {
        EpadProjectOperations projectOperations = DefaultEpadProjectOperations.getInstance();
        List<EpadFile> files = projectOperations.getSeriesFiles(null, null, null, series.seriesUID);
        for (EpadFile file : files) {
            String name = file.getName();
            File epadFile = new File(downloadDir, name);
            EPADFileUtils.copyFile(new File(EPADConfig.getEPADWebServerResourcesDir() + getEpadFilePath(file)),
                    epadFile);
            fileNames.add(name);
        }
    } else {
        EPADImageList imageList = new EPADImageList();
        try {
            imageList = epadOperations.getImageDescriptions(seriesReference, sessionID, null);
        } catch (Exception x) {
        }
        for (EPADImage image : imageList.ResultSet.Result) {
            String name = image.imageUID + ".dcm";
            File imageFile = new File(downloadDir, name);
            fileNames.add(name);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
                String queryString = "requestType=WADO&studyUID=" + seriesReference.studyUID + "&seriesUID="
                        + seriesReference.seriesUID + "&objectUID=" + image.imageUID
                        + "&contentType=application/dicom";
                performWADOQuery(queryString, fos, username, sessionID);
            } catch (Exception x) {
                log.warning("Error downloading image using wado");
            } finally {
                if (fos != null)
                    fos.close();
            }
        }
    }
    if (includeAIMs) {
        EPADAIMList aimList = epadOperations.getSeriesAIMDescriptions(seriesReference, username, sessionID);
        log.info("go filter");
        aimList = AIMUtil.filterPermittedImageAnnotations(aimList, username, sessionID);
        for (EPADAIM aim : aimList.ResultSet.Result) {
            String name = "Aim_" + format4Filename(series.patientName) + "_" + aim.aimID + ".xml";
            File aimFile = new File(downloadDir, name);
            fileNames.add(name);
            FileWriter fw = null;
            try {
                fw = new FileWriter(aimFile);
                fw.write(formatXMLtoLatest(aim.xml));
            } catch (Exception x) {
                log.warning("Error writing aim file");
            } finally {
                if (fw != null)
                    fw.close();
            }
        }
    }
    String zipName = "Patient-" + seriesReference.subjectID + "-Study-" + seriesReference.studyUID + "-Serie-"
            + seriesReference.seriesUID + ".zip";
    if (stream) {
        httpResponse.setContentType("application/zip");
        httpResponse.setHeader("Content-Disposition", "attachment;filename=\"" + zipName + "\"");
    }

    File zipFile = null;
    OutputStream out = null;
    try {
        if (stream) {
            out = httpResponse.getOutputStream();
        } else {
            zipFile = new File(downloadDir, zipName);
            out = new FileOutputStream(zipFile);
        }
    } catch (Exception e) {
        log.warning("Error getting output stream", e);
        throw e;
    }
    ZipAndStreamFiles(out, fileNames, downloadDirPath + "/");
    if (!stream) {
        File newZip = new File(EPADConfig.getEPADWebServerResourcesDir() + downloadDirName, zipName);
        zipFile.renameTo(newZip);
        EPADFile epadFile = new EPADFile("", "", "", "", "", zipName, zipFile.length(), "Series",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, seriesReference.seriesUID);
        PrintWriter responseStream = httpResponse.getWriter();
        responseStream.append(epadFile.toJSON());
    }
    EPADFileUtils.deleteDirectoryAndContents(downloadDir);
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java

/**
 * Method to download dicoms from a list of series
 * //from   ww  w  .  j  av a2  s.  c om
 * @param stream - true if file should stream, otherwise placed on disk to be picked (should be deleted after use)
 * @param httpResponse
 * @param studyReference
 * @param username
 * @param sessionID
 * @param searchFilter
 * @param seriesUIDs
 * @throws Exception
 */
public static void downloadSeries(boolean stream, HttpServletResponse httpResponse, String seriesUIDs,
        String username, String sessionID, boolean includeAIMs) throws Exception {
    log.info("Downloading seriesUIDs:" + seriesUIDs + " stream:" + stream);
    String downloadDirPath = EPADConfig.getEPADWebServerResourcesDir() + downloadDirName + "temp"
            + Long.toString(System.currentTimeMillis());
    File downloadDir = new File(downloadDirPath);
    downloadDir.mkdirs();
    EpadOperations epadOperations = DefaultEpadOperations.getInstance();
    List<String> fileNames = new ArrayList<String>();
    String[] seriesIDs = seriesUIDs.split(",");
    for (String seriesUID : seriesIDs) {
        if (seriesUID.trim().length() == 0)
            continue;
        File seriesDir = new File(downloadDir, "Series-" + seriesUID);
        seriesDir.mkdirs();
        SeriesReference seriesReference = new SeriesReference(null, null, null, seriesUID);
        EPADSeries series = epadOperations.getSeriesDescription(seriesReference, username, sessionID);
        if (series.isNonDicomSeries) {
            EpadProjectOperations projectOperations = DefaultEpadProjectOperations.getInstance();
            List<EpadFile> files = projectOperations.getSeriesFiles(null, null, null, series.seriesUID);
            for (EpadFile file : files) {
                String name = file.getName();
                File epadFile = new File(seriesDir, name);
                EPADFileUtils.copyFile(
                        new File(EPADConfig.getEPADWebServerResourcesDir() + getEpadFilePath(file)), epadFile);
                fileNames.add("Series-" + series.seriesUID + "/" + name);
            }
            continue;
        }
        seriesReference = new SeriesReference(null, series.patientID, series.studyUID, seriesUID);
        EPADImageList imageList = new EPADImageList();
        try {
            imageList = epadOperations.getImageDescriptions(seriesReference, sessionID, null);
        } catch (Exception x) {
        }
        int i = 0;
        for (EPADImage image : imageList.ResultSet.Result) {
            String name = image.imageUID + ".dcm";
            File imageFile = new File(seriesDir, name);
            fileNames.add("Series-" + series.seriesUID + "/" + name);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
                String queryString = "requestType=WADO&studyUID=" + seriesReference.studyUID + "&seriesUID="
                        + seriesReference.seriesUID + "&objectUID=" + image.imageUID
                        + "&contentType=application/dicom";
                performWADOQuery(queryString, fos, username, sessionID);
            } catch (Exception x) {
                log.warning("Error downloading image using wado");
            } finally {
                if (fos != null)
                    fos.close();
            }
        }
        if (includeAIMs) {
            EPADAIMList aimList = epadOperations.getSeriesAIMDescriptions(seriesReference, username, sessionID);
            log.info("go filter");
            aimList = AIMUtil.filterPermittedImageAnnotations(aimList, username, sessionID);
            for (EPADAIM aim : aimList.ResultSet.Result) {
                String name = "Aim_" + format4Filename(series.patientName) + "_" + aim.aimID + ".xml";
                File aimFile = new File(seriesDir, name);
                fileNames.add("Series-" + series.seriesUID + "/" + name);
                FileWriter fw = null;
                try {
                    fw = new FileWriter(aimFile);
                    fw.write(formatXMLtoLatest(aim.xml));
                } catch (Exception x) {
                    log.warning("Error writing aim file");
                } finally {
                    if (fw != null)
                        fw.close();
                }
            }
        }
    }
    String ids = seriesUIDs.replace(",", "-");
    if (ids.length() > 128)
        ids = ids.substring(0, 128);
    String zipName = "Series-" + ids + ".zip";
    if (stream) {
        httpResponse.setContentType("application/zip");
        httpResponse.setHeader("Content-Disposition", "attachment;filename=\"" + zipName + "\"");
    }

    File zipFile = null;
    OutputStream out = null;
    try {
        if (stream) {
            out = httpResponse.getOutputStream();
        } else {
            zipFile = new File(downloadDir, zipName);
            out = new FileOutputStream(zipFile);
        }
    } catch (Exception e) {
        log.warning("Error getting output stream", e);
        throw e;
    }
    ZipAndStreamFiles(out, fileNames, downloadDirPath + "/");
    if (!stream) {
        File newZip = new File(EPADConfig.getEPADWebServerResourcesDir() + downloadDirName, zipName);
        zipFile.renameTo(newZip);
        EPADFile epadFile = new EPADFile("", "", "", "", "", zipName, zipFile.length(), "Series",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, seriesUIDs);
        PrintWriter responseStream = httpResponse.getWriter();
        responseStream.append(epadFile.toJSON());
    }
    EPADFileUtils.deleteDirectoryAndContents(downloadDir);

}