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.imagelake.android.settings.Servlet_PrivilegeSetting.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {//from   w w  w .j a v  a  2  s.  c  om
        String type = request.getParameter("type");

        if (type != null && !type.equals("")) {

            if (type.equals("AllUserTypes")) {
                String k = inf.listPrivilages();
                System.out.println(k);
                out.write(k);
            } else if (type.equals("AddUserTypes")) {
                String ustype = request.getParameter("ustype");
                if (ustype != null && !ustype.trim().equals("")) {
                    boolean k = udi.addUsertType(ustype);
                    if (k) {
                        out.write("msg=Add_User_Type_Successfully...");
                    } else {
                        out.write("msg=Unable to complete the action.");
                    }
                } else {
                    out.write("msg=Internal server error,Please try again later.");
                }
            } else if (type.equals("TypePrivilege")) {
                String id = request.getParameter("userType");
                List<Privilages> li = pdi.listAll(Integer.parseInt(id));
                List<Interfaces> lf = inf.listAll((ArrayList<Privilages>) li);
                ja = new JSONArray();
                for (int i = 0; i < lf.size(); i++) {
                    Interfaces in = lf.get(i);
                    JSONObject jo = new JSONObject();
                    jo.put("id", in.getInterface_id());
                    jo.put("name", in.getDisplay_name());
                    jo.put("state", in.getState());
                    ja.add(jo);
                }
                out.write("json=" + ja.toJSONString());
            } else if (type.equals("remvinf")) {
                String id = request.getParameter("userType");
                String infid = request.getParameter("infid");

                boolean k = pdi.updatePrivilage(Integer.parseInt(id), Integer.parseInt(infid), 2);
                if (k) {
                    out.write("msg=Remve_Successfully...");
                } else {
                    out.write("msg=Unable to complete the action.");
                }
            } else if (type.equals("AllInterface")) {
                String k = inf.listInterfaces();
                System.out.println(type);
                System.out.println(k);
                out.write(k);
            } else if (type.equals("addinf")) {
                String id = request.getParameter("userType");
                String infid = request.getParameter("intfid");
                if (id != null && !id.trim().equals("") && Integer.parseInt(id) != 0 && infid != null
                        && !infid.trim().equals("") && Integer.parseInt(infid) != 0) {
                    boolean k = pdi.addPrivilage(Integer.parseInt(id), Integer.parseInt(infid), 1);
                    if (k) {
                        out.write("msg=Int_Add_Successfully...");
                    } else {
                        out.write("msg=Unable to complete the action.");
                    }
                } else {
                    out.write("msg=Internal server error,Please try again later.");
                }
            }
        } else {
            out.write("msg=Internal server error,Please try again later.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

private void doCallAction(final HttpServletRequestWrapper requestWrapper,
        final HttpServletResponse responseParam) throws IOException {
    String args = parseArgs(requestWrapper);
    String className = parseAction(requestWrapper).trim();
    StringWriter swriter = new StringWriter();
    PrintWriter pwriter = new PrintWriter(swriter);
    try {//from   w w  w  . ja  va 2s.  c o m
        moniServer.callAction(className, args, pwriter);
        pwriter.flush();
        PrintWriter rwriter = responseParam.getWriter();
        responseParam.setStatus(HttpServletResponse.SC_OK);
        rwriter.write(swriter.toString());
    } catch (Exception e) {
        throw new ServletRuntimeException(HttpServletResponse.SC_BAD_REQUEST, e, true);
    } finally {
        pwriter.close();
    }
}

From source file:cn.vlabs.umt.ui.servlet.LoginTokenServlet.java

private void writeToResponse(HttpServletResponse response, Token randomToken) throws IOException {
    // all for ie
    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    JSONObject obj = new JSONObject();
    obj.put("token", randomToken.getRandom() + "-" + randomToken.getId());
    obj.put("createTime", randomToken.getCreateTime().getTime());
    obj.put("expireTime", String.valueOf(randomToken.getExpireTime()));
    writer.write(obj.toString());
}

From source file:com.ibm.xsp.webdav.WebDavServlet.java

/**
 * (non-Javadoc)//from   w ww  . ja  v a 2  s .c om
 * 
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) {

    boolean canContinue = true; // Optimistic
    String errorMessage = null;
    IDAVAddressInformation repoAddress = null;
    this.writeDefaultHeaderInfo(req, resp);

    // We need to extract the repository name from the requestURL
    // If that is empty we list the available repositories as directories
    String curPath = req.getPathInfo();
    // LOGGER.info("Curr path="+curPath+"; method="+req.getMethod());
    if (curPath != null) {
        try {
            curPath = URLDecoder.decode(curPath, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            LOGGER.error(e1);
            curPath = req.getPathInfo(); // We take it unencoded then
        }
    }
    IDAVRepository repository = this.getRepository(req, curPath, servletPath);
    // LOGGER.info("CurrentPath="+curPath+";  servletPath="+servletPath+"");
    IDAVProcessable meth = this.getMethod(req, resp, repository);
    if (meth == null) {
        // LOGGER.info("Method is null");
    } else {
        // LOGGER.info("Method is " +meth.getClass());
    }

    // Now we could have everything, we check if we can move ahead

    // if ((repository == null) ||(curPath == null) || curPath.equals("/")){
    if ((repository == null)) {
        // LOGGER.info("Not found");
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        canContinue = false;
        errorMessage = "<HTML><HEAD><TITLE>Unable to Process Request</TITLE></HEAD><BODY><P>Http Status Code: 404</P><P>Reason: Unable to process request, resource not found</P></BODY></HTML>";
        resp.setContentLength(errorMessage.length());
        resp.setContentType("text/html");
        try {
            PrintWriter out = resp.getWriter();
            out.write(errorMessage);
            out.close();
            return;
        } catch (IOException e) {
            LOGGER.error(e);
        }

    } else {
        // LOGGER.info("repository found "+repository.getClass());
        repoAddress = (IDAVAddressInformation) repository;
    }

    // Without a method there's no point to continue
    if (canContinue && meth == null) {
        // LOGGER.info("Can continue and method is null");
        resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        canContinue = false;
        errorMessage = "<h1>Repository " + repoAddress.getName()
                + "</h1><h2>Sorry, but this repository doesn't support <span style=\"color : red; font-weight : bold;\">[HTTP "
                + req.getMethod() + "]</span></h2>";
    }

    // Now update credentials if we have them
    if (repository != null) {
        this.updateCredentials(req, repository);
    }

    if (canContinue) {
        try {
            // LOGGER.info("Can continue....");
            // We check if we can/have to reset the manager with all
            // repositories
            String reset = req.getParameter("reset");
            if (reset != null) {
                this.reset();
            }

            // Finally execute the method

            meth.process(req, resp, repository, this.getLockManager());

            if (meth.getLastHttpStatus().equals(IDAVProcessable.NO_STATUS_SET) && meth.didMethodSucceed()) {
                resp.setStatus(HttpServletResponse.SC_OK); // Make sure we
                // have a status
            } else if (!meth.didMethodSucceed()) {
                canContinue = false;
                errorMessage = meth.getErrorMessage();
                return;
            }
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            errorMessage = "<h1>Error executing " + meth.getClass().getName() + ": " + e.getMessage() + "</h1>";
            canContinue = false;
            LOGGER.error(e);
        }
    }

    // We might have hit an error just above
    if (!canContinue) {
        // Write out the error
        Unimplemented nothingToDo = new Unimplemented();
        nothingToDo.setUseStream(meth.streamUsed());
        nothingToDo.setErrorMessage(errorMessage);
        nothingToDo.setErrNum(meth.getLastHttpStatus());
        try {
            nothingToDo.process(req, resp, null, null);
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            LOGGER.error(e);
        }
    }
}

From source file:controller.SignUpController.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  w w w . j a  va2  s  .com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("iam in get signup ");
    boolean CreditMsgIndicator = true;
    User user = new User();
    Credit credit = new Credit();
    UserDao userDaoImpl = new UserDaoImpl();
    String creditNumber = request.getParameter("creditnumber");

    System.out.println("iam in get signup credit number is :" + creditNumber);
    user.setCreditNumber(creditNumber);
    credit.setNumber(creditNumber);
    CreditDao creditDao = new CreditDaoImpl();
    PrintWriter printWriter = response.getWriter();

    if (creditDao.checkCredit(credit)) {//credit number is exist is 

        if (!(userDaoImpl.isCreditNumberAssigned(credit))) {
            System.out.println("creditExist = true;");
        } else {
            printWriter.write("we are sorry.. credit number is Assigened to other client .. !");

            CreditMsgIndicator = false;
            System.out.println("creditExist = falsefalse;");

        }
    } else {

        if (CreditMsgIndicator) {
            printWriter.write("This credit number doesn't exist");
            System.out.println("creditExist=false;");

        }
        CreditMsgIndicator = true;
        System.out.println("creditExist=false;");

    }

}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    response.setContentType("text/html");
    String callType = request.getParameter("callType");

    switch (callType) {
    case "saveParams": {

        Map<String, String> key = new HashMap<>();
        key.put("feature_id", request.getParameter("feature_id"));

        long pk = (new Random()).nextLong();

        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

        PrintWriter writer = response.getWriter();
        writer.write("" + pk);
        writer.close();/*from   ww w .  j  a v  a 2s.  co m*/
        break;
    }
    case "getFeatureIds": {
        String pathwayId = request.getParameter("map");
        String featureList = request.getParameter("featureList");
        String algorithm = request.getParameter("algorithm");

        DataApiHandler dataApi = new DataApiHandler(request);

        SolrQuery query = new SolrQuery("pathway_id:(" + pathwayId.replaceAll(",", " OR ")
                + ") AND feature_id:(" + featureList.replaceAll(",", " OR ") + ")");
        query.addFilterQuery("annotation:" + algorithm).setRows(dataApi.MAX_ROWS).addField("feature_id");

        LOGGER.trace("getFeatureIds: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);
        String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");
        List<GenomeFeature> features = dataApi.bindDocuments((List<Map>) respBody.get("docs"),
                GenomeFeature.class);

        JSONArray featureIds = new JSONArray();
        for (GenomeFeature feature : features) {
            featureIds.add(feature.getId());
        }

        response.setContentType("application/json");
        featureIds.writeJSONString(response.getWriter());
        break;
    }
    case "getGenomeIds": {

        String featureIds = request.getParameter("feature_id");
        String pathwayId = request.getParameter("map");

        DataApiHandler dataApi = new DataApiHandler(request);

        String genomeId = "";
        if (featureIds != null && !featureIds.equals("") && pathwayId != null && !pathwayId.equals("")) {
            String[] listFeatureId = featureIds.split(",");

            SolrQuery query = new SolrQuery("pathway_id:(" + pathwayId + ") AND feature_id:("
                    + StringUtils.join(listFeatureId, " OR ") + ")");
            query.addField("genome_id").setRows(listFeatureId.length);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");
            List<Map> sdl = (List<Map>) respBody.get("docs");

            Set<String> listGenomeId = new HashSet<>();
            for (Map doc : sdl) {
                listGenomeId.add(doc.get("genome_id").toString());
            }
            genomeId = StringUtils.join(listGenomeId, ",");
        }
        PrintWriter writer = response.getWriter();
        writer.write(genomeId);
        writer.close();
        break;
    }
    case "download": {

        String _filename = "PathwaySummary";
        String _fileformat = request.getParameter("fileformat");
        String pk = request.getParameter("pk");
        Map<String, String> key = jsonReader
                .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));

        if (key != null && key.containsKey("feature_id")) {
            List<String> featureIDs = Arrays.asList(key.get("feature_id").split(","));
            JSONObject jsonResult = getEnrichmentPathway(request, featureIDs);

            List<String> _tbl_header = new ArrayList<>();
            List<String> _tbl_field = new ArrayList<>();
            JSONArray _tbl_source = (JSONArray) jsonResult.get("results");

            _tbl_header.addAll(Arrays.asList("Pathway Name", "# of Genes Selected   ", "# of Genes Annotated",
                    "% Coverage"));
            _tbl_field.addAll(Arrays.asList("pathway_name", "ocnt", "ecnt", "percentage"));

            ExcelHelper excel = new ExcelHelper("xssf", _tbl_header, _tbl_field, _tbl_source);
            excel.buildSpreadsheet();

            if (_fileformat.equalsIgnoreCase("xlsx")) {

                response.setContentType("application/octetstream");
                response.setProperty("Content-Disposition",
                        "attachment; filename=\"" + _filename + "." + _fileformat + "\"");

                excel.writeSpreadsheettoBrowser(response.getPortletOutputStream());
            } else if (_fileformat.equalsIgnoreCase("txt")) {

                response.setContentType("application/octetstream");
                response.setProperty("Content-Disposition",
                        "attachment; filename=\"" + _filename + "." + _fileformat + "\"");

                response.getWriter().write(excel.writeToTextFile());
            }
        }
        break;
    }
    case "getFeatureTable": {

        String pk = request.getParameter("pk");
        Map<String, String> key = jsonReader
                .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));

        response.setContentType("application/json");
        if (key != null && key.containsKey("feature_id")) {

            List<String> featureIDs = Arrays.asList(key.get("feature_id").split(","));
            JSONObject jsonResult = getEnrichmentPathway(request, featureIDs);

            PrintWriter writer = response.getWriter();
            jsonResult.writeJSONString(writer);
            writer.close();
        } else {
            PrintWriter writer = response.getWriter();
            writer.write("{}");
            writer.close();
        }
        break;
    }
    }
}

From source file:com.ctb.prism.report.api.CustomReportServlet.java

protected void pageUpdate(HttpServletRequest request, HttpServletResponse response,
        WebReportContext webReportContext) throws JRException, IOException {
    JasperPrintAccessor jasperPrintAccessor = (JasperPrintAccessor) webReportContext
            .getParameterValue(WebReportContext.REPORT_CONTEXT_PARAMETER_JASPER_PRINT_ACCESSOR);
    if (jasperPrintAccessor == null) {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_REPORT_NOT_FOUND, (Object[]) null);
    }/*from ww  w.  j  ava 2s.c o  m*/

    String pageIdxParam = request.getParameter(WebUtil.REQUEST_PARAMETER_PAGE);
    Integer pageIndex = pageIdxParam == null ? null : Integer.valueOf(pageIdxParam);
    String pageTimestampParam = request.getParameter(WebUtil.REQUEST_PARAMETER_PAGE_TIMESTAMP);
    Long pageTimestamp = pageTimestampParam == null ? null : Long.valueOf(pageTimestampParam);

    if (log.isDebugEnabled()) {
        log.debug("report page update check for pageIndex: " + pageIndex + ", pageTimestamp: " + pageTimestamp);
    }

    LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();
    putReportStatusResult(response, jasperPrintAccessor, result);

    if (pageIndex != null && pageTimestamp != null) {
        ReportPageStatus pageStatus = jasperPrintAccessor.pageStatus(pageIndex, pageTimestamp);
        boolean modified = pageStatus.hasModified();
        result.put("pageModified", modified);

        if (log.isDebugEnabled()) {
            log.debug("page " + pageIndex + " modified " + modified);
        }
    }

    String resultString = JacksonUtil.getInstance(getJasperReportsContext()).getJsonString(result);
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.write(resultString);
    out.flush();
}

From source file:com.vcredit.lrh.microservice.gateway.api.redis.SecurityHandlerRedis.java

private void serverErrorRequest(HttpServletResponse httpServletResponse) throws IOException {
    JSONObject jSONObject = new JSONObject();
    PrintWriter pw = httpServletResponse.getWriter();
    httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
    jSONObject.put("status", "error");
    jSONObject.put("code", HttpServletResponse.SC_NOT_ACCEPTABLE);
    jSONObject.put("message", "server error , please try again later...");
    pw.write(jSONObject.toJSONString());
    pw.flush();//from w w w .  j  av  a2  s.c  om
}

From source file:gov.nist.appvet.tool.AsynchronousService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;//from  w ww .j a  va  2  s.c o m
    FileItem fileItem = null;
    String appId = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get form fields
    Iterator iter = items.iterator();
    FileItem item = null;
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            String incomingParameter = item.getFieldName();
            String incomingValue = item.getString();
            if (incomingParameter.equals("appid")) {
                appId = incomingValue;
            }
            log.debug("Received: " + incomingParameter + " = " + incomingValue);
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
            }
        }
    }

    // If app ID and file were received, send back HTTP 202 now
    if (appId != null && fileItem != null) {
        sendHttp202(response, "Received app " + appId + " for processing.");
    } else {
        sendHttp400(response, "Did not receive proper request.");
        return;
    }

    String appFilePath = null;
    String reportPath = null;
    String fileName = null;

    if (item != null) {
        fileName = getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }

        appFilePath = Properties.TEMP_DIR + "/" + appId + fileName;
        reportPath = Properties.TEMP_DIR + "/" + appId + "_report.txt";
        log.debug("appFilePath: " + appFilePath);

        if (!saveFileUpload(fileItem, appFilePath)) {
            sendHttp500(response, "Could not save uploaded file");
            return;
        }
    } else {
        log.error("File item was null.");
        return;
    }

    // Test app
    AndroidVulnerabilityScanner vulnerabilityScanner = new AndroidVulnerabilityScanner(appFilePath);

    boolean masterKeyFound = vulnerabilityScanner.hasMasterKey();

    boolean extraFieldFound = vulnerabilityScanner.hasExtraField();
    vulnerabilityScanner.close();

    // Generate report
    String htmlReport = null;
    ToolStatus reportStatus = null;
    if (masterKeyFound) {
        reportStatus = ToolStatus.FAIL;
        htmlReport = generateReport(fileName, reportStatus, "Master Key vulnerability detected.");
    }
    if (extraFieldFound) {
        reportStatus = ToolStatus.FAIL;
        htmlReport = generateReport(fileName, reportStatus, "Extra Field vulnerability detected.");
    }

    if (!masterKeyFound && !extraFieldFound) {
        reportStatus = ToolStatus.PASS;
        htmlReport = generateReport(fileName, reportStatus,
                "No Master Key or Extra Field vulnerablity detected.");
    }

    // Write report file
    PrintWriter out = new PrintWriter(reportPath);
    out.write(htmlReport);
    out.close();

    // Now send report
    sendReport(appId, reportStatus.name(), reportPath);

    boolean deleted = deleteFile(appFilePath);
    if (deleted) {
        log.debug("Deleted app " + appFilePath);
    } else {
        log.error("Could not delete app file " + appFilePath);
    }

    deleted = deleteFile(reportPath);
    if (deleted) {
        log.debug("Deleted report " + reportPath);
    } else {
        log.error("Could not delete report file " + reportPath);
    }

    // Clean up
    System.gc();
}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    String sraction = request.getParameter("sraction");

    if (sraction != null && sraction.equals("save_params")) {

        LOGGER.debug("{}", request.getParameterMap());

        Map<String, String> key = new HashMap<>();

        String genomeId = request.getParameter("genomeId");
        String taxonId = "";
        String cType = request.getParameter("cType");
        String cId = request.getParameter("cId");

        if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) {
            taxonId = cId;//ww w .  j a  v  a2s.c o m
        }

        String keyword = request.getParameter("keyword");
        String state = request.getParameter("state");
        String ncbi_taxon_id = request.getParameter("ncbi_taxon_id");
        String exact_search_term = request.getParameter("exact_search_term");

        if (genomeId != null && !genomeId.equalsIgnoreCase("")) {
            key.put("genomeId", genomeId);
        }
        if (!taxonId.equalsIgnoreCase("")) {
            key.put("taxonId", taxonId);
        }
        if (keyword != null) {
            key.put("keyword", keyword.trim());
        }
        if (ncbi_taxon_id != null) {
            key.put("ncbi_taxon_id", ncbi_taxon_id);
        }
        if (state != null) {
            key.put("state", state);
        }
        if (exact_search_term != null) {
            key.put("exact_search_term", exact_search_term);
        }

        if (!key.containsKey("genomeId") && cType != null && cType.equals("genome") && cId != null
                && !cId.equals("")) {
            key.put("genomeId", cId);
        }
        if (!key.containsKey("taxonId") && cType != null && cType.equals("taxon") && cId != null
                && !cId.equals("")) {
            key.put("taxonId", cId);
        }
        // random
        long pk = (new Random()).nextLong();

        SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

        PrintWriter writer = response.getWriter();
        writer.write("" + pk);
        writer.close();

    } else {

        String need = request.getParameter("need");
        JSONObject jsonResult = new JSONObject();

        switch (need) {
        case "feature":
        case "featurewofacet": {
            // Getting Feature List
            Map data = processFeatureTab(request);

            int numFound = (Integer) data.get("numFound");
            List<GenomeFeature> records = (List<GenomeFeature>) data.get("features");

            JSONArray docs = new JSONArray();
            for (GenomeFeature item : records) {
                docs.add(item.toJSONObject());
            }

            jsonResult.put("results", docs);
            jsonResult.put("total", numFound);

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            jsonResult.writeJSONString(writer);
            writer.close();

            break;
        }
        case "download": {
            List<String> tableHeader = new ArrayList<>();
            List<String> tableField = new ArrayList<>();
            JSONArray tableSource = new JSONArray();

            String fileName = "FeatureTable";
            String fileFormat = request.getParameter("fileformat");

            // features
            Map data = processFeatureTab(request);
            List<GenomeFeature> features = (List<GenomeFeature>) data.get("features");

            for (GenomeFeature feature : features) {
                tableSource.add(feature.toJSONObject());
            }

            tableHeader.addAll(DownloadHelper.getHeaderForFeatures());
            tableField.addAll(DownloadHelper.getFieldsForFeatures());

            ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource);
            excel.buildSpreadsheet();

            if (fileFormat.equalsIgnoreCase("xlsx")) {
                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                excel.writeSpreadsheettoBrowser(response.getPortletOutputStream());
            } else if (fileFormat.equalsIgnoreCase("txt")) {

                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                response.getPortletOutputStream().write(excel.writeToTextFile().getBytes());
            }

            break;
        }
        }
    }
}