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:com.indeed.imhotep.web.QueryServlet.java

private void handleDescribeField(HttpServletRequest req, HttpServletResponse resp,
        DescribeStatement parsedQuery) throws IOException {
    final ServletOutputStream outputStream = resp.getOutputStream();
    final String dataset = parsedQuery.dataset;
    final String fieldName = parsedQuery.field;
    final List<String> topTerms = topTermsCache.getTopTerms(dataset, fieldName);
    FieldMetadata field = metadata.getDataset(dataset).getField(fieldName);
    if (field == null) {
        field = new FieldMetadata("notfound", FieldType.String);
        field.setDescription("Field not found");
    }//from www. j a va2 s .c om
    final boolean json = req.getParameter("json") != null;
    if (json) {
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        final ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        final ObjectNode jsonRoot = mapper.createObjectNode();
        field.toJSON(jsonRoot);

        final ArrayNode termsArray = mapper.createArrayNode();
        jsonRoot.put("topTerms", termsArray);
        for (String term : topTerms) {
            termsArray.add(term);
        }
        mapper.writeValue(outputStream, jsonRoot);
    } else {
        for (String term : topTerms) {
            outputStream.println(term);
        }
    }
    outputStream.close();
}

From source file:org.openlaszlo.servlets.HistoryServlet.java

private void doSendHistory(HttpServletRequest req, HttpServletResponse res, Document doc) {
    mLogger.info("doSendHistory");
    Element el = doc.getRootElement().getChild("root").getChild("history");

    ServletOutputStream out = null;
    GetMethod request = null;/*from   w w  w  .  j a  v a  2  s .c  om*/
    String status = null;
    String body = null;
    try {
        out = res.getOutputStream();

        request = new MyGetMethod();

        String url = mURL + "?lzt=agentmessage" + "&url=" + URLEncoder.encode(mAgentURL) + "&group="
                + mAgentGroup + "&to=*&range=user" + "&dset=" + mClientDataset + "&msg="
                + URLEncoder.encode(getXMLHistory());

        mLogger.debug("url: " + url);
        URI uri = new URI(url.toCharArray());
        HostConfiguration hcfg = new HostConfiguration();
        hcfg.setHost(uri);

        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();

        mLogger.debug("path: " + path);
        mLogger.debug("query: " + query);

        request.setPath(path);
        request.setQueryString(query);

        HttpClient htc = new HttpClient(mConnectionMgr);
        htc.setHostConfiguration(hcfg);
        int rc = htc.executeMethod(hcfg, request);

        status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug("remote response status: " + status);

        body = request.getResponseBodyAsString();

        mLogger.debug("response body: " + body);
    } catch (HttpRecoverableException e) {
        mLogger.debug("HttpRecoverableException: " + e.getMessage());
        sendError(out, "<status message=\"HttpRecoverableException " + e.getMessage() + "\" />");
    } catch (HttpException e) {
        mLogger.debug("HttpException: " + e.getMessage());
        sendError(out, "<status message=\"HttpException " + e.getMessage() + "\" />");
    } catch (IOException e) {
        mLogger.debug("IOException: " + e.getMessage());
        sendError(out, "<status message=\"IOException " + e.getMessage() + "\" />");
    } finally {
        if (request != null) {
            request.releaseConnection();
        }
    }

    try {
        if (status != null && status.equals("OK")) {
            out.println("<status message=\"ok\">" + (body != null ? body : "") + "</status>");
        } else {
            out.println("<status message=\"" + mURL + "?lzt=agentmessage" + " " + status + "\" />");
        }
        out.flush();
    } catch (IOException e) {
        mLogger.debug("Client IOException");
        // ignore client ioexception
    } finally {
        close(out);
    }
}

From source file:it.cnr.icar.eric.server.interfaces.rest.QueryManagerURLHandler.java

@SuppressWarnings("unused")
private void writeDirectoryListingItem(ServletOutputStream os, RegistryObjectType ebRegistryObjectType)
        throws IOException, RegistryException {
    String baseURL = getBaseUrl();
    String reqId = request.getParameter("param-id");
    String reqLid = request.getParameter("param-lid");
    String reqVersionName = request.getParameter("param-versionName");
    String method = request.getParameter("method");

    String id = ebRegistryObjectType.getId();
    String name = getClosestValue(ebRegistryObjectType.getName());
    String desc = getClosestValue(ebRegistryObjectType.getDescription());
    String lid = ebRegistryObjectType.getLid();
    ServerRequestContext context = new ServerRequestContext("QueryManagerURLHandler.writeDirectoryListingItem",
            null);/*from  w  w  w.java 2  s.  com*/
    ClassificationNodeType node = (ClassificationNodeType) qm.getRegistryObject(context,
            ebRegistryObjectType.getObjectType());
    String objectType = node.getCode();
    VersionInfoType versionInfo = ebRegistryObjectType.getVersionInfo();
    VersionInfoType contentVersionInfo = null;

    String versionName = versionInfo.getVersionName();
    String contentVersionName = "";
    if (ebRegistryObjectType instanceof ExtrinsicObjectType) {
        ExtrinsicObjectType eo = (ExtrinsicObjectType) ebRegistryObjectType;
        contentVersionInfo = eo.getContentVersionInfo();
        if (contentVersionInfo != null) {
            contentVersionName = contentVersionInfo.getVersionName();
        }
    }

    String roURL = baseURL + "?interface=QueryManager&method=getRegistryObject&";
    if (reqId != null) {
        roURL += "param-id=" + id;
    } else if (reqLid != null) {
        roURL += "param-lid=" + lid + "&param-versionName=" + versionName;
    }

    String riURL = baseURL + "?interface=QueryManager&method=getRepositoryItem&";
    if (reqId != null) {
        riURL += "param-id=" + id;
    } else if (reqLid != null) {
        riURL += "param-lid=" + lid + "&param-versionName=" + versionName;
    }

    os.println(objectType + "\t\t" + name + "\t\t<a href=\"" + roURL + "\">" + versionName
            + "</a>\t\t<a href=\"" + riURL + "\">" + contentVersionName + "</a>\t\t" + lid + "<br/>");
}

From source file:gov.nih.nci.system.web.HTTPQuery.java

/**
 * Handles Get requests/*from  ww  w.  jav a 2 s . com*/
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletOutputStream out = response.getOutputStream();
    out = response.getOutputStream();

    Object[] resultSet = null;
    int pageNumber = 1;

    ApplicationService applicationService = (ApplicationService) ctx.getBean("ApplicationServiceImpl");
    ClassCache classCache = (ClassCache) ctx.getBean("ClassCache");
    HibernateConfigurationHolder configurationHolder = (HibernateConfigurationHolder) ctx
            .getBean("HibernateConfigHolder");
    HTTPUtils httpUtils = new HTTPUtils(applicationService, classCache, pageSize, configurationHolder);
    String queryType = httpUtils.getQueryType(request.getRequestURL().toString());

    String query = null;

    try {
        if (URLDecoder.decode(request.getQueryString(), "ISO-8859-1") != null) {
            query = URLDecoder.decode(request.getQueryString(), "ISO-8859-1");
        } else {
            throw new Exception("Query not defined" + getQuerySyntax());
        }
        if (query.indexOf("&username") > 0)
            query = query.substring(0, query.indexOf("&username"));

        validateQuery(query);
        httpUtils.setQueryArguments(query);

        if (httpUtils.getPageNumber() != null) {
            pageNumber = Integer.parseInt(httpUtils.getPageNumber());
        }
        httpUtils.setServletName(request.getRequestURL().toString());

        if (httpUtils.getPageSize() != null) {
            //FIX for pagesize being reset by the end user
            //pageSize = Integer.parseInt(httpUtils.getPageSize());
        } else {
            httpUtils.setPageSize(pageSize);
        }

        try {
            resultSet = httpUtils.getResultSet();
        } catch (Exception ex) {
            log.error("Get ResultSet Exception: " + ex.getMessage());
            throw ex;
        }
        executeFormatOutput(response, out, resultSet, pageNumber, httpUtils, queryType);
    } catch (Exception ex) {
        log.error("Exception: ", ex);

        if (queryType.endsWith("XML")) {
            response.setContentType("text/xml");

            out.println(getXMLErrorMsg(ex, query));
        } else {
            response.setContentType("text/html");
            out.println(getHTMLErrorMsg(ex));
        }
        // Need to add JSON error output???
    }

}

From source file:com.gae.ImageUpServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    //ReturnValue value = new ReturnValue();
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    resp.setContentType("image/jpeg");
    ServletOutputStream out = resp.getOutputStream();
    try {//from   w  w  w .  jav a2  s .  c  om
        List<FileItem> list = upload.parseRequest(req);
        //FileItem list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                filename = item.getName();
                if (filename != null && !"".equals(filename)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image newImage = ImagesServiceFactory.makeImage(data);
                    byte[] newImageData = newImage.getImageData();

                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   
                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   

                    out.write(newImageData);
                    out.flush();

                    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    Key key = KeyFactory.createKey(kind, skey);
                    Blob blobImage = new Blob(newImageData);
                    DirectBeans_textjson dbeans = new DirectBeans_textjson();
                    /*  ?Date?     */
                    //Entity entity = dbeans.setentity("add", kind, true, key, id, val);

                    //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val);
                    //Entity entity = value.entity;
                    //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue();
                    DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val);
                    Entity entity = eval.entity;

                    /*  ?Date                         */
                    //for(int i=0; i<id.length; i++ ){
                    //   if(id[i].equals("image")){
                    //      //filetitle = val[i];
                    //      //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
                    //   }
                    //}                

                    entity.setProperty("image", blobImage);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss");
                    sdf.setTimeZone(TimeZone.getTimeZone("JST"));
                    entity.setProperty("moddate", sdf.format(date));
                    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    ds.put(entity);
                    out.println("? KEY:" + key);
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.exist.security.realm.openid.AuthenticatorOpenIdServlet.java

public String authRequest(String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
        throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
        ServletOutputStream out = httpResp.getOutputStream();
        httpResp.setContentType("text/html; charset=\"UTF-8\"");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        out.print("<html><head>");
        out.print("<title>OpenIDServlet Error</title>");
        out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
        out.print("<body><div id=\"container\"><h1>Error found</h1>");

        out.print("<h2>Message:");
        out.print("OpenID realm wasn't initialized.");
        out.print("</h2>");

        //out.print(HTTPUtils.printStackTraceHTML(t));

        out.print("</div></body></html>");
        return null;
    }/*  ww w  .ja  v a 2s  .  c om*/
    try {
        String returnAfterAuthentication = httpReq.getParameter("return_to");

        // configure the return_to URL where your application will receive
        // the authentication responses from the OpenID provider
        String returnToUrl = httpReq.getRequestURL().toString() + "?is_return=true&exist_return="
                + returnAfterAuthentication;

        // perform discovery on the user-supplied identifier
        List<?> discoveries = manager.discover(userSuppliedString);

        // attempt to associate with the OpenID provider
        // and retrieve one service endpoint for authentication
        DiscoveryInformation discovered = manager.associate(discoveries);

        // store the discovery information in the user's session
        httpReq.getSession().setAttribute("openid-disc", discovered);

        // obtain a AuthRequest message to be sent to the OpenID provider
        AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

        if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
            SRegRequest sregReq = SRegRequest.createFetchRequest();

            sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

            authReq.addExtension(sregReq);
        } else {

            FetchRequest fetch = FetchRequest.createFetchRequest();

            fetch.addAttribute(AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

            // wants up to three email addresses
            fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

            authReq.addExtension(fetch);
        }

        if (!discovered.isVersion2()) {
            // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
            // The only method supported in OpenID 1.x
            // redirect-URL usually limited ~2048 bytes
            httpResp.sendRedirect(authReq.getDestinationUrl(true));
            return null;

        } else {
            // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

            Object OPEndpoint = authReq.getDestinationUrl(false);

            ServletOutputStream out = httpResp.getOutputStream();

            httpResp.setContentType("text/html; charset=UTF-8");
            httpResp.addHeader("pragma", "no-cache");
            httpResp.addHeader("Cache-Control", "no-cache");

            out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            out.println("<head>");
            out.println("    <title>OpenID HTML FORM Redirection</title>");
            out.println("</head>");
            out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
            out.println("    <form name=\"openid-form-redirection\" action=\"" + OPEndpoint
                    + "\" method=\"post\" accept-charset=\"utf-8\">");

            Map<String, String> parameterMap = authReq.getParameterMap();
            for (Entry<String, String> entry : parameterMap.entrySet()) {
                out.println("   <input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\""
                        + entry.getValue() + "\"/>");
            }

            out.println("        <button type=\"submit\">Continue...</button>");
            out.println("    </form>");
            out.println("</body>");
            out.println("</html>");

            out.flush();
        }
    } catch (OpenIDException e) {
        // present error to the user
        LOG.debug("OpenIDException", e);

        ServletOutputStream out = httpResp.getOutputStream();
        httpResp.setContentType("text/html; charset=\"UTF-8\"");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        out.print("<html><head>");
        out.print("<title>OpenIDServlet Error</title>");
        out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
        out.print("<body><div id=\"container\"><h1>Error found</h1>");

        out.print("<h2>Message:");
        out.print(e.getMessage());
        out.print("</h2>");

        Throwable t = e.getCause();
        if (t != null) {
            // t can be null
            out.print(HTTPUtils.printStackTraceHTML(t));
        }

        out.print("</div></body></html>");
    }

    return null;
}

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//w  ww  .  j  a  v  a 2  s.c o  m
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetPatientServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * /*from   w w w.  ja v  a  2s  .  c om*/
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@Override
public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
        Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;
    for (String indicator : indicatorsList.keySet()) {
        count++;
        outputStream.println(
                count + " , " + indicator.toString() + " , " + indicatorsList.get(indicator).toString());
    }

    outputStream.flush();
    outputStream.close();
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * //from   w  w w.  ja  va2  s  .  com
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@SuppressWarnings("unchecked")
@Override
public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
        Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;

    List<String> indicator_msg = null;

    indicator_msg = (ArrayList<String>) request.getSession().getAttribute(request.getParameter("id") + "_msg");

    for (String indicator : indicatorsList.keySet()) {
        count++;
        outputStream.println(indicator.toString().substring(4) + " , " + indicator_msg.get(count - 1) + " , "
                + indicatorsList.get(indicator).toString());
    }

    outputStream.flush();
    outputStream.close();
}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

/**
 * Exports data to the CSV File or Text File
 * //w  w w . ja v a  2 s .co m
 * @throws IOException
 * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
 */
@Override
public void exportPatientsListToCsvFile(HttpServletRequest request, HttpServletResponse response,
        List<Person> patientsList, String filename, String title, String startDate, String endDate)
        throws IOException {

    Session session = getSessionFactory().getCurrentSession();
    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
    outputStream.println();
    outputStream.println("# , Indicator Name , Indicator");
    outputStream.println();
    int count = 0;

    for (Person person : patientsList) {

        Date maxEncounterDateTime = (Date) session
                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where patient_id = "
                        + person.getPersonId())
                .uniqueResult();

        Date maxReturnVisitDay = (Date) session
                .createSQLQuery("select cast(max(value_datetime) as DATE ) " + "from obs where concept_id = "
                        + ConstantValues.NEXT_SCHEDULED_VISIT + " and person_id = " + person.getPersonId())
                .uniqueResult();

        count++;
        outputStream.println(count + " , " + person.getPersonId() + " , " + person.getFamilyName() + " "
                + person.getGivenName() + " , " + person.getGender() + " , " + maxEncounterDateTime.toString()
                + " , " + maxReturnVisitDay.toString());
    }

    outputStream.flush();
    outputStream.close();
}