/** {@inheritDoc} */
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    String[] requiredParameters =
        new String[] {"parentResourceId or", "parentResourceType and parentResource"};

    String endUrl = WebSecurityUtils.sanitizeString(request.getParameter("endUrl"));

    String resourceId = WebSecurityUtils.sanitizeString(request.getParameter("parentResourceId"));
    if (resourceId == null) {
      String resourceType =
          WebSecurityUtils.sanitizeString(request.getParameter("parentResourceType"));
      String resource = WebSecurityUtils.sanitizeString(request.getParameter("parentResource"));
      if (request.getParameter("parentResourceType") == null) {
        throw new MissingParameterException("parentResourceType", requiredParameters);
      }
      if (request.getParameter("parentResource") == null) {
        throw new MissingParameterException("parentResource", requiredParameters);
      }

      resourceId = OnmsResource.createResourceId(resourceType, resource);
    }

    if (endUrl == null || "".equals(endUrl)) {
      endUrl = m_defaultEndUrl;
    }

    ChooseResourceModel model = m_chooseResourceService.findChildResources(resourceId, endUrl);

    return new ModelAndView("/graph/chooseresource", "model", model);
  }
  /** {@inheritDoc} */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String nodeIdString = request.getParameter("node");
    String isNewString = request.getParameter("isnew");

    if (nodeIdString == null) {
      throw new MissingParameterException("node", new String[] {"node", "isnew"});
    }

    if (isNewString == null) {
      throw new MissingParameterException("isnew", new String[] {"node", "isnew"});
    }

    int nodeId = WebSecurityUtils.safeParseInt(nodeIdString);
    boolean isNew = Boolean.valueOf(isNewString).booleanValue();

    Asset asset = this.parms2Asset(request, nodeId);

    Event evnt = EventUtils.createAssetInfoChangedEvent("OpenNMS.WebUI", nodeId, -1L);
    sendEvent(evnt);

    try {
      if (isNew) {
        this.model.createAsset(asset);
      } else {
        this.model.modifyAsset(asset);
      }

      response.sendRedirect("modify.jsp?node=" + nodeId);
    } catch (SQLException e) {
      throw new ServletException("database error", e);
    }
  }
  /** {@inheritDoc} */
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    int nodeId = -1;
    String nodeIdString = request.getParameter("node");

    if (nodeIdString == null) throw new ServletException("Missing node Id.");

    HttpSession user = request.getSession(true);

    try {
      nodeId = WebSecurityUtils.safeParseInt(nodeIdString);
    } catch (NumberFormatException numE) {
      throw new ServletException(numE.getMessage());
    }

    if (nodeId < 0) throw new ServletException("Invalid node ID.");

    try {
      user.setAttribute("interfaces.nodemanagement", getInterfaces(user, nodeId));
    } catch (SQLException sqlE) {
      throw new ServletException(sqlE);
    } catch (IllegalStateException illE) {
      throw new ServletException(illE);
    }

    // forward the request for proper display
    RequestDispatcher dispatcher =
        this.getServletContext().getRequestDispatcher("/admin/nodemanagement/managenode.jsp");
    dispatcher.forward(request, response);
  }
 /**
  * getRequestParameter
  *
  * @param request a {@link javax.servlet.http.HttpServletRequest} object.
  * @param name a {@link java.lang.String} object.
  * @return a {@link java.lang.String} object.
  */
 protected String getRequestParameter(final HttpServletRequest request, final String name) {
   boolean allowHTML = false;
   if (s_allowHtmlFields.contains(name.toLowerCase())) {
     allowHTML = true;
   }
   return WebSecurityUtils.sanitizeString(request.getParameter(name), allowHTML);
 }
  /** {@inheritDoc} */
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession userSession = request.getSession(false);

    if (userSession != null) {
      // group.modifyGroup.jsp
      WebGroup newGroup = (WebGroup) userSession.getAttribute("group.modifyGroup.jsp");

      // get the rest of the group information from the form
      String users[] = request.getParameterValues("selectedUsers");

      newGroup.setUsers(new ArrayList<String>(Arrays.asList(users)));

      String[] selectedCategories = request.getParameterValues("selectedCategories");

      newGroup.setAuthorizedCategories(new ArrayList<String>(Arrays.asList(selectedCategories)));

      Vector<Object> newSchedule = new Vector<Object>();
      ChoiceFormat days = new ChoiceFormat("0#Mo|1#Tu|2#We|3#Th|4#Fr|5#Sa|6#Su");

      Collection<String> dutySchedules = newGroup.getDutySchedules();
      dutySchedules.clear();

      int dutyCount = WebSecurityUtils.safeParseInt(request.getParameter("dutySchedules"));
      for (int duties = 0; duties < dutyCount; duties++) {
        newSchedule.clear();
        String deleteFlag = request.getParameter("deleteDuty" + duties);
        // don't save any duties that were marked for deletion
        if (deleteFlag == null) {
          for (int i = 0; i < 7; i++) {
            String curDayFlag = request.getParameter("duty" + duties + days.format(i));
            if (curDayFlag != null) {
              newSchedule.addElement(Boolean.TRUE);
            } else {
              newSchedule.addElement(Boolean.FALSE);
            }
          }

          newSchedule.addElement(request.getParameter("duty" + duties + "Begin"));
          newSchedule.addElement(request.getParameter("duty" + duties + "End"));

          DutySchedule newDuty = new DutySchedule(newSchedule);
          dutySchedules.add(newDuty.toString());
        }
      }

      userSession.setAttribute("group.modifyGroup.jsp", newGroup);
    }

    return new ModelAndView(request.getParameter("redirect"));
  }
  /** {@inheritDoc} */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession userSession = request.getSession(true);

    Group group = (Group) userSession.getAttribute("group.modifyGroup.jsp");
    GroupInfo groupInfo = group.getGroupInfo();

    List<DutySchedule> dutySchedules = groupInfo.getDutySchedules();

    int dutyCount = WebSecurityUtils.safeParseInt(request.getParameter("dutySchedules"));
    for (int i = 0; i < dutyCount; i++) {
      String curDuty = request.getParameter("deleteDuty" + i);
      if (curDuty != null) {
        dutySchedules.remove(i);
      }
    }

    // forward the request for proper display
    RequestDispatcher dispatcher =
        this.getServletContext()
            .getRequestDispatcher("/admin/userGroupView/groups/modifyGroup.jsp");
    dispatcher.forward(request, response);
  }
  /** {@inheritDoc} */
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    ThreadCategory.setPrefix(MapsConstants.LOG4J_CATEGORY);
    log = ThreadCategory.getInstance(this.getClass());
    String action = request.getParameter("action");
    String elems = request.getParameter("elems");
    log.debug("Adding Nodes action:" + action + ", elems=" + elems);

    BufferedWriter bw =
        new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    try {
      Integer[] nodeids = null;

      boolean actionfound = false;

      if (action.equals(MapsConstants.ADDNODES_ACTION)) {
        log.debug("Adding nodes by id: " + elems);
        actionfound = true;
        String[] snodeids = elems.split(",");
        nodeids = new Integer[snodeids.length];
        for (int i = 0; i < snodeids.length; i++) {
          nodeids[i] = new Integer(snodeids[i]);
        }
      }

      if (action.equals(MapsConstants.ADDNODES_BY_CATEGORY_ACTION)) {
        log.debug("Adding nodes by category: " + elems);
        actionfound = true;
        String categoryName = elems;
        CategoryFactory.init();
        CatFactory cf = CategoryFactory.getInstance();
        cf.getReadLock().lock();
        try {
          final String rule = cf.getEffectiveRule(categoryName);
          final List<InetAddress> nodeIPs = FilterDaoFactory.getInstance().getIPAddressList(rule);
          LogUtils.debugf(this, "ips found: %s", nodeIPs.toString());
          nodeids = new Integer[nodeIPs.size()];
          for (int i = 0; i < nodeIPs.size(); i++) {
            final InetAddress nodeIp = nodeIPs.get(i);
            final List<Integer> ids =
                NetworkElementFactory.getInstance(getServletContext())
                    .getNodeIdsWithIpLike(InetAddressUtils.str(nodeIp));
            LogUtils.debugf(this, "Ids by ipaddress %s: %s", nodeIp, ids.toString());
            nodeids[i] = ids.get(0);
          }
        } finally {
          cf.getReadLock().unlock();
        }
      }

      if (action.equals(MapsConstants.ADDNODES_BY_LABEL_ACTION)) {
        log.debug("Adding nodes by label: " + elems);
        actionfound = true;
        List<OnmsNode> nodes = NetworkElementFactory.getInstance(getServletContext()).getAllNodes();
        nodeids = new Integer[nodes.size()];
        for (int i = 0; i < nodes.size(); i++) {
          nodeids[i] = nodes.get(i).getId();
        }
      }

      if (action.equals(MapsConstants.ADDRANGE_ACTION)) {
        log.debug("Adding nodes by range: " + elems);
        actionfound = true;
        nodeids =
            (Integer[])
                NetworkElementFactory.getInstance(getServletContext())
                    .getNodeIdsWithIpLike(elems)
                    .toArray(new Integer[0]);
      }

      if (action.equals(MapsConstants.ADDNODES_NEIG_ACTION)) {
        log.debug("Adding nodes neighbor of:" + elems);
        actionfound = true;
        nodeids =
            (Integer[])
                NetworkElementFactory.getInstance(getServletContext())
                    .getLinkedNodeIdOnNode(WebSecurityUtils.safeParseInt(elems))
                    .toArray(new Integer[0]);
      }

      if (action.equals(MapsConstants.ADDNODES_WITH_NEIG_ACTION)) {
        log.debug("Adding nodes with neighbor of:" + elems);
        actionfound = true;
        Set<Integer> linkednodeids =
            NetworkElementFactory.getInstance(getServletContext())
                .getLinkedNodeIdOnNode(WebSecurityUtils.safeParseInt(elems));
        linkednodeids.add(new Integer(elems));
        nodeids = linkednodeids.toArray(new Integer[linkednodeids.size()]);
      }

      VMap map = manager.openMap();
      if (log.isDebugEnabled()) log.debug("Got map from manager " + map);

      List<VElement> velems = new ArrayList<VElement>();
      // response for addElement
      if (actionfound) {
        log.debug("Before Checking map contains elems");

        for (int i = 0; i < nodeids.length; i++) {
          int elemId = nodeids[i].intValue();
          if (map.containsElement(elemId, MapsConstants.NODE_TYPE)) {
            log.debug(
                "Action: "
                    + action
                    + " . Map Contains Element: "
                    + elemId
                    + MapsConstants.NODE_TYPE);
            continue;
          }

          velems.add(manager.newElement(map.getId(), elemId, MapsConstants.NODE_TYPE));
        } // end for

        // get links and add elements to map
        map = manager.addElements(map, velems);
        log.debug("After getting/adding links");

        bw.write(ResponseAssembler.getAddElementResponse(null, velems, map.getLinks()));
      }
    } catch (Throwable e) {
      log.error("Error while adding nodes for action: " + action, e);
      bw.write(ResponseAssembler.getMapErrorResponse(action));
    } finally {
      bw.close();
    }

    return null;
  }
  /**
   * decodeAssetsText
   *
   * @param text a {@link java.lang.String} object.
   * @return a {@link java.util.List} object.
   * @throws org.opennms.web.asset.ImportAssetsServlet$AssetException if any.
   */
  public List<Asset> decodeAssetsText(String text) throws AssetException {
    CSVReader csvReader = null;
    StringReader stringReader = null;
    String[] line;
    List<Asset> list = new ArrayList<Asset>();
    text = text.trim();

    int count = 0;

    try {
      stringReader = new StringReader(text);
      csvReader = new CSVReader(stringReader);

      while ((line = csvReader.readNext()) != null) {
        count++;
        try {
          logger.debug("asset line is:'{}'", (Object) line);
          if (line.length <= 37) {
            logger.error(
                "csv test row length was not at least 37 line length: '{}' line was:'{}', line length",
                line.length,
                line);
            throw new NoSuchElementException();
          }

          // skip the first line if it's the headers
          if (line[0].equals("Node Label")) {
            logger.debug("line was header. line:'{}'", (Object) line);
            continue;
          }

          final Asset asset = new Asset();

          asset.setNodeId(WebSecurityUtils.safeParseInt(line[1]));
          asset.setCategory(Util.decode(line[2]));
          asset.setManufacturer(Util.decode(line[3]));
          asset.setVendor(Util.decode(line[4]));
          asset.setModelNumber(Util.decode(line[5]));
          asset.setSerialNumber(Util.decode(line[6]));
          asset.setDescription(Util.decode(line[7]));
          asset.setCircuitId(Util.decode(line[8]));
          asset.setAssetNumber(Util.decode(line[9]));
          asset.setOperatingSystem(Util.decode(line[10]));
          asset.setRack(Util.decode(line[11]));
          asset.setSlot(Util.decode(line[12]));
          asset.setPort(Util.decode(line[13]));
          asset.setRegion(Util.decode(line[14]));
          asset.setDivision(Util.decode(line[15]));
          asset.setDepartment(Util.decode(line[16]));
          asset.setAddress1(Util.decode(line[17]));
          asset.setAddress2(Util.decode(line[18]));
          asset.setCity(Util.decode(line[19]));
          asset.setState(Util.decode(line[20]));
          asset.setZip(Util.decode(line[21]));
          asset.setBuilding(Util.decode(line[22]));
          asset.setFloor(Util.decode(line[23]));
          asset.setRoom(Util.decode(line[24]));
          asset.setVendorPhone(Util.decode(line[25]));
          asset.setVendorFax(Util.decode(line[26]));
          asset.setDateInstalled(Util.decode(line[27]));
          asset.setLease(Util.decode(line[28]));
          asset.setLeaseExpires(Util.decode(line[29]));
          asset.setSupportPhone(Util.decode(line[30]));
          asset.setMaintContract(Util.decode(line[31]));
          asset.setVendorAssetNumber(Util.decode(line[32]));
          asset.setMaintContractExpires(Util.decode(line[33]));
          asset.setDisplayCategory(Util.decode(line[34]));
          asset.setNotifyCategory(Util.decode(line[35]));
          asset.setPollerCategory(Util.decode(line[36]));

          if (line.length > 37) {
            asset.setThresholdCategory(Util.decode(line[37]));
            asset.setUsername(Util.decode(line[38]));
            asset.setPassword(Util.decode(line[39]));
            asset.setEnable(Util.decode(line[40]));
            asset.setConnection(Util.decode(line[41]));
            asset.setAutoenable(Util.decode(line[42]));
            asset.setComments(Util.decode(line[43]));
          }

          if (line.length > 44) {
            asset.setCpu(Util.decode(line[44]));
            asset.setRam(Util.decode(line[45]));
            asset.setStoragectrl(Util.decode(line[46]));
            asset.setHdd1(Util.decode(line[47]));
            asset.setHdd2(Util.decode(line[48]));
            asset.setHdd3(Util.decode(line[49]));
            asset.setHdd4(Util.decode(line[50]));
            asset.setHdd5(Util.decode(line[51]));
            asset.setHdd6(Util.decode(line[52]));

            asset.setNumpowersupplies(Util.decode(line[53]));
            asset.setInputpower(Util.decode(line[54]));

            asset.setAdditionalhardware(Util.decode(line[55]));
            asset.setAdmin(Util.decode(line[56]));
            asset.setSnmpcommunity(Util.decode(line[57]));
            asset.setRackunitheight(Util.decode(line[58]));
          }

          if (line.length > 59) {
            asset.setCountry(Util.decode(line[59]));
            asset.setLongitude(Util.decode(line[60]));
            asset.setLatitude(Util.decode(line[61]));
          }

          list.add(asset);
          logger.debug("decoded asset:'{}'", (Object) asset);

        } catch (NoSuchElementException e) {
          errors.add("Ignoring malformed import for entry " + count + ", not enough values.");
        } catch (NumberFormatException e) {
          logger.error(
              "NodeId parsing to int faild, ignoreing malformed import for entry number '{}' exception message:'{}'",
              count,
              e.getMessage());
          errors.add("Ignoring malformed import for entry " + count + ", node id not a number.");
        }
      }
    } catch (IOException e) {
      logger.error("An error occurred reading the CSV input. Message:'{}'", e.getMessage());
      throw new AssetException("An error occurred reading the CSV input.", e);
    } finally {
      IOUtils.closeQuietly(stringReader);
      IOUtils.closeQuietly(csvReader);
    }

    if (list.size() == 0) {
      logger.error("No asset information was found, list size was 0");
      throw new AssetException("No asset information was found.");
    }

    return list;
  }
  /** {@inheritDoc} */
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String nodeIdString = request.getParameter("node");
    String labelType = request.getParameter("labeltype");
    String userLabel = request.getParameter("userlabel");

    if (nodeIdString == null) {
      throw new MissingParameterException("node", new String[] {"node", "labeltype", "userlabel"});
    }
    if (labelType == null) {
      throw new MissingParameterException(
          "labeltype", new String[] {"node", "labeltype", "userlabel"});
    }
    if (userLabel == null) {
      throw new MissingParameterException(
          "userlabel", new String[] {"node", "labeltype", "userlabel"});
    }

    try {
      final int nodeId = WebSecurityUtils.safeParseInt(nodeIdString);
      final OnmsNode node = NetworkElementFactory.getInstance(getServletContext()).getNode(nodeId);
      NodeLabelJDBCImpl oldLabel = new NodeLabelJDBCImpl(node.getLabel(), node.getLabelSource());
      NodeLabelJDBCImpl newLabel = null;

      if (labelType.equals("auto")) {
        newLabel = NodeLabelJDBCImpl.getInstance().computeLabel(nodeId);
      } else if (labelType.equals("user")) {
        newLabel = new NodeLabelJDBCImpl(userLabel, NodeLabelSource.USER);
      } else {
        throw new ServletException("Unexpected labeltype value: " + labelType);
      }

      final String newNodeLabel = newLabel.getLabel();
      boolean managedByProvisiond = node.getForeignSource() != null && node.getForeignId() != null;
      if (managedByProvisiond) {
        WebApplicationContext beanFactory =
            WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        final TransactionTemplate transactionTemplate =
            beanFactory.getBean(TransactionTemplate.class);
        final RequisitionAccessService requisitionService =
            beanFactory.getBean(RequisitionAccessService.class);
        transactionTemplate.execute(
            new TransactionCallback<RequisitionNode>() {
              @Override
              public RequisitionNode doInTransaction(TransactionStatus status) {
                MultivaluedMapImpl params = new MultivaluedMapImpl();
                params.putSingle("node-label", newNodeLabel);
                requisitionService.updateNode(node.getForeignSource(), node.getForeignId(), params);
                return requisitionService.getNode(node.getForeignSource(), node.getForeignId());
              }
            });
      }

      this.sendLabelChangeEvent(nodeId, oldLabel, newLabel);

      if (managedByProvisiond) {
        response.sendRedirect(
            Util.calculateUrlBase(
                request,
                "admin/nodelabelProvisioned.jsp?node="
                    + nodeIdString
                    + "&foreignSource="
                    + node.getForeignSource()));
      } else {
        NodeLabelJDBCImpl.getInstance().assignLabel(nodeId, newLabel);
        response.sendRedirect(
            Util.calculateUrlBase(request, "element/node.jsp?node=" + nodeIdString));
      }
    } catch (SQLException e) {
      throw new ServletException("Database exception", e);
    } catch (Throwable e) {
      throw new ServletException("Exception sending node label change event", e);
    }
  }
  /**
   * {@inheritDoc}
   *
   * <p>Purge or purge all action of the selected alarms specified in the POST and then redirect the
   * client to an appropriate URL for display.
   */
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    logger.info("Enter into the AlarmPurgeController action");

    // Handle the alarm and actionCode parameter
    String[] alarmIdStrings = request.getParameterValues("alarm");
    String action = request.getParameter("actionCode");

    List<Integer> alarmIds = new ArrayList<Integer>();
    if (alarmIdStrings != null && action.equals(PURGE_ACTION)) {
      for (int i = 0; i < alarmIdStrings.length; i++) {
        try {
          alarmIds.add(WebSecurityUtils.safeParseInt(alarmIdStrings[i]));
        } catch (Exception e) {
          logger.error("Could not parse alarm ID '{}' to integer.", alarmIdStrings[i]);
        }
      }
    }

    // Handle the acknowledge type parameter
    String ackTypeString = request.getParameter("acktype");
    AcknowledgeType alarmAckType = m_defaultAlarmAcknowledgeType;

    if (ackTypeString != null) {
      try {
        alarmAckType = AcknowledgeType.getAcknowledgeType(ackTypeString);
      } catch (Exception e) {
        logger.error("Could not retrieve acknowledge type for this '{}'.", ackTypeString);
      }
    }

    // Handle the filter parameter
    List<Filter> filterList = new ArrayList<Filter>();
    String[] filterStrings = request.getParameterValues("filter");

    if (action.equals(PURGEALL_ACTION)) {
      if (filterStrings != null) {
        for (int i = 0; i < filterStrings.length; i++) {
          Filter filter = AlarmUtil.getFilter(filterStrings[i], getServletContext());
          if (filter != null) {
            filterList.add(filter);
          }
        }
      }
    }

    // Get the alarms by alarm criteria
    Filter[] alarmFilters = filterList.toArray(new Filter[0]);

    if (action.equals(PURGEALL_ACTION)) {
      alarmIds.clear();
      AlarmCriteria alarmQueryCriteria = new AlarmCriteria(alarmAckType, alarmFilters);
      OnmsAlarm[] alarms =
          m_webAlarmRepository.getMatchingAlarms(AlarmUtil.getOnmsCriteria(alarmQueryCriteria));
      for (OnmsAlarm alarm : alarms) {
        alarmIds.add(alarm.getId());
      }
    }

    // Handle the purge action
    if (action.equals(PURGE_ACTION) || action.equals(PURGEALL_ACTION)) {
      try {
        m_webAlarmRepository.purgeAlarms(alarmIds);
        request.getSession().setAttribute("actionStatus", alarmIds.size() + "," + SUCCESS_ACTION);
        logger.info(
            "The Purge action is successfully completed for the alarm Id's " + alarmIds + " ");
      } catch (final Exception ex) {
        ex.printStackTrace();
        request.getSession().setAttribute("actionStatus", alarmIds.size() + "," + FAILURE_ACTION);
        logger.error("Unable to do purge action for this alarm Id's.", alarmIds);
      }
    } else {
      logger.error("Unknown alarm action: " + action);
    }

    // Handle the redirect parameters
    String redirectParms = request.getParameter("redirectParms");
    String viewName = m_redirectView;
    if (redirectParms != null) {
      viewName = m_redirectView + "?" + redirectParms;
    }

    RedirectView view = new RedirectView(viewName, true);
    logger.info("Terminated from the AlarmPurgeController action");

    return new ModelAndView(view);
  }
  /** {@inheritDoc} */
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

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

    m_reportdConfigurationDao =
        BeanUtils.getBean("reportdContext", "reportdConfigDao", ReportdConfigurationDao.class);
    final File storageDirectory = new File(m_reportdConfigurationDao.getStorageDirectory());

    if (fileName != null) {
      final File requestedFile = new File(fileName);
      if (!requestedFile
          .getParentFile()
          .getCanonicalFile()
          .equals(storageDirectory.getCanonicalFile())) {
        LogUtils.warnf(
            this,
            "User attempted to retrieve file %s but was restricted to %s",
            requestedFile,
            storageDirectory);
        throw new IllegalArgumentException(
            "Cannot retrieve reports from outside Reportd storage directory");
      }

      if (fileName.toLowerCase().endsWith(".pdf")) {
        response.setContentType("application/pdf;charset=UTF-8");
      }
      if (fileName.toLowerCase().endsWith(".csv")) {
        response.setContentType("text/csv;charset=UTF-8");
      }
      response.setHeader("Content-disposition", "inline; filename=" + fileName);
      response.setHeader("Pragma", "public");
      response.setHeader("Cache-Control", "cache");
      response.setHeader("Cache-Control", "must-revalidate");
      StreamUtils.copy(new FileInputStream(new File(fileName)), response.getOutputStream());
      return null;
    }

    String[] requiredParameters = new String[] {"locatorId", "format"};

    for (String requiredParameter : requiredParameters) {
      if (request.getParameter(requiredParameter) == null) {
        throw new MissingParameterException(requiredParameter, requiredParameters);
      }
    }

    try {
      Integer reportCatalogEntryId =
          Integer.valueOf(WebSecurityUtils.safeParseInt(request.getParameter("locatorId")));

      String requestFormat = new String(request.getParameter("format"));

      if ((ReportFormat.PDF == ReportFormat.valueOf(requestFormat))
          || (ReportFormat.SVG == ReportFormat.valueOf(requestFormat))) {
        response.setContentType("application/pdf;charset=UTF-8");
        response.setHeader(
            "Content-disposition", "inline; filename=" + reportCatalogEntryId.toString() + ".pdf");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "cache");
        response.setHeader("Cache-Control", "must-revalidate");
      }
      if (ReportFormat.CSV == ReportFormat.valueOf(requestFormat)) {
        response.setContentType("text/csv;charset=UTF-8");
        response.setHeader(
            "Content-disposition", "inline; filename=" + reportCatalogEntryId.toString() + ".csv");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "cache");
        response.setHeader("Cache-Control", "must-revalidate");
      }
      m_reportStoreService.render(
          reportCatalogEntryId,
          ReportFormat.valueOf(requestFormat),
          (OutputStream) response.getOutputStream());
    } catch (NumberFormatException e) {
      // TODO something useful here.
    }

    return null;
  }