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:au.org.paperminer.main.UserFilter.java

/**
 * Either extracts the current user editable data (email and trove key) for possible
 * user modification, or resets the DB data to passed values.
 * @param req/* w  ww .  j  a  va 2  s. co m*/
 * @param resp
 */
private void updateUser(HttpServletRequest req, HttpServletResponse resp) {
    String id = req.getParameter("id");
    m_logger.info("updating user info " + id);
    if ((id != null) && id.length() > 0) {
        resetUserData(id, req, resp);
    } else {
        id = CookieHelper.getCookieValue(req, PaperMinerConstants.PMC_USER_ID);
        if (id == null) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e110");
        } else {
            m_logger.debug("retrieving user info");
            UserHelper helper = new UserHelper(id);
            if (!helper.isKnownUser()) {
                req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e106");
            } else {
                try {
                    resp.setContentType("text/html");
                    PrintWriter pm = resp.getWriter();
                    pm.write("<form id=\"user-mod\" action=\"\" method=\"post\">");
                    pm.append("<input id=\"id\" type=\"hidden\" value=\"" + helper.get(UserHelper.ID) + "\"/>");
                    pm.append("<table>");
                    pm.append("<tr><td>eMail address </td><td><input id=\"em\" type=\"text=\" value=\""
                            + helper.get(UserHelper.EMAIL) + "\"/></td></tr>");
                    pm.append("<tr><td>TROVE Key </td><td><input id=\"tk\" type=\"text=\" value=\""
                            + helper.get(UserHelper.TROVE_KEY) + "\"/></td></tr>");
                    pm.append("</table>");
                    pm.append(
                            "<p><input id=\"vfy\" name=\"usr-cb\" type=\"checkbox\" value=\"verify\"/> Verify my eMail Address.");
                    pm.append("</form>");
                } catch (IOException ex) {
                    req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e107");
                }
            }
        }
    }
}

From source file:opendap.hai.BesControlApi.java

private void controlApi(HttpServletRequest request, HttpServletResponse response, boolean isPost)
        throws IOException {

    StringBuilder sb = new StringBuilder();

    Enumeration headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = request.getHeader(headerName);
        sb.append("    ").append(headerName).append(" = '").append(headerValue).append("'\n");
    }/*from ww w .j  a  va 2s .  c o m*/

    log.debug("\nHTTP HEADERS:\n{}", sb);

    //log.debug("\nBODY:\n{}",getRequestBodyAsString(request));

    HashMap<String, String> kvp = Util.processQuery(request);

    String status = null;
    try {
        status = processBesCommand(kvp, isPost);
    } catch (BesAdminFail baf) {
        status = baf.getMessage();

    }
    PrintWriter output = response.getWriter();

    //@todo work this out to not escape everything.
    //output.append(StringEscapeUtils.escapeHtml(status));

    //String s = processStatus(status);

    output.append(status);

    output.flush();

}

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

/**
 * Method to download Subject dicoms//w  ww .  j a  v  a  2s  .c  om
 * 
 * @param stream - true if file should stream, otherwise placed on disk to be picked (should be deleted after use)
 * @param httpResponse
 * @param subjectReference
 * @param username
 * @param sessionID
 * @param searchFilter
 * @param studyUIDs - download only these selected studies
 * @throws Exception
 */
public static void downloadSubject(boolean stream, HttpServletResponse httpResponse,
        SubjectReference subjectReference, String username, String sessionID, EPADSearchFilter searchFilter,
        String studyUIDs, boolean includeAIMs) throws Exception {
    log.info("Downloading subject:" + subjectReference.subjectID + " stream:" + stream);
    Set<String> studies = new HashSet<String>();
    if (studyUIDs != null) {
        String[] ids = studyUIDs.split(",");
        for (String id : ids)
            studies.add(id.trim());
    }
    String downloadDirPath = EPADConfig.getEPADWebServerResourcesDir() + downloadDirName + "temp"
            + Long.toString(System.currentTimeMillis());
    log.info("download path:" + downloadDirPath);
    File downloadDir = new File(downloadDirPath);
    downloadDir.mkdirs();
    EpadOperations epadOperations = DefaultEpadOperations.getInstance();
    List<String> fileNames = new ArrayList<String>();
    EPADStudyList studyList = epadOperations.getStudyDescriptions(subjectReference, username, sessionID,
            searchFilter);
    for (EPADStudy study : studyList.ResultSet.Result) {
        if (!studies.isEmpty() && !studies.contains(study.studyUID))
            continue;
        File studyDir = new File(downloadDir, "Study-" + study.studyUID);
        studyDir.mkdirs();
        StudyReference studyReference = new StudyReference(subjectReference.projectID,
                subjectReference.subjectID, study.studyUID);
        EPADSeriesList seriesList = epadOperations.getSeriesDescriptions(studyReference, username, sessionID,
                searchFilter, false);
        for (EPADSeries series : seriesList.ResultSet.Result) {
            log.info("series proj=" + series.projectID + " study proj=" + studyReference.projectID);
            if (series.projectID != studyReference.projectID) //if the series is not in this project, skip
                continue;
            File seriesDir = new File(studyDir, "Series-" + series.seriesUID);
            seriesDir.mkdirs();
            SeriesReference seriesReference = new SeriesReference(studyReference.projectID,
                    studyReference.subjectID, studyReference.studyUID, series.seriesUID);
            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(seriesDir, name);
                fileNames.add("Study-" + studyReference.studyUID + "/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();
                }
            }

            //ml include aims copied from series
            if (includeAIMs) {
                EPADAIMList aimList = epadOperations.getSeriesAIMDescriptions(seriesReference, username,
                        sessionID);
                aimList = AIMUtil.filterPermittedImageAnnotations(aimList, username, sessionID);
                for (EPADAIM aim : aimList.ResultSet.Result) {
                    String name = "Aim_" + format4Filename(study.patientName) + "_" + aim.aimID + ".xml";
                    File aimFile = new File(seriesDir, name);
                    fileNames.add(
                            "Study-" + studyReference.studyUID + "/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 zipName = "Patient-" + subjectReference.subjectID + ".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(), "Patient",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, subjectReference.subjectID);
        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 Study dicoms//from w ww .  j  a  v  a2  s .co m
 * 
 * @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 - download only these selected series
 * @throws Exception
 */
public static void downloadStudy(boolean stream, HttpServletResponse httpResponse,
        StudyReference studyReference, String username, String sessionID, EPADSearchFilter searchFilter,
        String seriesUIDs, boolean includeAIMs) throws Exception {
    log.info("Downloading study:" + studyReference.studyUID + " stream:" + stream);
    Set<String> seriesSet = new HashSet<String>();
    if (seriesUIDs != null) {
        String[] ids = seriesUIDs.split(",");
        for (String id : ids)
            seriesSet.add(id.trim());
    }
    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>();
    EPADSeriesList seriesList = epadOperations.getSeriesDescriptions(studyReference, username, sessionID,
            searchFilter, false);
    int imageCount = 0;
    log.info("Number series in study:" + seriesList.ResultSet.totalRecords);
    for (EPADSeries series : seriesList.ResultSet.Result) {
        if (!seriesSet.isEmpty() && !seriesSet.contains(series.seriesUID))
            continue;
        File seriesDir = new File(downloadDir, "Series-" + series.seriesUID);
        seriesDir.mkdirs();
        SeriesReference seriesReference = new SeriesReference(studyReference.projectID,
                studyReference.subjectID, studyReference.studyUID, series.seriesUID);
        if (series.isNonDicomSeries) {
            log.debug("Downloading files:" + series.seriesUID);
            EpadProjectOperations projectOperations = DefaultEpadProjectOperations.getInstance();
            List<EpadFile> files = projectOperations.getSeriesFiles(studyReference.projectID,
                    studyReference.subjectID, studyReference.studyUID, 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;
        }
        EPADImageList imageList = new EPADImageList();
        try {
            imageList = epadOperations.getImageDescriptions(seriesReference, sessionID, null);
        } catch (Exception x) {
        }
        int i = 0;
        for (EPADImage image : imageList.ResultSet.Result) {
            imageCount++;
            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);
            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 zipName = "Patient-" + studyReference.subjectID + "-Study-" + studyReference.studyUID + ".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(), "Study",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, studyReference.studyUID);
        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 Project dicoms/* w w  w .  jav  a  2  s .c  o  m*/
 * 
 * @author Emel Alkim  
 * @param stream - true if file should stream, otherwise placed on disk to be picked (should be deleted after use)
 * @param httpResponse
 * @param subjectReference
 * @param username
 * @param sessionID
 * @param searchFilter
 * @param subjectUIDs - download only these selected subjects
 * @throws Exception
 */
public static void downloadProject(boolean stream, HttpServletResponse httpResponse,
        ProjectReference projectReference, String username, String sessionID, EPADSearchFilter searchFilter,
        String subjectUIDs, boolean includeAIMs) throws Exception {
    log.info("Downloading project:" + projectReference.projectID + " stream:" + stream);
    Set<String> subjects = new HashSet<String>();
    if (subjectUIDs != null) {
        String[] ids = subjectUIDs.split(",");
        for (String id : ids)
            subjects.add(id.trim());
    }
    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>();
    //TODO ml change the static numbers
    //subjects
    EPADSubjectList subjectList = epadOperations.getSubjectDescriptions(projectReference.projectID, username,
            sessionID, searchFilter, 1, 5000, "", false);
    for (EPADSubject subject : subjectList.ResultSet.Result) {
        if (!subjects.isEmpty() && !subjects.contains(subject.subjectID))
            continue;
        File subjectDir = new File(downloadDir, "Subject-" + subject.subjectID);
        subjectDir.mkdirs();
        SubjectReference subjectReference = new SubjectReference(projectReference.projectID, subject.subjectID);
        //studies
        EPADStudyList studyList = epadOperations.getStudyDescriptions(subjectReference, username, sessionID,
                searchFilter);
        for (EPADStudy study : studyList.ResultSet.Result) {
            File studyDir = new File(subjectDir, "Study-" + study.studyUID);
            studyDir.mkdirs();

            StudyReference studyReference = new StudyReference(subjectReference.projectID,
                    subjectReference.subjectID, study.studyUID);
            //series
            EPADSeriesList seriesList = epadOperations.getSeriesDescriptions(studyReference, username,
                    sessionID, searchFilter, false);
            for (EPADSeries series : seriesList.ResultSet.Result) {
                File seriesDir = new File(studyDir, "Series-" + series.seriesUID);
                seriesDir.mkdirs();
                SeriesReference seriesReference = new SeriesReference(studyReference.projectID,
                        studyReference.subjectID, studyReference.studyUID, series.seriesUID);
                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(seriesDir, name);
                    fileNames.add("Subject-" + subjectReference.subjectID + "/Study-" + studyReference.studyUID
                            + "/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();
                    }
                }

                //ml include aims copied from series
                if (includeAIMs) {
                    EPADAIMList aimList = epadOperations.getSeriesAIMDescriptions(seriesReference, username,
                            sessionID);
                    aimList = AIMUtil.filterPermittedImageAnnotations(aimList, username, sessionID);
                    for (EPADAIM aim : aimList.ResultSet.Result) {
                        String name = "Aim_" + format4Filename(subject.subjectName) + "_" + aim.aimID + ".xml";
                        File aimFile = new File(seriesDir, name);
                        fileNames.add("Subject-" + subjectReference.subjectID + "/Study-"
                                + studyReference.studyUID + "/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 zipName = "Project-" + projectReference.projectID + ".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(), "Project",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, projectReference.projectID);
        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 multiple Subject dicoms
 * //from   ww  w  .ja v  a  2  s . c  om
 * @author Emel Alkim  
 * @param stream - true if file should stream, otherwise placed on disk to be picked (should be deleted after use)
 * @param httpResponse
 * @param subjectReference
 * @param username
 * @param sessionID
 * @param searchFilter
 * @param subjectUIDs - download only these selected subjects
 * @throws Exception
 */
public static void downloadSubjects(boolean stream, HttpServletResponse httpResponse, String subjectUIDs,
        String username, String sessionID, EPADSearchFilter searchFilter, boolean includeAIMs, String projectID)
        throws Exception {
    log.info("Downloading subjects:" + subjectUIDs + " stream:" + stream);
    Set<String> subjects = new HashSet<String>();
    if (subjectUIDs != null) {
        String[] ids = subjectUIDs.split(",");
        for (String id : ids)
            subjects.add(id.trim());
    }
    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>();
    //TODO ml change the static numbers
    //subjects
    for (String subjectID : subjects) {
        SubjectReference subjectReference = new SubjectReference(projectID, subjectID);
        EPADSubject subject = epadOperations.getSubjectDescription(subjectReference, username, sessionID);

        if (!subjects.isEmpty() && !subjects.contains(subject.subjectID))
            continue;
        File subjectDir = new File(downloadDir, "Subject-" + subject.subjectID);
        subjectDir.mkdirs();
        //studies
        EPADStudyList studyList = epadOperations.getStudyDescriptions(subjectReference, username, sessionID,
                searchFilter);

        for (EPADStudy study : studyList.ResultSet.Result) {
            File studyDir = new File(subjectDir, "Study-" + study.studyUID);
            studyDir.mkdirs();

            StudyReference studyReference = new StudyReference(subjectReference.projectID,
                    subjectReference.subjectID, study.studyUID);
            //series
            EPADSeriesList seriesList = epadOperations.getSeriesDescriptions(studyReference, username,
                    sessionID, searchFilter, false);
            for (EPADSeries series : seriesList.ResultSet.Result) {
                File seriesDir = new File(studyDir, "Series-" + series.seriesUID);
                seriesDir.mkdirs();
                SeriesReference seriesReference = new SeriesReference(studyReference.projectID,
                        studyReference.subjectID, studyReference.studyUID, series.seriesUID);
                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(seriesDir, name);
                    fileNames.add("Subject-" + subjectReference.subjectID + "/Study-" + studyReference.studyUID
                            + "/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", x);
                    } finally {
                        if (fos != null)
                            fos.close();
                    }
                }

                //ml include aims copied from series
                if (includeAIMs) {
                    EPADAIMList aimList = epadOperations.getSeriesAIMDescriptions(seriesReference, username,
                            sessionID);
                    aimList = AIMUtil.filterPermittedImageAnnotations(aimList, username, sessionID);
                    for (EPADAIM aim : aimList.ResultSet.Result) {
                        String name = "Aim_" + format4Filename(subject.subjectName) + "_" + aim.aimID + ".xml";

                        File aimFile = new File(seriesDir, name);
                        fileNames.add("Subject-" + subjectReference.subjectID + "/Study-"
                                + studyReference.studyUID + "/Series-" + series.seriesUID + "/" + name);
                        FileWriter fw = null;
                        try {
                            fw = new FileWriter(aimFile);
                            //                     fw.write(aim.xml);
                            fw.write(formatXMLtoLatest(aim.xml));
                        } catch (Exception x) {
                            log.warning("Error writing aim file");
                        } finally {
                            if (fw != null)
                                fw.close();
                        }
                    }
                }
            }
        }
    }
    String zipName = "Subjects-" + subjectUIDs + ".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(), "Subjects",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, subjectUIDs);
        PrintWriter responseStream = httpResponse.getWriter();
        responseStream.append(epadFile.toJSON());
    }
    EPADFileUtils.deleteDirectoryAndContents(downloadDir);
}

From source file:jmap2gml.ScriptGui.java

/**
 * Formats the window, initializes the JMap2Script object, and sets up all
 * the necessary events.//from w w w .j av a2  s  .  c  om
 */
public ScriptGui() {
    setTitle("jmap to gml script converter");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().setLayout(new GridBagLayout());

    this.addWindowListener(new WindowListener() {
        @Override
        public void windowOpened(WindowEvent we) {
        }

        @Override
        public void windowClosing(WindowEvent we) {
            saveConfig();
        }

        @Override
        public void windowClosed(WindowEvent we) {
        }

        @Override
        public void windowIconified(WindowEvent we) {
        }

        @Override
        public void windowDeiconified(WindowEvent we) {
        }

        @Override
        public void windowActivated(WindowEvent we) {
        }

        @Override
        public void windowDeactivated(WindowEvent we) {
        }
    });

    GridBagConstraints c = new GridBagConstraints();

    setResizable(true);
    setIconImage((new ImageIcon("spikeup.png")).getImage());

    jta = new JTextArea(38, 30);

    loadConfig();

    JScrollPane jsp = new JScrollPane(jta);
    jsp.setRowHeaderView(new TextLineNumber(jta));
    jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    jsp.setSize(jsp.getWidth(), 608);

    // menu bar
    JMenuBar menubar = new JMenuBar();

    // file menu
    JMenu file = new JMenu("File");

    // load button
    JMenuItem load = new JMenuItem("Load jmap");
    load.addActionListener(ae -> {
        JFileChooser fileChooser = new JFileChooser(prevDirectory);
        fileChooser.setFileFilter(new FileNameExtensionFilter("jmap file", "jmap", "jmap"));

        int returnValue = fileChooser.showOpenDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();

            prevDirectory = selectedFile.getAbsolutePath();

            jm2s = new ScriptFromJmap(selectedFile.getPath(), false);

            jta.setText("");
            jta.append(jm2s.toString());
            jta.setCaretPosition(0);

            writeFile.setEnabled(true);

            drawPanel.setItems(jta.getText().split("\n"));
        }
    });

    // add load to file menu
    file.add(load);

    // button to save script to file
    writeFile = new JMenuItem("Write file");
    writeFile.addActionListener(ae -> {
        if (jm2s != null) {
            PrintWriter out;
            try {
                File f = new File(
                        jm2s.getFileName().substring(0, jm2s.getFileName().lastIndexOf(".jmap")) + ".gml");
                out = new PrintWriter(f);
                out.append(jm2s.toString());
                out.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScriptGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    writeFile.setEnabled(false);

    JMenuItem gmx = new JMenuItem("Export as gmx");
    gmx.addActionListener(ae -> {
        String fn = String.format("%s.room.gmx", prevDirectory);

        JFileChooser fc = new JFileChooser(prevDirectory);
        fc.setSelectedFile(new File(fn));
        fc.setFileFilter(new FileNameExtensionFilter("Game Maker XML", "gmx", "gmx"));
        fc.showDialog(null, "Save");
        File f = fc.getSelectedFile();

        if (f != null) {
            try {
                GMX.itemsToGMX(drawPanel.items, new FileOutputStream(f));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScriptGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    // add to file menu
    file.add(writeFile);
    file.add(gmx);

    // add file menu to the menubar
    menubar.add(file);

    // Edit menu

    // display menu
    JMenu display = new JMenu("Display");

    JMenuItem update = new JMenuItem("Update");

    update.addActionListener(ae -> {
        drawPanel.setItems(jta.getText().split("\n"));
    });

    display.add(update);

    JMenuItem gridToggle = new JMenuItem("Toggle Grid");
    gridToggle.addActionListener(ae -> {
        drawPanel.toggleGrid();
    });
    display.add(gridToggle);

    JMenuItem gridOptions = new JMenuItem("Modify Grid");
    gridOptions.addActionListener(ae -> {
        drawPanel.modifyGrid();
    });
    display.add(gridOptions);

    menubar.add(display);

    // sets the menubar
    setJMenuBar(menubar);

    // add the text area to the window
    c.gridx = 0;
    c.gridy = 0;
    add(jsp, c);

    // initialize the preview panel
    drawPanel = new Preview(this);
    JScrollPane scrollPane = new JScrollPane(drawPanel);

    // add preview panel to the window
    c.gridx = 1;
    c.gridwidth = 2;
    add(scrollPane, c);

    pack();
    setMinimumSize(this.getSize());
    setLocationRelativeTo(null);
    setVisible(true);
    drawPanel.setItems(jta.getText().split("\n"));
}

From source file:com.ifeng.computing.batch.job.writer.NewsItemFlatFileItemWriter.java

@Override
public void write(List<? extends List<NewsItem>> items) throws Exception {
    PrintWriter pw = new PrintWriter(new File("sub_data.csv"));
    StringBuilder sb = null;// w w  w. ja  v  a  2s . c o  m

    for (List<NewsItem> news : items) {
        for (NewsItem item : news) {
            sb = new StringBuilder("");

            sb.append(item.getId());
            sb.append(",");

            sb.append(item.getCategory());
            sb.append(",");

            sb.append(item.getHotLevel());
            sb.append(",");

            sb.append(item.getpId());
            sb.append(",");

            sb.append(item.getSimScore());

            pw.append(sb.toString());
            pw.println();
        }
    }

    pw.flush();
    pw.close();
}

From source file:org.silverpeas.core.contribution.content.form.displayers.AbstractFileFieldDisplayer.java

/**
 * Prints the javascripts which will be used to control the new value given to the named field.
 * The error messages may be adapted to a local language. The FieldTemplate gives the field type
 * and constraints. The FieldTemplate gives the local labeld too. Never throws an Exception but
 * log a silvertrace and writes an empty string when :
 * <ul>/*  w  w w .  ja  va 2 s  .c om*/
 * <li>the fieldName is unknown by the template.</li>
 * <li>the field type is not a managed type.</li>
 * </ul>
 */
@Override
public void displayScripts(final PrintWriter out, final FieldTemplate template, final PagesContext pageContext)
        throws IOException {
    checkFieldType(template.getTypeName(), "AbstractFileFieldDisplayer.displayScripts");
    String language = pageContext.getLanguage();
    String fieldName = template.getFieldName();
    if (template.isMandatory() && pageContext.useMandatory()) {
        out.append("  if (isWhitespace(stripInitialWhitespace(field.value))) {\n").append("   var ")
                .append(fieldName).append("Value = document.getElementById('").append(fieldName)
                .append(FileField.PARAM_ID_SUFFIX).append("').value;\n").append("   var ").append(fieldName)
                .append("Operation = document.").append(pageContext.getFormName()).append(".").append(fieldName)
                .append(OPERATION_KEY).append(".value;\n").append("   if (").append(fieldName)
                .append("Value=='' || ").append(fieldName).append("Operation=='")
                .append(Operation.DELETION.name()).append("') {\n").append("     errorMsg+=\"  - '")
                .append(WebEncodeHelper.javaStringToJsString(template.getLabel(language))).append("' ")
                .append(Util.getString("GML.MustBeFilled", language)).append("\\n\";\n")
                .append("     errorNb++;\n").append("   }\n").append(" }\n");
    }

    if (!template.isReadOnly()) {
        Util.includeFileNameLengthChecker(template, pageContext, out);
        Util.getJavascriptChecker(template.getFieldName(), pageContext, out);
    }
}

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

/**
 * Method to download list of Study dicoms
 * //w w w.ja  v a  2 s  . c  o m
 * @param stream - true if file should stream, otherwise placed on disk to be picked (should be deleted after use)
 * @param httpResponse
 * @param subjectReference
 * @param username
 * @param sessionID
 * @param searchFilter
 * @param studyUIDs - download only these selected studies
 * @param projectID
 * @throws Exception
 */
public static void downloadStudies(boolean stream, HttpServletResponse httpResponse, String studyUIDs,
        String username, String sessionID, boolean includeAIMs, String projectID) throws Exception {
    log.info("Downloading studies:" + studyUIDs + " stream:" + stream);
    Set<String> studies = new HashSet<String>();
    if (studyUIDs != null) {
        String[] ids = studyUIDs.split(",");
        for (String id : ids)
            studies.add(id.trim());
    }
    String downloadDirPath = EPADConfig.getEPADWebServerResourcesDir() + downloadDirName + "temp"
            + Long.toString(System.currentTimeMillis());
    File downloadDir = new File(downloadDirPath);
    downloadDir.mkdirs();
    EpadOperations epadOperations = DefaultEpadOperations.getInstance();
    EpadProjectOperations projectOperations = DefaultEpadProjectOperations.getInstance();
    EpadDatabaseOperations databaseOperations = EpadDatabase.getInstance().getEPADDatabaseOperations();
    List<String> fileNames = new ArrayList<String>();
    for (String studyUID : studies) {
        if (studyUID.length() == 0)
            continue;
        File studyDir = new File(downloadDir, "Study-" + studyUID);
        studyDir.mkdirs();

        StudyReference studyReference = new StudyReference(projectID, null, studyUID);
        EPADStudy study = epadOperations.getStudyDescription(studyReference, username, sessionID);
        if (study == null)
            throw new Exception("Study not found:" + studyReference.studyUID);
        studyReference = new StudyReference(projectID, study.patientID, studyUID);
        EPADSeriesList seriesList = epadOperations.getSeriesDescriptions(studyReference, username, sessionID,
                new EPADSearchFilter(), false);
        for (EPADSeries series : seriesList.ResultSet.Result) {
            if (series.isNonDicomSeries) {
                File seriesDir = new File(studyDir, "Series-" + series.seriesUID);
                seriesDir.mkdirs();
                List<EpadFile> files = projectOperations.getSeriesFiles(projectID, null, studyUID,
                        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);
                }
                continue;
            }
            if (series.isDSO) {
                try {
                    List<EPADAIM> aims = databaseOperations.getAIMsByDSOSeries(series.seriesUID);
                    boolean skip = true;
                    for (EPADAIM aim : aims) {
                        if (aim.userName.equalsIgnoreCase(username))
                            skip = false;
                    }
                    if (skip)
                        continue;
                } catch (Exception x) {
                }
                ;
            }
            File seriesDir = new File(studyDir, "Series-" + series.seriesUID);
            seriesDir.mkdirs();
            SeriesReference seriesReference = new SeriesReference(studyReference.projectID,
                    studyReference.subjectID, studyReference.studyUID, series.seriesUID);
            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(seriesDir, name);
                fileNames.add("Study-" + studyReference.studyUID + "/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);
                aimList = AIMUtil.filterPermittedImageAnnotations(aimList, username, sessionID);
                for (EPADAIM aim : aimList.ResultSet.Result) {
                    //String name = "Aim_" + aim.aimID + ".xml";
                    String name = "Aim_" + format4Filename(study.patientName) + "_" + aim.aimID + ".xml";

                    File aimFile = new File(seriesDir, name);
                    fileNames.add(
                            "Study-" + studyReference.studyUID + "/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 = studyUIDs.replace(",", "-");
    if (ids.length() > 128)
        ids = ids.substring(0, 128);
    String zipName = "Studies-" + 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(), "Studies",
                formatDate(new Date()), downloadDirName + zipFile.getName(), true, studyUIDs);
        PrintWriter responseStream = httpResponse.getWriter();
        responseStream.append(epadFile.toJSON());
    }
    EPADFileUtils.deleteDirectoryAndContents(downloadDir);

}