Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:com.hp.avmon.config.web.AgentController.java

/**
 * ?Agent//from w w w .  j a v a2 s  .c om
 * @param request
 * @param writer
 */
@RequestMapping(value = "/startAgent")
public void startAgent(HttpServletRequest request, PrintWriter writer) {
    String json = "";
    try {
        json = agentManageService.startAgent(request);
        writer.write(json);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error(this.getClass().getName() + e.getMessage());
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:com.hp.avmon.kpigetconfig.web.KpigetconfigAgentController.java

@RequestMapping(value = "/pushAmpSchedule")
public void pushAmpSchedule(HttpServletRequest request, PrintWriter writer) {
    Map map = agentManageService.pushAmpSchedule(request);
    String jsonData = JackJson.fromObjectToJson(map);
    logger.debug("findAgentSchedue: " + jsonData);
    writer.write(jsonData);
    writer.flush();/*from  w ww.  j a  v a2  s.  c om*/
    writer.close();
}

From source file:com.hp.avmon.config.web.AgentController.java

/**
 * Agent/*  w  w w .ja  v a  2s  .  c  om*/
 * @param request
 * @param writer
 */
@RequestMapping(value = "/removeAgent")
public void removeAgent(HttpServletRequest request, PrintWriter writer) {
    String json = "";
    try {
        json = agentManageService.removeAgent(request);
        writer.write(json);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error(this.getClass().getName() + e.getMessage());
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:edu.ku.brc.specify.utilapps.RegProcessor.java

/**
 * @param urlKey//from w w  w .  j  a v  a  2  s .  co m
 * @param inclDmp
 * @return
 */
public File getDataFromWeb(final String urlKey, final boolean inclDmp) {
    try {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter("http.useragent", RegisterSpecify.class.getName()); //$NON-NLS-1$

        String urlStr = UIRegistry.getResourceString(urlKey);

        PostMethod postMethod = new PostMethod(urlStr + (inclDmp ? "?dmp=1&" : ""));

        // connect to the server
        try {
            httpClient.executeMethod(postMethod);

            InputStream iStream = postMethod.getResponseBodyAsStream();

            File tempFile = File.createTempFile("web", "data");
            byte[] bytes = new byte[8196];

            PrintWriter pw = new PrintWriter(tempFile);
            int numBytes = 0;
            do {
                numBytes = iStream.read(bytes);
                if (numBytes > 0) {
                    pw.write(new String(bytes, 0, numBytes));
                }

            } while (numBytes > 0);

            pw.close();

            return tempFile;
        } catch (Exception e) {
            //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(RegProcessor.class, e);
            e.printStackTrace();
            throw new ConnectionException(e);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:edu.vt.vbi.patric.portlets.WorkspacePortlet.java

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    String action_type = request.getParameter("action_type");
    String action = request.getParameter("action");

    if (action_type != null && action != null) {

        if (action_type.equals("WSSupport")) {

            switch (action) {
            case "inlinestatus": {

                String linkWorkspace = "";
                if (isLoggedIn(request)) {
                    linkWorkspace = "<a class=\"arrow-white-e\" href=\"/workspace/\">WORKSPACE: HOME</a>";
                }//  w  w w.  j  a va  2  s . c o m

                response.setContentType("text/plain");
                PrintWriter writer = response.getWriter();
                writer.write(linkWorkspace);
                writer.close();
                break;
            }
            case "getGenomeGroupList": {
                JSONArray res = new JSONArray();

                if (isLoggedIn(request)) {
                    String token = getAuthorizationToken(request);
                    String pathGenomeGroup = getUserWorkspacePath(request, DEFAULT_WORKSPACE_NAME)
                            + "/Genome Groups";

                    try {
                        DataApiHandler dataApi = new DataApiHandler(request);
                        Workspace serviceWS = new Workspace(WORKSPACE_API_URL, token);
                        list_params params = new list_params();
                        params.paths = Arrays.asList(pathGenomeGroup);
                        Map<String, List<ObjectMeta>> resp = serviceWS.ls(params);

                        List<ObjectMeta> groupList = resp.get(pathGenomeGroup);

                        // sort by name
                        Comparator comparator = new GenomeGroupNameComparator();
                        Collections.sort(groupList, comparator);

                        JSONParser jsonParser = new JSONParser();

                        for (ObjectMeta group : groupList) {
                            LOGGER.trace("reading: {},{},{},{},{},{},{}", group.e_1, group.e_2, group.e_3,
                                    group.e_5, group.e_7, group.e_8, group.e_9);

                            if ("genome_group".equals(group.e_2)) {
                                JSONObject grp = new JSONObject();
                                String genomeGroupId = group.e_5; // e_5, object id
                                grp.put("id", genomeGroupId);
                                grp.put("name", group.e_1); // e_1, object name
                                grp.put("leaf", false);
                                grp.put("collapsed", true);

                                JSONArray children = new JSONArray();
                                // get genome associated in this group
                                get_params gp = new get_params();
                                gp.objects = Arrays.asList(group.e_3 + group.e_1); // e_3, path
                                gp.metadata_only = 0;
                                gp.adminmode = 0;

                                LOGGER.trace("requesting.. {}", group.e_3 + group.e_1);

                                try {
                                    List<Workspace_tuple_2> r = serviceWS.get(gp);

                                    for (Workspace_tuple_2 item : r) {
                                        if (item.e_2 != null) {

                                            JSONObject groupInfo = (JSONObject) jsonParser.parse(item.e_2); // objectMeta
                                            List<String> genomeIdList = (List<String>) ((JSONObject) groupInfo
                                                    .get("id_list")).get("genome_id");
                                            Set<String> genomeIdSet = new HashSet<>(genomeIdList);
                                            genomeIdSet.remove("");

                                            SolrQuery query = new SolrQuery("genome_id:("
                                                    + StringUtils.join(genomeIdSet, " OR ") + ")");
                                            query.setRows(10000).addField("genome_id,genome_name,taxon_id");

                                            LOGGER.trace("[{}] {}", SolrCore.GENOME.getSolrCoreName(), query);
                                            String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);
                                            Map respApi = jsonReader.readValue(apiResponse);
                                            Map respBody = (Map) respApi.get("response");
                                            List<Genome> genomes = dataApi.bindDocuments(
                                                    (List<Map>) respBody.get("docs"), Genome.class);

                                            Map<String, Genome> genomeHash = new LinkedHashMap<>();
                                            for (Genome g : genomes) {
                                                genomeHash.put(g.getId(), g);
                                            }

                                            for (String genomeId : genomeIdSet) {
                                                Genome genome = genomeHash.get(genomeId);

                                                if (genome != null) {
                                                    JSONObject leafGenome = new JSONObject();
                                                    leafGenome.put("id", genomeId);
                                                    leafGenome.put("parentID", genomeGroupId);
                                                    leafGenome.put("name", genome.getGenomeName());
                                                    leafGenome.put("leaf", true);
                                                    leafGenome.put("genome_id", genomeId);
                                                    leafGenome.put("taxon_id", genome.getTaxonId());

                                                    children.add(leafGenome);
                                                }
                                            }
                                        }
                                    }

                                    grp.put("children", children);
                                    res.add(grp);
                                } catch (Exception ex) {
                                    LOGGER.error(ex.getMessage(), ex);
                                }
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                res.writeJSONString(writer);
                writer.close();
                break;
            }
            case "getGroupList": {
                String grp_type = request.getParameter("group_type");
                JSONArray res = new JSONArray();

                String grp_path = getUserWorkspacePath(request, DEFAULT_WORKSPACE_NAME);
                String grp_obj_type;
                switch (grp_type) {
                case "Genome":
                    grp_path += "/Genome Groups";
                    grp_obj_type = "genome_group";
                    break;
                case "Feature":
                    grp_path += "/Feature Groups";
                    grp_obj_type = "feature_group";
                    break;
                case "ExpressionExperiment":
                    grp_path += "/Experiment Groups";
                    grp_obj_type = "experiment_group";
                    break;
                default:
                    grp_obj_type = "";
                    //
                }

                String token = getAuthorizationToken(request);
                Workspace serviceWS = new Workspace(WORKSPACE_API_URL, token);
                list_params params = new list_params();
                params.paths = Arrays.asList(grp_path);

                try {
                    Map<String, List<ObjectMeta>> resp = serviceWS.ls(params);
                    List<ObjectMeta> groupList = resp.get(grp_path);

                    for (ObjectMeta group : groupList) {
                        String groupId = group.e_5; // e_5, object id
                        String groupName = group.e_1; // e_1, object name
                        // TODO: how to read group description???

                        if (grp_obj_type.equals(group.e_2)) {
                            JSONObject grp = new JSONObject();
                            grp.put("name", groupName);
                            grp.put("description", "");
                            grp.put("tag", "");
                            grp.put("id", groupId);

                            res.add(grp);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                res.writeJSONString(writer);
                writer.close();
                break;
            }
            default:
                response.setContentType("application/json");
                response.getWriter().write("sorry");
                response.getWriter().close();
                break;
            }
        } else if (action_type.equals("GSESupport")) {
            //            if (action.equals("group_list")) {
            //               // PersistentCartGroup group = null;
            //               JSONArray groups = ws.getGroups();
            //               StringBuilder output = new StringBuilder();
            //
            //               output.append("<group_set>\n");
            //               for (Object aGroup : groups) {
            //                  JSONObject group = (JSONObject) aGroup;
            //
            //                  output.append("\t<group>\n");
            //                  output.append("\t\t<idx>").append(group.get("tagId")).append("</idx>\n");
            //                  output.append("\t\t<name>").append(group.get("name")).append("</name>\n");
            //                  output.append("\t</group>\n");
            //               }
            //               output.append("</group_set>");
            //
            //               response.setContentType("text/xml");
            //               response.getWriter().write(output.toString());
            //               response.getWriter().close();
            //            }
            //            else if (action.equals("groups")) {
            //               String strTagIds = request.getParameter("groupIds");
            //               JSONObject filter = new JSONObject();
            //               filter.put("key", "tagId");
            //               filter.put("value", strTagIds);
            //
            //               JSONArray groups = ws.getGroups(filter);
            //               StringBuilder o = new StringBuilder();
            //
            //               o.append("<group_set>\n");
            //
            //               for (Object aGroup : groups) {
            //                  JSONObject group = (JSONObject) aGroup;
            //
            //                  o.append("\t<group>\n");
            //                  o.append("\t\t<name>").append(group.get("name")).append("</name>\n");
            //                  o.append("\t\t<description>").append(((group.get("desc") != null) ? group.get("desc") : "")).append("</description>\n");
            //                  o.append("\t\t<members>\n");
            //
            //                  List<JSONObject> members = ws.findMappingByTagId(Integer.parseInt(group.get("tagId").toString()));
            //
            //                  Set<Integer> trackIds = new HashSet<>();
            //                  for (JSONObject member : members) {
            //                     trackIds.add(Integer.parseInt(member.get("trackId").toString()));
            //                  }
            //                  JSONArray tracks = ws.getTracks(trackIds);
            //                  for (Object track : tracks) {
            //                     JSONObject member = (JSONObject) track;
            //                     o.append(member.get("internalId")).append("\n");
            //                  }
            //
            //                  o.append("\t\t</members>\n");
            //                  o.append("\t</group>\n");
            //               }
            //               o.append("</group_set>");
            //
            //               //
            //               response.setContentType("text/xml");
            //               response.getWriter().write(o.toString());
            //               response.getWriter().close();
            //            }
            //            else if (action.equals("items")) {
            //
            //               Set<Integer> trackIds = new HashSet<>();
            //               String strTagIds = request.getParameter("groupIds");
            //               String groupType;
            //               String _tagId = null;
            //
            //               if (strTagIds.contains(",")) {
            //                  for (String tagId : strTagIds.split(",")) {
            //                     List<JSONObject> mappings = ws.findMappingByTagId(Integer.parseInt(tagId));
            //                     for (JSONObject mapping : mappings) {
            //                        trackIds.add(Integer.parseInt(mapping.get("trackId").toString()));
            //                     }
            //                     _tagId = tagId;
            //                  }
            //               }
            //               else {
            //                  List<JSONObject> mappings = ws.findMappingByTagId(Integer.parseInt(strTagIds));
            //                  for (JSONObject mapping : mappings) {
            //                     trackIds.add(Integer.parseInt(mapping.get("trackId").toString()));
            //                  }
            //                  _tagId = strTagIds;
            //               }
            //
            //               JSONArray tracks = ws.getTracks(trackIds);
            //
            //               // get group type
            //               JSONObject filter = new JSONObject();
            //               filter.put("key", "tagId");
            //               filter.put("value", _tagId);
            //               JSONArray gr = ws.getTags(filter);
            //               groupType = ((JSONObject) gr.get(0)).get("type").toString();
            //
            //               JSONObject res;
            //               Map<String, Object> key = new HashMap<>();
            //               key.put("tracks", tracks);
            //
            //               StringBuilder out_sb = new StringBuilder();
            //
            //               if (groupType.equals("Feature")) {
            //                  res = solr.getFeaturesByID(key);
            //                  JSONArray items = (JSONArray) res.get("results");
            //
            //                  out_sb.append(
            //                        "Feature ID\tGenome Name\tAccession\tPATRIC ID\tRefSeq Locus Tag\tAlt Locus Tag\tAnnotation\tFeature Type\tStart\tEnd\tLength(NT)\tStrand\t");
            //                  out_sb.append("Protein Id\tLength(AA)\tGene Symbol\tProduct\n");
            //
            //                  for (Object aItem : items) {
            //                     JSONObject item = (JSONObject) aItem;
            //                     out_sb.append(item.get("feature_id")).append("\t");
            //                     out_sb.append(item.get("genome_name")).append("\t");
            //                     out_sb.append(item.get("accession")).append("\t");
            //                     out_sb.append(item.get("seed_id")).append("\t");
            //                     out_sb.append((item.get("refseq_locus_tag") != null ? item.get("refseq_locus_tag") : "")).append("\t");
            //                     out_sb.append((item.get("alt_locus_tag") != null ? item.get("alt_locus_tag") : "")).append("\t");
            //                     out_sb.append(item.get("annotation")).append("\t");
            //                     out_sb.append(item.get("feature_type")).append("\t");
            //                     out_sb.append(item.get("start")).append("\t");
            //                     out_sb.append(item.get("end")).append("\t");
            //                     out_sb.append(item.get("na_length")).append("\t");
            //                     out_sb.append(item.get("strand")).append("\t");
            //                     out_sb.append((item.get("protein_id") != null ? item.get("protein_id") : "")).append("\t");
            //                     out_sb.append(item.get("aa_length")).append("\t");
            //                     out_sb.append((item.get("gene") != null ? item.get("gene") : "")).append("\t");
            //                     out_sb.append(item.get("product")).append("\n");
            //                  }
            //               }
            //               else if (groupType.equals("Genome")) {
            //                  res = solr.getGenomesByID(key);
            //                  JSONArray items = (JSONArray) res.get("results");
            //
            //                  out_sb.append("Genome ID\tGenome Name\tStatus\tHost\tDisease\tIsolation Country\tCollection Date\tCompletion Date\n");
            //
            //                  for (Object aItem : items) {
            //                     JSONObject item = (JSONObject) aItem;
            //                     out_sb.append(item.get("genome_id")).append("\t");
            //                     out_sb.append(item.get("genome_name")).append("\t");
            //                     out_sb.append(item.get("genome_status")).append("\t");
            //                     out_sb.append((item.get("host_name") != null ? item.get("host_name") : "")).append("\t");
            //                     out_sb.append((item.get("disease") != null ? item.get("disease") : "")).append("\t");
            //                     out_sb.append((item.get("isolation_country") != null ? item.get("isolation_country") : "")).append("\t");
            //                     out_sb.append((item.get("collection_date") != null ? item.get("collection_date") : "")).append("\t");
            //                     out_sb.append((item.get("completion_date") != null ? item.get("completion_date") : "")).append("\n");
            //                  }
            //               }
            //               else if (groupType.equals("ExpressionExperiment")) {
            //                  List<String> collectionIds = new ArrayList<>();
            //
            //                  JSONArray exptracks;
            //                  JSONArray tracksPATRIC = new JSONArray();
            //
            //                  if (key.containsKey("tracks")) {
            //                     exptracks = (JSONArray) key.get("tracks");
            //
            //                     if (exptracks.size() > 0) {
            //                        for (Object exptrack : exptracks) {
            //                           JSONObject tr = (JSONObject) exptrack;
            //                           try {
            //                              Integer.parseInt(tr.get("internalId").toString());
            //                              tracksPATRIC.add(tr);
            //                           }
            //                           catch (NumberFormatException nfe) {
            //                              collectionIds.add(tr.get("internalId").toString());
            //                           }
            //                        }
            //                     }
            //                  }
            //
            //                  out_sb.append("Experiment Id\tSource\tTitle\tData Type\tAccession\n");
            //
            //                  if (tracksPATRIC.size() > 0) {
            //                     Map<String, Object> keyPATRIC = new HashMap<>();
            //                     keyPATRIC.put("tracks", tracksPATRIC);
            //                     res = solr.getExperimentsByID(keyPATRIC);
            //
            //                     JSONArray items = (JSONArray) res.get("results");
            //                     for (Object aItem : items) {
            //                        JSONObject item = (JSONObject) aItem;
            //                        out_sb.append(item.get("expid")).append("\t");
            //                        out_sb.append("PATRIC\t");
            //                        out_sb.append(item.get("title")).append("\t");
            //                        out_sb.append("Transcriptomics\t"); // TODO: modify later
            //                        out_sb.append((item.get("accession") != null ? item.get("accession") : "")).append("\n");
            //                     }
            //                  }
            //
            //                  if (collectionIds.size() > 0) {
            //                     PolyomicHandler polyomic = getPolyomicHandler(request);
            //                     res = polyomic.getExperiments(collectionIds);
            //
            //                     JSONArray items = (JSONArray) res.get("results");
            //                     for (Object aItem : items) {
            //                        JSONObject item = (JSONObject) aItem;
            //                        out_sb.append(item.get("expid")).append("\t");
            //                        out_sb.append("me\t");
            //                        out_sb.append(item.get("title")).append("\t");
            //                        out_sb.append((item.get("data_type") != null ? item.get("data_type") : "")).append("\t");
            //                        out_sb.append((item.get("accession") != null ? item.get("accession") : "")).append("\n");
            //                     }
            //                  }
            //               }
            //               else {
            //                  // error
            //               }
            //
            //               response.setContentType("text/plain");
            //               response.getWriter().write(out_sb.toString());
            //               response.getWriter().close();
            //            }
        } else if (action_type.equals("LoginStatus")) {
            if (action.equals("getLoginStatus")) {
                if (!isLoggedIn(request)) {
                    response.setContentType("text/plain");
                    response.getWriter().write("false");
                    response.getWriter().close();
                } else {
                    response.setContentType("text/plain");
                    response.getWriter().write("true");
                    response.getWriter().close();
                }
            }
        } else if (action_type.equals("HTTPProvider")) {

            UIPreference uiPref = getValidUIPreference(request);

            switch (action) {
            case "storage":
                if (request.getMethod().equals("GET")) {

                    String strUIPref = uiPref.getStateList().toJSONString();

                    response.getWriter().write(strUIPref);
                    response.getWriter().close();
                } else if (request.getMethod().equals("POST")) {

                    JSONParser parser = new JSONParser();
                    JSONObject param;
                    JSONArray params;
                    try {
                        Object rt = parser.parse(request.getReader());
                        if (rt instanceof JSONObject) {
                            param = (JSONObject) rt;
                            uiPref.setState(param);
                        } else if (rt instanceof JSONArray) {
                            params = (JSONArray) rt;
                            uiPref.setStateList(params);
                        } else {
                            LOGGER.error(rt.toString());
                        }

                        this.saveUIPreference(request, uiPref);
                    } catch (ParseException e) {
                        LOGGER.error(e.getMessage(), e);
                    }

                    response.getWriter().write("");
                    response.getWriter().close();
                }
                break;
            case "remove":
                if (request.getParameter("name") != null) {
                    uiPref.resetState(request.getParameter("name"));
                    this.saveUIPreference(request, uiPref);
                }

                response.getWriter().write("");
                response.getWriter().close();
                break;
            case "reset":
                uiPref.reset();
                this.saveUIPreference(request, uiPref);

                response.getWriter().write("");
                response.getWriter().close();
                break;
            }
        }
    }
}

From source file:com.hp.avmon.config.web.AgentController.java

/**
 * ?Agent//from   w  ww  .  j  a va2  s. c  o  m
 * @param request
 * @param writer
 */
@RequestMapping(value = "/upgradeAgent")
public void upgradeAgent(HttpServletRequest request, PrintWriter writer) {
    String json = "";
    try {
        json = agentManageService.upgradeAgent(request);
        writer.write(json);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error(this.getClass().getName() + e.getMessage());
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:com.hp.avmon.config.web.AgentController.java

/**
 * ?Agent/*from   w w w .  j  a  va 2s .  co  m*/
 * @param request
 * @param writer
 */
@RequestMapping(value = "/stopAgent")
public void stopAgent(HttpServletRequest request, PrintWriter writer) {
    String status = "";
    try {
        status = agentManageService.stopAgent(request);
        writer.write(status);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error(this.getClass().getName() + e.getMessage());
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:com.alfaariss.oa.profile.saml2.SAML2Profile.java

private void handleMetaData(HttpServletResponse servletResponse) throws OAException {
    PrintWriter oPWOut = null;
    try {/*from  w  w  w  . j  a v  a  2  s.  c  om*/
        // Marshall the metadata:
        MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(_entityDescriptor);
        Element e = marshaller.marshall(_entityDescriptor);

        servletResponse.setContentType(SAML2Constants.METADATA_CONTENT_TYPE);
        servletResponse.setHeader("Content-Disposition", "attachment; filename=metadata.xml");

        //TODO EVB, MHO: cache processing conform RFC2616 [saml-metadata r1404]
        oPWOut = servletResponse.getWriter();
        String s = XMLUtils.getStringFromDocument(e.getOwnerDocument());

        oPWOut.write(s);
    } catch (IOException e) {
        _logger.warn("I/O error while processing metadata request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (Exception e) {
        _logger.warn("Internal error while processing metadata request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oPWOut != null)
            oPWOut.close();
    }
}

From source file:BA.Server.FileUpload.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*  www  .j  a v a2 s . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter outp = resp.getWriter();

    PrintWriter writer = null;

    try {
        writer = resp.getWriter();
    } catch (IOException ex) {
        log(FileUpload.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    StringBuffer buff = new StringBuffer();

    File file1 = (File) req.getAttribute("file");

    if (file1 == null || !file1.exists()) {
        System.out.println("File does not exist");
    } else if (file1.isDirectory()) {
        System.out.println("File is a directory");
    }

    else {
        File outputFile = new File("/tmp/" + req.getParameter("file"));
        file1.renameTo(outputFile);

        FileInputStream f = new FileInputStream(outputFile);

        // Here BufferedInputStream is added for fast reading.
        BufferedInputStream bis = new BufferedInputStream(f);
        DataInputStream dis = new DataInputStream(bis);
        int i = 0;
        String result = "";

        writer.write("<html>");
        writer.write("<head><script type='text/javascript'>");
        while (dis.available() != 0) {
            String current = dis.readLine();

            if (((String) req.getParameter("uploadType")).equals("equations")) {
                if (FormulaTester.testInput(current) == -1) {
                    writer.write("window.opener.addTabExt(\"" + current + "\" , \"" + req.getParameter("file")
                            + "\");");
                }
            } else {
                writer.write("window.opener.addMacroExt(\"" + current + "\");");
            }
            i++;

        }

        writer.write("this.close();</script></head>");
        writer.write("</script></head>");
        writer.write("<body>");
        writer.write("</body>");
        writer.write("</html>");

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

        dis.close();
        bis.close();
        f.close();
        outputFile.delete();

    }
}

From source file:com.hp.avmon.kpigetconfig.web.KpigetconfigAgentController.java

/**
 * ?//from   w ww. j  av a 2 s .  c  om
 * @param request 
 * @param writer
 */
@RequestMapping(value = "/batchPushAgentAmpSchedule")
public void batchPushAgentAmpSchedule(HttpServletRequest request, PrintWriter writer) {
    Map map = agentManageService.batchPushAgentAmpSchedule(request);
    String jsonData = JackJson.fromObjectToJson(map);
    logger.debug("pushAgentAmpSchedule: " + jsonData);
    writer.write(jsonData);
    writer.flush();
    writer.close();
}