Example usage for javax.servlet ServletOutputStream println

List of usage examples for javax.servlet ServletOutputStream println

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream println.

Prototype


public void println(double d) throws IOException 

Source Link

Document

Writes a double value to the client, followed by a carriage return-line feed (CRLF).

Usage

From source file:org.openmrs.module.tracpatienttransfer.util.FileExporter.java

/**
 * Auto generated method comment//from   w  w  w  .  j a  v  a2 s . co  m
 * 
 * @param request
 * @param response
 * @param res
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Integer> res,
        String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;

    try {
        SimpleDateFormat sdf = Context.getDateFormat();
        outputStream = response.getOutputStream();
        ObsService os = Context.getObsService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        // header
        outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report", null) + ", : " + title);
        outputStream.println();
        if (request.getParameter("reason") != null
                && request.getParameter("reason").trim().compareTo("") != 0) {
            Integer conceptId = Integer.parseInt(request.getParameter("reason"));
            outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report.reasonofexit", null)
                    + ", : " + TransferOutInPatientTag.getConceptNameById("" + conceptId));
            // outputStream.println();
        }

        if (request.getParameter("location") != null
                && request.getParameter("location").trim().compareTo("") != 0) {
            Integer locationId = Integer.parseInt(request.getParameter("location"));
            outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report.location", null) + ", : "
                    + Context.getLocationService().getLocation(locationId).getName());
            outputStream.println();
        }
        outputStream.println("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdon", null)
                + ", : " + sdf.format(new Date()));// Report date
        outputStream.println("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdby", null)
                + ", : " + Context.getAuthenticatedUser().getPersonName());// Report

        outputStream.println(
                MohTracUtil.getMessage("tracpatienttransfer.report.numberofpatient", null) + ", " + res.size());
        outputStream.println();

        boolean hasRoleToViewPatientsNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

        // column header
        outputStream
                .println(MohTracUtil.getMessage("tracpatienttransfer.general.number", null) + ", "
                        + TransferOutInPatientTag
                                .getIdentifierTypeNameById(
                                        "" + TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
                        + ", "
                        + TransferOutInPatientTag.getIdentifierTypeNameById(""
                                + TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                        + ", "
                        + ((hasRoleToViewPatientsNames)
                                ? MohTracUtil.getMessage("tracpatienttransfer.general.names", null) + ", "
                                : "")
                        + MohTracUtil.getMessage("tracpatienttransfer.general.reasonofexit", null) + ", "
                        + MohTracUtil.getMessage("tracpatienttransfer.general.exitwhen", null)
                        + " ?(dd/MM/yyyy), "
                        // + MohTracUtil.getMessage("Encounter.provider", null)
                        // + ", "
                        + MohTracUtil.getMessage("Encounter.location", null) + "");
        outputStream.println();

        int ids = 0;

        log.info(">>>>>>>>>>>>>> Trying to create a CSV file...");

        for (Integer obsId : res) {
            // log.info(">>>>>>>>>>>>>> Trying to load obs#" + obsId);
            Obs obs = os.getObs(obsId);
            // log.info("----------------------------> It's ok for getObs");
            Integer patientId = obs.getPersonId();
            // log.info("----------------------------> It's ok for patientId");
            ids += 1;

            outputStream.println(ids + ","
                    + TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                            TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
                    + ","
                    + TransferOutInPatientTag
                            .personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                                    TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    + ","
                    + ((hasRoleToViewPatientsNames) ? TransferOutInPatientTag
                            .getPersonNames(patientId) + "," : "")
                    + TransferOutInPatientTag.conceptValueByObs(obs) + ""
                    + ((obs.getValueCoded().getConceptId()
                            .intValue() == TransferOutInPatientConstant.PATIENT_TRANSFERED_OUT)
                                    ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                            TransferOutInPatientConstant.TRANSFER_OUT_TO_A_LOCATION) + ")"
                                    : (obs.getValueCoded().getConceptId()
                                            .intValue() == TransferOutInPatientConstant.PATIENT_DEAD) ? " ("
                                                    + TransferOutInPatientTag.getObservationValueFromEncounter(
                                                            obs, TransferOutInPatientConstant.CAUSE_OF_DEATH)
                                                    + ")" : "")
                    + "," + new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(obs.getObsDatetime()) // + "," +
                    // TransferOutInPatientTag.getProviderByObs(obs)
                    + "," + obs.getLocation().getName() // + ","
            // + TransferOutInPatientTag.obsVoidedReason(obs)
            );
            log.info("----------------------------> It's ok for outputstream");
        }

        outputStream.flush();
        log.info(">>>>>>>>>>>>>> A CSV file was created successfully.");
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:org.openmrs.module.mohtracportal.util.FileExporter.java

/**
 * Auto generated method comment//w w  w  .  ja va  2 s.  c o m
 * 
 * @param request
 * @param response
 * @param res
 * @param filename
 * @param title
 * @param to
 * @param from
 * @param selectedUsers
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Object> res,
        String filename, String title, String from, String to, List<Integer> selectedUsers) throws Exception {

    SimpleDateFormat sdf = Context.getDateFormat();
    ServletOutputStream outputStream = null;

    try {
        outputStream = response.getOutputStream();
        PersonService ps = Context.getPersonService();

        String users = "";
        for (Integer usrId : selectedUsers) {
            users += ps.getPerson(usrId).getPersonName() + "; ";
        }

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.title", null) + ", : " + title);
        if (from.trim().compareTo("") != 0)
            outputStream.println(MohTracUtil.getMessage("mohtracportal.from", null) + ", : " + from);
        if (to.trim().compareTo("") != 0)
            outputStream.println(MohTracUtil.getMessage("mohtracportal.to", null) + ", : " + to);
        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.created.on", null) + ", : "
                + sdf.format(new Date()));// Report
        // date
        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.created.by", null) + ", : "
                + Context.getAuthenticatedUser().getPersonName());// Report
        // author
        if (users.trim().compareTo("") != 0)
            outputStream
                    .println(MohTracUtil.getMessage("mohtracportal.patient.enterers", null) + ", : " + users);
        outputStream.println();
        Integer numberOfPatients = res.size();
        outputStream.println(MohTracUtil.getMessage("mohtracportal.numberOfPatients", null) + ", "
                + numberOfPatients.toString());
        outputStream.println();

        boolean hasPrivToViewPatientNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

        outputStream.println(MohTracUtil.getMessage("mohtracportal.report.list.no", null) + ","
                + ((hasPrivToViewPatientNames)
                        ? MohTracUtil.getMessage("mohtracportal.patient.names", null) + ", "
                        : "")
                + MohTracPortalTag.getIdentifierTypeNameByIdAsString(
                        "" + MohTracConfigurationUtil.getTracNetIdentifierTypeId())
                + ", "
                + MohTracPortalTag.getIdentifierTypeNameByIdAsString(
                        "" + MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                + ", " + MohTracUtil.getMessage("mohtracportal.patient.date.created", null) + "("
                + Context.getDateFormat().toPattern() + "), "
                + MohTracUtil.getMessage("mohtracportal.numberOfEncounters", null));
        outputStream.println();

        int ids = 0;

        for (Object patient : res) {
            Object[] o = (Object[]) patient;

            ids += 1;
            outputStream.println(ids + ","
                    + ((hasPrivToViewPatientNames)
                            ? MohTracPortalTag.getPersonNames(Integer.valueOf(o[0].toString())) + ","
                            : "")
                    + MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                            Integer.valueOf(o[0].toString()),
                            MohTracConfigurationUtil.getTracNetIdentifierTypeId())
                    + ","
                    + MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                            Integer.valueOf(o[0].toString()),
                            MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    + "," + sdf.format(o[1]) + ","
                    + MohTracPortalTag.getNumberOfEncounterByPatient(Integer.valueOf(o[0].toString())));
        }

        outputStream.flush();
        log.info("csv File created");
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:org.wings.session.PortletSessionServlet.java

/**
 * this method references to/*from w ww.  j  a  va2s . co m*/
 * {@link #doGet(HttpServletRequest, HttpServletResponse)}
 */
public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    //value chosen to limit denial of service
    if (req.getContentLength() > getSession().getMaxContentLength() * 1024) {
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        // WingS-Portlet-Bridge: removed unsupported tags
        out.println("<div><h1>Error - content length &gt; " + getSession().getMaxContentLength() + "k");
        out.println("</h1></div>");
    } else {
        doGet(req, res);
    }
    // sollte man den obigen Block nicht durch folgende Zeile ersetzen?
    //throw new RuntimeException("this method must never be called!");
    // bsc: Wieso?
}

From source file:org.openmrs.module.vcttrac.util.FileExporter.java

/**
 * Auto generated method comment//www  .j  av  a 2  s .  c o m
 * 
 * @param request
 * @param response
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVTracNetIndicators(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ServletOutputStream outputStream = null;
    //      DateFormat df = Context.getDateFormat();
    try {
        outputStream = response.getOutputStream();

        String title = VCTTracUtil.getMessage("vcttrac.tracnetIndicators", null);
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + title.trim().toLowerCase().replace(" ", "_") + ".csv" + "\"");
        outputStream.println(title);

        String location = request.getParameter("location");
        Date dateFrom = Context.getDateFormat().parse(request.getParameter("dateFrom"));
        Date dateTo = Context.getDateFormat().parse(request.getParameter("dateTo"));

        outputStream.println(VCTTracUtil.getMessage("Encounter.location", null) + " , "
                + ((location == null || location.compareTo("") == 0) ? ""
                        : Context.getLocationService().getLocation(Integer.valueOf(location)).getName()));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.from", null) + " , "
                + (new SimpleDateFormat("dd-MMM-yyyy").format(dateFrom)));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.to", null) + " , "
                + (new SimpleDateFormat("dd-MMM-yyyy").format(dateTo)));
        outputStream.println();
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.generatedby", null) + " , "
                + Context.getAuthenticatedUser().getPersonName());
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.generatedon", null) + " , "
                + new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
        outputStream.println();
        outputStream.println();

        Integer loc = Integer.parseInt(location);
        String from = request.getParameter("dateFrom");
        String to = request.getParameter("dateTo");

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.vct.indicators", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+");

        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsCounseledAndTestedForHiv", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 0, 25, 0, "m"));
        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsTestedAndReceivedResults", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 0, 25, 0, "m"));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria.numberOfHivPositiveClients", null)
                + ", " + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 0, 15, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 0, 15, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 15, 25, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 15, 25, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 25, 0, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 0, 25, 0, "m"));

        outputStream.println();
        outputStream.println();

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.pit.indicators", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " <15, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 15-24, "
                + VCTTracUtil.getMessage("vcttrac.person.female", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+, "
                + VCTTracUtil.getMessage("vcttrac.person.male", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.age", null) + " 25+");

        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsCounseledAndTestedForHiv", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsCounseledAndTestedForHIV(from, to, loc, 1, 25, 0, "m"));
        outputStream.println(VCTTracUtil
                .getMessage("vcttrac.tracnet.criteria.numberOfNewClientsTestedAndReceivedResults", null) + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 0, 15, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 0, 15, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 15, 25, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 15, 25, "m")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 25, 0, "f")
                + ", "
                + VCTModuleTag.getNumberOfNewClientsTestedAndReceivedResults(from, to, loc, 1, 25, 0, "m"));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria.numberOfHivPositiveClients", null)
                + ", " + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 0, 15, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 0, 15, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 15, 25, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 15, 25, "m") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 25, 0, "f") + ", "
                + VCTModuleTag.getNumberOfHIVPositiveClients(from, to, loc, 1, 25, 0, "m"));

        outputStream.println();
        outputStream.println();

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.couple.indicators", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.counseled", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.tested", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.all", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.tested", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.oneoftwo", null) + ", "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.tested", null) + " : "
                + VCTTracUtil.getMessage("vcttrac.tracnet.couple.none", null));
        //            +VCTTracUtil.getMessage("vcttrac.person.male", null)+" : "+VCTTracUtil.getMessage("vcttrac.age", null)+" 15-24, "
        //            +VCTTracUtil.getMessage("vcttrac.person.female", null)+" : "+VCTTracUtil.getMessage("vcttrac.age", null)+" 25+, "
        //            +VCTTracUtil.getMessage("vcttrac.person.male", null)+" : "+VCTTracUtil.getMessage("vcttrac.age", null)+" 25+");

        outputStream.println(VCTTracUtil.getMessage("vcttrac.tracnet.criteria.numberOfCouples", null) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseled(from, to, loc) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseledAndTested(from, to, loc, 2) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseledAndTested(from, to, loc, 1) + ", "
                + VCTModuleTag.getNumberOfCouplesCounseledAndTested(from, to, loc, 0));

        outputStream.println();

        outputStream.flush();
    } catch (Exception e) {
        log.error(">>VCT>>Export>>in>>CSV>>Format>>Tracnet>>Indicators>> " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }

}

From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java

/**
 * Serves up a site that can be used to examine and modify active sessions.
 * /*w  w  w. j a va  2s  . c  o m*/
 * @param req The HTTP request.
 * @param res The HTTP response.
 * @throws ServletException If the processing fails.
 * @throws IOException If the connection fails.
 */
public synchronized void examine(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    String cmd = req.getParameter("cmd");
    String process = req.getParameter("process");
    String session = req.getParameter("session");
    String variable = req.getParameter("variable");
    String action = req.getParameter("action");
    String value = req.getParameter("value");
    Deployment deployment = null;
    if (process != null)
        deployment = deploymentsByPath.get(process);
    DeploymentSession deploymentSession = null;
    if (session != null)
        deploymentSession = deployment.getActiveSession(session);
    IDataObject parent = null, object = null;
    String fieldName = null;
    if (variable != null) {
        for (String token : variable.split("\\.")) {
            if (object == null)
                object = deploymentSession.getVariableRegistry().getVariable(token);
            else {
                parent = object;
                object = parent.getField(token);
            }
            fieldName = token;
        }
    }
    if ("unlock".equals(cmd)) {
        if (action.startsWith("Save")) {
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            if (object == null) {
                object = variables.createVariable(parent.getField(fieldName).getType());
                parent.setField(fieldName, object);
            }
            if (object instanceof IBooleanObject)
                ((IBooleanObject) object).setValue(value);
            else if (object instanceof IDateObject)
                ((IDateObject) object).setValue(value);
            else if (object instanceof IDecimalObject)
                ((IDecimalObject) object).setValue(value);
            else if (object instanceof INumberObject)
                ((INumberObject) object).setValue(value);
            else if (object instanceof IStringObject)
                ((IStringObject) object).setValue(value);
        }
        deploymentSession.unlock();
        res.sendRedirect(
                res.encodeRedirectURL("examine?cmd=variables&process=" + process + "&session=" + session));
    } else {
        String base = res.encodeURL("examine?cmd=");
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        out.println("<html><head><title>Runtime Examination</title></head><body>");
        if ("edit".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            deploymentSession.lock();
            out.println("<form action=\"examine\" method=\"post\">");
            out.println("<input type=\"hidden\" name=\"cmd\" value=\"unlock\" />");
            out.println("<input type=\"hidden\" name=\"process\" value=\"" + process + "\" />");
            out.println("<input type=\"hidden\" name=\"session\" value=\"" + session + "\" />");
            out.println("<input type=\"hidden\" name=\"variable\" value=\"" + variable + "\" />");
            out.println("<p>" + variable + " = ");
            out.println("<input type=\"text\" name=\"value\" value=\"");
            if (object != null)
                out.println(object.toString());
            out.println("\" /></p>");
            out.println("<p><input type=\"submit\" name=\"action\" value=\"Save & Unlock\" />&nbsp;");
            out.println("<input type=\"submit\" name=\"action\" value=\"Cancel & Unlock\" /></p>");
            out.println("</form>");
        } else if ("variables".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            out.println("<p>Select a variable to edit:</p><ul>");
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            String prefix = base + "edit&process=" + process + "&session=" + session + "&variable=";
            String[] variableNames = variables.getVariableNames();
            Arrays.sort(variableNames);
            for (String name : variableNames)
                examineVariable(out, prefix, name, variables.getVariable(name));
            out.println("</ul>");
        } else if ("sessions".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Select the session to examine:</p><ul>");
            for (DeploymentSession s : deployment.getActiveSessions()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("variables&process=");
                out.print(process);
                out.print("&session=");
                out.print(s.getSessionID());
                out.print("\">");
                out.print(s.getSessionID());
                out.print(" : ");
                out.print(s.getCurrentPosition());
                out.println("</a></li>");
            }
            out.println("</ul>");
        } else {
            out.println("<p>Select the application to examine:</p><ul>");
            for (Object o : deploymentsByPath.keySet()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("sessions&process=");
                out.print(o.toString());
                out.print("\">");
                out.print(o.toString());
                out.println("</a></li>");
            }
            out.println("</ul>");
        }
        out.println("</body></html>");
    }
}

From source file:org.inbio.ait.web.ajax.controller.TableController.java

/**
 * Return the XML with the results/*  w w w .j a  v a 2s  . c o  m*/
 * @param request
 * @param response
 * @param species
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, Long[][] matrix,
        List<SpeciesNode> species) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();

    StringBuilder result = new StringBuilder();
    result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
    result.append("<speciesList>");
    for (SpeciesNode sp : species) {
        result.append("<species>" + sp.getName() + "</species>");
    }
    result.append("</speciesList>");
    if (matrix.length > 0) {
        int rows = matrix.length;
        int columns = matrix[0].length;
        for (int i = 0; i < rows; i++) {
            result.append("<row>");
            for (int j = 0; j < columns; j++) {
                result.append("<column>" + matrix[i][j] + "</column>");
            }
            result.append("</row>");
        }
    }
    result.append("</response>");

    out.println(result.toString());
    out.flush();
    out.close();

    return null;
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    initialize(request);//from   w w w . j a  va2s .com

    int userId = 0;
    int groupId = 0;
    String user = "";
    String context = request.getContextPath();
    String url = request.getPathInfo();

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    try {
        //On initialise le dataProvider
        Connection c = null;
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // =====================================================================================
    boolean trace = false;
    StringBuffer outTrace = new StringBuffer();
    StringBuffer outPrint = new StringBuffer();
    String logFName = null;

    response.setCharacterEncoding("UTF-8");

    System.out.println("FileServlet::doGet");
    try {
        // ====== URI : /resources/file[/{lang}]/{context-id}
        // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo
        //         String uri = request.getRequestURI();
        String[] token = url.split("/");
        String uuid = token[1];
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri);

        /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder
        String sourceip = request.getRemoteAddr();
        System.out.println("IP: " + sourceip);

        /// Vrification des droits d'accs
        // TODO: Might be something special with proxy and export/PDF, to investigate
        if (!ourIPs.contains(sourceip)) {
            if (userId == 0)
                throw new RestWebApplicationException(Status.FORBIDDEN, "");

            if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid);
            }
        } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification
        {
            System.out.println("IP OK: bypass");
        }

        /// On rcupre le noeud de la ressource pour retrouver le lien
        String data = dataProvider.getResNode(uuid, userId, groupId);

        //         javax.servlet.http.HttpSession session = request.getSession(true);
        //====================================================
        //String ppath = session.getServletContext().getRealPath("/");
        //logFName = ppath +"logs/logNode.txt";
        //====================================================
        String size = request.getParameter("size");
        if (size == null)
            size = "S";

        String lang = request.getParameter("lang");
        if (lang == null) {
            lang = "fr";
        }

        /*
        String nodeUuid = uri.substring(uri.lastIndexOf("/")+1);
        if  (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. --
           lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/"));
        }
        //*/

        String ref = request.getHeader("referer");

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Trouve le bon noeud
        XPath xPath = XPathFactory.newInstance().newXPath();

        /// Either we have a fileid per language
        String filterRes = "//fileid[@lang='" + lang + "']";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);
        String resolve = "";
        if (nodelist.getLength() != 0) {
            Element fileNode = (Element) nodelist.item(0);
            resolve = fileNode.getTextContent();
        }

        /// Or just a single one shared
        if ("".equals(resolve)) {
            response.setStatus(404);
            return;
        }

        String filterName = "//filename[@lang='" + lang + "']";
        NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filename = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            filename = fileNode.getTextContent();
        }

        String filterType = "//type[@lang='" + lang + "']";
        textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET);
        String type = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            type = fileNode.getTextContent();
        }

        /*
        String filterSize = "//size[@lang='"+lang+"']";
        textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filesize = "";
        if( textList.getLength() != 0 )
        {
           Element fileNode = (Element) textList.item(0);
           filesize = fileNode.getTextContent();
        }
        //*/

        System.out.println("!!! RESOLVE: " + resolve);

        /// Envoie de la requte au servlet de fichiers
        // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql
        /// TODO: Ne plus avoir besoin du switch
        String urlTarget = "http://" + server + "/" + resolve;
        //         String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs";

        HttpURLConnection connection = CreateConnection(urlTarget, request);
        connection.connect();
        InputStream input = connection.getInputStream();
        String sizeComplete = connection.getHeaderField("Content-Length");
        int completeSize = Integer.parseInt(sizeComplete);

        response.setContentLength(completeSize);
        response.setContentType(type);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        ServletOutputStream output = response.getOutputStream();

        byte[] buffer = new byte[completeSize];
        int totalRead = 0;
        int bytesRead = -1;

        while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) {
            output.write(buffer, 0, bytesRead);
            totalRead += bytesRead;
        }

        //         IOUtils.copy(input, output);
        //         IOUtils.closeQuietly(output);

        output.flush();
        output.close();
        input.close();
        connection.disconnect();
    } catch (RestWebApplicationException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.toString() + " -> " + e.getLocalizedMessage());
        e.printStackTrace();
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e);
    } finally {
        try {
            dataProvider.disconnect();
        } catch (Exception e) {
            ServletOutputStream out = response.getOutputStream();
            out.println("Erreur dans doGet: " + e);
            out.close();
        }
    }
}

From source file:org.jspresso.framework.util.resources.server.ResourceProviderServlet.java

/**
 * {@inheritDoc}/*from   w ww  . j  a  v a2s.  c  o m*/
 */
@SuppressWarnings("unchecked")
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {

    try {
        HttpRequestHolder.setServletRequest(request);
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items = upload.parseRequest(request);
        response.setContentType("text/xml");
        ServletOutputStream out = response.getOutputStream();
        for (FileItem item : items) {
            if (!item.isFormField()) {
                out.print("<resource");
                IResourceBase uploadResource = new UploadResourceAdapter("application/octet-stream", item);
                String resourceId = ResourceManager.getInstance().register(uploadResource);
                out.print(" id=\"" + resourceId);
                // Sometimes prevents the browser to parse back the result
                // out.print("\" name=\"" + HtmlHelper.escapeForHTML(item.getName()));
                out.println("\" />");
            }
        }
        out.flush();
        out.close();
    } catch (Exception ex) {
        LOG.error("An unexpected error occurred while uploading the content.", ex);
    } finally {
        HttpRequestHolder.setServletRequest(null);
    }
}

From source file:com.iyonger.apm.web.controller.PerfTestController.java

/**
 * Show the given log for the perf test having the given id.
 *
 * @param id       test id/*from w  w w .  j a  v  a 2  s  .c  o m*/
 * @param path     path in the log folder
 * @param response response
 */
@RequestMapping(value = "/{id}/show_log/**")
public void showLog(@PathVariable("id") long id, @RemainedPath String path, HttpServletResponse response) {
    getOneWithPermissionCheck(getCurrentUser(), id, false);
    File targetFile = perfTestService.getLogFile(id, path);
    response.reset();
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(targetFile);
        ServletOutputStream outputStream = response.getOutputStream();
        if (FilenameUtils.isExtension(targetFile.getName(), "zip")) {
            // Limit log view to 1MB
            outputStream.println(" Only the last 1MB of a log shows.\n");
            outputStream
                    .println("==========================================================================\n\n");
            LogCompressUtils.decompress(fileInputStream, outputStream, 1 * 1024 * 1204);
        } else {
            IOUtils.copy(fileInputStream, outputStream);
        }
    } catch (Exception e) {
        CoreLogger.LOGGER.error("Error while processing log. {}", targetFile, e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:org.inbio.ait.web.ajax.controller.ExportCsvController.java

private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<Specimen> specimens) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();

    //String documento = "";
    StringBuilder documento = new StringBuilder();
    documento.append(//  w  w  w. j av a2s .  c  o m
            "<table class=\"contacts\" cellspacing=\"0\"><tr><th class=\"species\">Nombre cientfico</th><th class=\"species\">Longitud</th><th class=\"species\">Latitud</th><th class=\"species\"># de catlogo</th><th class=\"species\">Institucin</th>");

    for (Specimen s : specimens) {
        documento.append("<tr>");
        documento.append("<td class=\"contact\">" + s.getScientificname() + "</td>");
        documento.append("<td class=\"contact\">" + s.getDecimallongitude() + "</td>");
        documento.append("<td class=\"contact\">" + s.getDecimallatitude() + "</td>");
        documento.append("<td class=\"contact\">" + s.getCatalognumber() + "</td>");
        documento.append("<td class=\"contact\">" + s.getInstitutioncode() + "</td>");
        documento.append("<tr>");
    }
    documento.append("</table>");

    out.println(documento.toString());
    out.flush();
    out.close();

    return null;
}