@RequestMapping(value = "/create-category", method = RequestMethod.POST)
  public String createCategory(
      Model model,
      @ModelAttribute("category") @Valid Category category,
      Errors errors,
      @RequestParam("name") String name,
      @RequestParam("description") String description) {

    model.addAttribute("title", "Create Category");

    Category newCategory =
        new Category(HtmlUtils.htmlEscape(name), HtmlUtils.htmlEscape(description));

    if (errors.hasErrors()) {
      model.addAttribute("category", category);
      return "create-category";
    }

    /*
     * What to do if there is no error
     * We need a DAO and Service to add category into the database
     */
    try {
      categoryService.createCategory(newCategory);
      model.addAttribute(
          "success",
          "<div class=\"info\">Succesfully Created <p> <a href='manage-category.html'>Go back to Management Page</a></div>"); // Add success message
      category.setName(""); // Reset form field
      category.setDescription(""); // Reset form field
    } catch (EJBException e) {
      model.addAttribute("error", e.getMessage());
    }

    return "create-category";
  }
  public ReservationView(
      Reservation reservation,
      ElementActionView deleteActionView,
      ElementActionView modifyActionView,
      ElementActionView copyActionView) {
    this.id = reservation.getId();
    this.virtualResourceGroup =
        reservation.getVirtualResourceGroup().map(g -> g.getName()).orElse("-");
    this.sourcePort = new PortView(reservation.getSourcePort());
    this.destinationPort = new PortView(reservation.getDestinationPort());
    // `<c:out>` strips newlines, so we have to manually HTML escape.
    this.failedReason = HtmlUtils.htmlEscape(reservation.formattedFailedReason(), "UTF-8");
    this.cancelReason = HtmlUtils.htmlEscape(reservation.getCancelReason(), "UTF-8");
    this.startDateTime = reservation.getStartDateTime();
    this.endDateTime = reservation.getEndDateTime().orElse(null);
    this.bandwidth = reservation.getBandwidth();
    this.userCreated = reservation.getUserCreated();
    this.providerConnectionId = reservation.getProviderConnectionId();
    this.creationDateTime = reservation.getCreationDateTime();
    this.protectionType = reservation.getRequesterConnection().getProtectionType();
    this.name = reservation.getName();
    NsiRequesterConnection connection = reservation.getRequesterConnection();
    this.requesterConnectionId = connection.getConnectionId();
    this.ero = presentEro(connection);

    states = connection.getStates().toShortString();
    reservationState = connection.getReservationState();
    provisionState = connection.getProvisionState().orElse(null);
    lifecycleState = connection.getLifecycleState();
    dataPlaneActive = connection.isDataPlaneActive();

    this.deleteActionView = deleteActionView;
    this.modifyActionView = modifyActionView;
    this.copyActionView = copyActionView;
  }
 @RequestMapping(value = "/resetforgotpassword", method = RequestMethod.POST)
 public String resetforgotPassword(HttpServletRequest request, ModelMap model) {
   String email = HtmlUtils.htmlEscape(request.getParameter("email"));
   if (email != null) {
     String userid = email;
     String password = HtmlUtils.htmlEscape(request.getParameter("password"));
     PersistenceManager pm = PMF.get().getPersistenceManager();
     Query q = pm.newQuery(User.class);
     q.setFilter("email==userid");
     q.declareParameters("String userid");
     List<User> result = (List<User>) q.execute(userid);
     try {
       User c = pm.getObjectById(User.class, result.get(0).getUserId());
       c.setPassword(password);
       model.addAttribute("registered", "Password reset successfully, Login now !!");
       model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     } finally {
       pm.close();
     }
     return "login";
   } else {
     model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     return "login";
   }
 }
Example #4
0
 String replaceStringLiterals(String content) {
   content =
       content.replaceAll(
           "%backup_initiated_by%",
           HtmlUtils.htmlEscape(backupService.backupRunningSinceISO8601()));
   content =
       content.replaceAll(
           "%backup_started_by%", HtmlUtils.htmlEscape(backupService.backupStartedBy()));
   return content;
 }
 @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
 public String authenticate(ModelMap model, HttpServletRequest request) {
   String email = HtmlUtils.htmlEscape(request.getParameter("email"));
   String password = HtmlUtils.htmlEscape(request.getParameter("password"));
   String p = HtmlUtils.htmlEscape(request.getParameter("p"));
   PersistenceManager pm = PMF.get().getPersistenceManager();
   Query q = pm.newQuery(Category.class);
   List<Category> result = null;
   model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
   try {
     result = (List<Category>) q.execute();
     if (result.isEmpty()) {
       model.addAttribute("listCategory", null);
     } else {
       model.addAttribute("listCategory", result);
     }
     pm = PMF.get().getPersistenceManager();
     Query q1 = null;
     q = pm.newQuery(User.class);
     q.setFilter("email == emailParam && password == passwordParam");
     // q.setOrdering("date desc");
     q.declareParameters("String emailParam,String passwordParam");
     List<User> results = (List<User>) q.execute(email, password);
     // System.out.println(email + " " + password + results.size());
     if (results.size() >= 1) {
       HttpSession hs = request.getSession(true);
       hs.setAttribute("userid", email);
       hs.setAttribute("username", results.get(0).getUserName());
       hs.setAttribute("collegeName", results.get(0).getCollege());
       hs.setAttribute("contactNo", results.get(0).getMobile());
       model.addAttribute("productDao", productDao);
       model.addAttribute("result", "Login Successfully!");
       if (p != null && (!p.equals("null")))
         // return new ModelAndView("redirect:"+p);
         return p;
       else return "index";
     } else {
       model.addAttribute("result", "Incorrect User ID or Password! Try Again");
       model.addAttribute("p", p);
       return "login";
     }
   } catch (Exception e) {
     e.printStackTrace();
     // System.out.println("in exception");
     model.addAttribute("result", "Incorrect Userid or Password! Try Again");
     return "login";
   } finally {
     q.closeAll();
     pm.close();
   }
 }
  @RequestMapping(value = "/edit-category/{categoryId}", method = RequestMethod.POST)
  public String doEditCategory(
      @ModelAttribute("category") @Valid Category category,
      Errors errors,
      @PathVariable String categoryId,
      @RequestParam("name") String name,
      @RequestParam("description") String description,
      Model model) {

    model.addAttribute("title", "Edit Category");

    if (errors.hasErrors()) {
      model.addAttribute("category", category);
      return "edit-category";
    }

    category = categoryService.getCategory(Integer.parseInt(HtmlUtils.htmlEscape(categoryId)));

    if (category == null) {
      return "redirect:manage-category.html";
    }
    category.setDescription(description);
    category.setName(name);

    categoryService.updateCategory(category);
    model.addAttribute(
        "info",
        "<div class=\"info\">Succesfully Updated <p> <a href='../manage-category.html'>Go back to Management Page</a></div>");

    return "edit-category";
  }
Example #7
0
  @ResponseBody
  @RequestMapping(method = RequestMethod.POST)
  public Object insert(Post post, String tags) {
    MapContainer form = PostFormValidator.validatePublish(post);
    if (!form.isEmpty()) {
      return form.put("success", false);
    }

    post.setId(optionManager.getNextPostid());
    post.setCreator(WebContextFactory.get().getUser().getId());
    post.setCreateTime(new Date());
    post.setLastUpdate(post.getCreateTime());

    /* 由于加入xss的过滤,html内容都被转义了,这里需要unescape */
    String content = HtmlUtils.htmlUnescape(post.getContent());
    post.setContent(JsoupUtils.filter(content));
    String cleanTxt = JsoupUtils.plainText(content);
    post.setExcerpt(
        cleanTxt.length() > PostConstants.EXCERPT_LENGTH
            ? cleanTxt.substring(0, PostConstants.EXCERPT_LENGTH)
            : cleanTxt);

    postManager.insertPost(post, PostTagHelper.from(post, tags, post.getCreator()));
    return new MapContainer("success", true);
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> names = request.getParameterNames();
    if (names.hasMoreElements()) {
      param = names.nextElement(); // just grab first element
    }

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='******'";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.PreparedStatement statement =
          connection.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS);
      statement.setString(1, "foo");
      statement.execute();
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  }
 @Override
 public void setAsText(String text) {
   String value = text;
   if (text != null) {
     value = HtmlUtils.htmlEscape(text, Constants.DEFAULT_CHARSET);
   }
   super.setAsText(value);
 }
 @RequestMapping("/login")
 public String userlogin(ModelMap map, HttpServletRequest request) {
   map.addAttribute("p", HtmlUtils.htmlEscape(request.getParameter("p")));
   HttpSession hs = request.getSession(false);
   if (hs != null && hs.getAttribute("userid") != null) {
     map.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     return "index";
   } else return "login";
 }
Example #11
0
 public Tag set(String attribute, String value) {
   if (attribute != null && value != null) {
     if (attributes == null) {
       attributes = Maps.newLinkedHashMap();
     }
     attributes.put(attribute, HtmlUtils.htmlEscape(value));
   }
   return this;
 }
  /** result name is encoded to prevent security issue with xss injection */
  protected void encodeResultName() {
    try {
      String tempResult = HtmlUtils.htmlEscape(resultName, "UTF-8");
      if (!tempResult.equals(resultName)) {
        resultName = URLEncoder.encode(resultName, "UTF-8");
      }

    } catch (Exception e) {
      log.debug("error with encoding search result name", e);
    }
  }
Example #13
0
 /**
  * Displays an informational message.
  *
  * @param message the message to display.
  * @return the model and view.
  */
 @RequestMapping(UiConstants.DISPLAY_INFO_MESSAGE_URL)
 public ModelAndView displayInfoMessage(
     @RequestParam(UiConstants.MODEL_KEY_MESSAGE) String message) {
   String viewName = UiConstants.DISPLAY_INFO_MESSAGE_PAGE;
   if (message == null) {
     return new ModelAndView(viewName);
   } else {
     return new ModelAndView(
         viewName, UiConstants.MODEL_KEY_MESSAGE, HtmlUtils.htmlEscape(message));
   }
 }
Example #14
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getQueryString();

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    Object[] obj = {"a", bar};
    response.getWriter().println(obj);
  }
  @RequestMapping(value = "/edit-category/{categoryId}", method = RequestMethod.GET)
  public String editCategory(@PathVariable String categoryId, Model model) {

    Category category =
        categoryService.getCategory(Integer.parseInt(HtmlUtils.htmlEscape(categoryId)));
    if (category == null) {
      return "redirect:manage-category.html";
    }
    model.addAttribute("category", category);
    return "edit-category";
  }
Example #16
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  final void processRequest(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException, CerberusException {
    response.setContentType("text/html;charset=UTF-8");
    final PrintWriter out = response.getWriter();
    final PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    try {
      final String type = policy.sanitize(request.getParameter("Type"));
      final String name = policy.sanitize(request.getParameter("Name"));
      // CTE - on utilise la méthode utilitaire pour encoder le xml
      final String envelope = request.getParameter("Envelope");
      final String envelopeBDD = HtmlUtils.htmlEscape(envelope);
      final String description = policy.sanitize(request.getParameter("Description"));
      final String servicePath = policy.sanitize(request.getParameter("ServicePath"));
      final String parsingAnswer = policy.sanitize(request.getParameter("ParsingAnswer"));
      final String method = policy.sanitize(request.getParameter("Method"));

      final ApplicationContext appContext =
          WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
      final ISoapLibraryService soapLibraryService = appContext.getBean(ISoapLibraryService.class);
      final IFactorySoapLibrary factorySoapLibrary = appContext.getBean(IFactorySoapLibrary.class);

      final SoapLibrary soapLib =
          factorySoapLibrary.create(
              type, name, envelopeBDD, description, servicePath, parsingAnswer, method);
      soapLibraryService.createSoapLibrary(soapLib);

      /** Adding Log entry. */
      ILogEventService logEventService = appContext.getBean(LogEventService.class);
      IFactoryLogEvent factoryLogEvent = appContext.getBean(FactoryLogEvent.class);
      try {
        logEventService.insertLogEvent(
            factoryLogEvent.create(
                0,
                0,
                request.getUserPrincipal().getName(),
                null,
                "/CreateSoapLibrary",
                "CREATE",
                "Create SoapLibrary : " + name,
                "",
                ""));
      } catch (CerberusException ex) {
        org.apache.log4j.Logger.getLogger(CreateSoapLibrary.class.getName())
            .log(org.apache.log4j.Level.ERROR, null, ex);
      }

      response.sendRedirect("SoapLibrary.jsp");
    } finally {
      out.close();
    }
  }
  @RequestMapping(value = "/delete-category/{categoryId}", method = RequestMethod.GET)
  public String deleteCategory(@PathVariable String categoryId, Model model) {
    try {
      categoryService.deleteCategory(Integer.parseInt(HtmlUtils.htmlEscape(categoryId)));
      model.addAttribute(
          "info",
          "<div class=\"info\">Succesfully Deleted <p> <a href='../manage-category.html'>Go back to Management Page</a></div>");
    } catch (EJBTransactionRolledbackException e) {
      model.addAttribute(
          "info",
          "<div class=\"info\">Category Doesn't Existed <p> <a href='../manage-category.html'>Go back to Management Page</a></div>");
    }

    return "manage-category";
  }
  public String toHtml(String query, String keywordClass) {
    String sql = formatter.prettyPrint(query);
    sql = HtmlUtils.htmlEscape(sql);
    for (int i = 0; i < KEYWORDS.length; i++) {
      String keyword = KEYWORDS[i][0];
      String selectorSuffix = KEYWORDS[i][1];

      if (sql.contains(keyword)) {
        String spanTag = makeSpanTag(keywordClass, selectorSuffix);
        String replace = new StringBuilder(spanTag).append(keyword).append("</span>").toString();
        sql = sql.replace(keyword, replace);
      }
    }
    return sql;
  }
Example #19
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    Object[] obj = {"a", bar};

    response.getWriter().printf(java.util.Locale.US, "notfoo", obj);
  }
Example #20
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getHeader("foo");

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    String sql = "UPDATE USERS SET PASSWORD='******' WHERE USERNAME='******'";

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      int count = statement.executeUpdate(sql, new String[] {"user", "password"});
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  }
  @RequestMapping(method = RequestMethod.GET)
  public void viewSource(
      @RequestParam("file") String file, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (!enabled) {
      throw (new OpenLegacyRuntimeException("View source controller is not enabled"));
    }

    ServletContext servletContext = request.getSession().getServletContext();

    InputStream resource = servletContext.getResourceAsStream(file);
    if (resource == null) {
      throw (new OpenLegacyRuntimeException("Specified resource doesn''t exists"));
    }
    String content = IOUtils.toString(resource);
    content = HtmlUtils.htmlEscape(content);
    response.getWriter().write(MessageFormat.format(htmlOutput, content));
  }
  public String[] getStringTable(String parameter, HttpServletRequest request, boolean toEscape) {

    if (request.getParameterValues(parameter) != null) {
      try {
        request.setCharacterEncoding("UTF-8");
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      String[] parameters = request.getParameterValues(parameter);
      if (toEscape) {
        for (int i = 0; i < parameters.length; i++) {
          parameters[i] = HtmlUtils.htmlEscape(parameters[i]);
        }
      }
      return parameters;
    }
    return new String[0];
  }
  private void writeSheet(
      List<Map<String, String>> valueMaps, String worksheetName, HSSFWorkbook wb) {
    // Set column widths
    HSSFSheet sheet = wb.createSheet(worksheetName);
    sheet.setColumnWidth(Short.parseShort("0"), Short.parseShort("15000"));
    sheet.setColumnWidth(Short.parseShort("1"), Short.parseShort("30000"));

    // header style
    HSSFCellStyle headerStyle;
    HSSFFont headerFont = wb.createFont();
    headerFont.setFontHeightInPoints((short) 11);
    headerStyle = wb.createCellStyle();
    headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    headerStyle.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
    headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    headerStyle.setFont(headerFont);
    headerStyle.setWrapText(true);

    // header row
    HSSFRow headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(30);
    HSSFCell headerCell0 = headerRow.createCell((short) 0);
    HSSFCell headerCell1 = headerRow.createCell((short) 1);

    headerCell0.setCellStyle(headerStyle);
    setText(headerCell0, "Layer Name");
    headerCell1.setCellStyle(headerStyle);
    setText(headerCell1, "Message");

    int counter = 1;
    for (Map<String, String> valueMap : valueMaps) {
      HSSFRow dataRow = sheet.createRow(counter);
      String layer = valueMap.get("layer");
      String status = valueMap.get("status");
      status = HtmlUtils.htmlUnescape(status);
      HSSFCell currentCell0 = dataRow.createCell((short) 0);
      HSSFCell currentCell1 = dataRow.createCell((short) 1);
      setText(currentCell0, layer);
      setText(currentCell1, status);
      counter++;
    }
  }
Example #24
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    try {
      javax.naming.directory.InitialDirContext idc =
          org.owasp.benchmark.helpers.Utils.getInitialDirContext();
      idc.search("name", bar, new javax.naming.directory.SearchControls());
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    }
  }
Example #25
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    String sql = "UPDATE USERS SET PASSWORD='******' WHERE USERNAME='******'";

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      int count = statement.executeUpdate(sql);
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  }
  @RequestMapping(value = "/jobs/{jobName}", method = RequestMethod.GET)
  public String details(
      ModelMap model,
      @ModelAttribute("jobName") String jobName,
      Errors errors,
      @RequestParam(defaultValue = "0") int startJobInstance,
      @RequestParam(defaultValue = "20") int pageSize) {

    boolean launchable = jobService.isLaunchable(jobName);

    try {

      Collection<JobInstance> result =
          jobService.listJobInstances(jobName, startJobInstance, pageSize);
      Collection<JobInstanceInfo> jobInstances = new ArrayList<JobInstanceInfo>();
      model.addAttribute(
          "jobParameters",
          jobParametersExtractor.fromJobParameters(jobService.getLastJobParameters(jobName)));

      for (JobInstance jobInstance : result) {
        Collection<JobExecution> jobExecutions =
            jobService.getJobExecutionsForJobInstance(jobName, jobInstance.getId());
        jobInstances.add(new JobInstanceInfo(jobInstance, jobExecutions, timeZone));
      }

      model.addAttribute("jobInstances", jobInstances);
      int total = jobService.countJobInstances(jobName);
      TableUtils.addPagination(model, total, startJobInstance, pageSize, "JobInstance");
      int count = jobService.countJobExecutionsForJob(jobName);
      model.addAttribute(
          "jobInfo", new JobInfo(jobName, count, launchable, jobService.isIncrementable(jobName)));

    } catch (NoSuchJobException e) {
      errors.reject(
          "no.such.job",
          new Object[] {jobName},
          "There is no such job (" + HtmlUtils.htmlEscape(jobName) + ")");
    }

    return "jobs/job";
  }
 @RequestMapping(value = "/resetpassword", method = RequestMethod.POST)
 public ModelAndView resetPassword(HttpServletRequest request, ModelMap model) {
   HttpSession hs = request.getSession(false);
   if (hs != null) {
     String userid = (String) hs.getAttribute("userid");
     String password = HtmlUtils.htmlEscape(request.getParameter("password"));
     PersistenceManager pm = PMF.get().getPersistenceManager();
     Query q = pm.newQuery(User.class);
     q.setFilter("email==userid");
     q.declareParameters("String userid");
     List<User> result = (List<User>) q.execute(userid);
     try {
       User c = pm.getObjectById(User.class, result.get(0).getUserId());
       c.setPassword(password);
       model.addAttribute("resultresetpage", "Password reset successfully");
     } finally {
       pm.close();
     }
     return new ModelAndView("redirect:resetpassword");
   } else return new ModelAndView("redirect:resetpassword");
 }
Example #28
0
  private static String doSomething(String param) throws ServletException, IOException {

    String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);

    return bar;
  }
Example #29
0
 /**
  * html转义->html
  *
  * @param html
  * @return
  */
 public static String htmlUnescape(String html) {
   return HtmlUtils.htmlUnescape(html);
 }
 @RequestMapping(params = "demoTurn")
 @ResponseBody
 public String demoTurn(String id) {
   String code = systemService.get(TSDemo.class, id).getDemocode();
   return HtmlUtils.htmlUnescape(code);
 }