Example #1
0
  private ArrayList<MusicInfo> getMusicInfoListFromHtml(String html)
      throws UnsupportedEncodingException {
    Utils.D("+++++++++++++++");
    Utils.D(html);
    Utils.D("+++++++++++++++");

    ArrayList<MusicInfo> musicList = new ArrayList<MusicInfo>();
    Matcher matcherRow = PATTERN_ROW.matcher(html);
    while (matcherRow.find()) {
      Matcher m = PATTERN.matcher(matcherRow.group(1));
      while (m.find()) {
        MusicInfo info = new MusicInfo();
        info.setTitle(StringEscapeUtils.unescapeHtml(m.group(1).trim()));
        info.setArtist(
            StringEscapeUtils.unescapeHtml(URLDecoder.decode(m.group(2), "gb2312").trim()));
        info.setAlbum(StringEscapeUtils.unescapeHtml(m.group(3).trim()));
        info.addUrl(SOGOU_MP3 + m.group(4).trim());
        // TODO(zyu): Fix lyrics.
        //					info.setLyricUrl(SOGOU_MP3 + m.group(5).trim());
        String displayFileSize = m.group(6).trim();
        if (displayFileSize.equals("未知")) displayFileSize = "Unknown size";
        info.setDisplayFileSize(displayFileSize);
        info.setType(m.group(7).trim());

        musicList.add(info);
      }
    }
    Utils.D("Exit getMusicInfoListFromHtml");
    return musicList;
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b())
            .goodB2G_source(request, response);

    final String xmldoc =
        "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml";

    /* assume username||password as source */
    String[] tokens = data.split("||");
    if (tokens.length < 2) {
      return;
    }

    /* FIX: validate input using StringEscapeUtils */
    String uname = StringEscapeUtils.escapeXml(tokens[0]);
    String pword = StringEscapeUtils.escapeXml(tokens[1]);

    /* build xpath */
    XPath xp = XPathFactory.newInstance().newXPath();
    InputSource inxml = new InputSource(xmldoc);

    String query =
        "//users/user[name/text()='"
            + uname
            + "' and pass/text()='"
            + pword
            + "']"
            + "/secret/text()";
    String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING);
  }
  public void validate(Object obj, Errors errors, MemberService service) {

    Member member = (Member) obj;

    String escapedName = StringEscapeUtils.escapeJava(member.getFullName());
    String escapedPassword = StringEscapeUtils.escapeJavaScript(member.getPassword());
    String escapedEmailAddress = StringEscapeUtils.escapeJavaScript(member.getEmailAddress());
    String escapedTown = StringEscapeUtils.escapeJavaScript(member.getTown());
    String escapedUsername = StringEscapeUtils.escapeJavaScript(member.getUserName());

    if (escapedName.equals("") || escapedName.length() < 10) {
      errors.reject("name", "Fullname shouldn't be empty");
    }
    if (escapedPassword.length() < 10) {
      errors.reject("password", "Password should consists atleast of 10 symbols");
    }
    if (escapedEmailAddress == null || escapedEmailAddress.indexOf("@") < 0) {
      errors.reject("emailaddress", "Email address should be valid");
    }
    if (escapedTown == null || escapedTown.equals("")) {
      errors.reject("town", "Town shouldn't be empty");
    }
    if (escapedUsername == null || escapedUsername.length() < 8) {
      errors.reject("userName", "username should be longer");
    }

    if (service.getMember(escapedUsername) > 0) {
      errors.reject("userNameExists", "user with provided username already exists");
    }
    member.setFullName(escapedName);
    member.setEmailAddress(escapedEmailAddress);
    member.setPassword(escapedPassword);
    member.setTown(escapedTown);
  }
  public static ArrayList<CommentEntry> execute(CommentTask commentTask, String html) {
    ArrayList<CommentEntry> entryList = new ArrayList<CommentEntry>();

    html = html.replace("<dd class=\"re_detail\">", "分");
    String pattern =
        "第(\\d+)[^<]+</strong>([^发]+)发表于([^<]+)[^分]+分([^<]+)[^支]+支持</a>\\(<span id=\"support([h\\d]+)\">(\\d+)[^反]+反对</a>[^>]+>(\\d+)";

    Matcher matcher = Pattern.compile(pattern).matcher(html);
    while (matcher.find()) {
      String liveId = matcher.group(1).trim();
      String name =
          StringEscapeUtils.unescapeHtml(
              matcher.group(2).trim().replace("\r", "").replace("\n", ""));
      String date = matcher.group(3).trim();
      String message = StringEscapeUtils.unescapeHtml(matcher.group(4).trim().replace("\r", ""));
      String unknow = matcher.group(5).trim();
      String supportNumber = matcher.group(6).trim();
      String unSupportNumber = matcher.group(7).trim();

      entryList.add(
          new CommentEntry(liveId, name, date, message, unknow, supportNumber, unSupportNumber));
    }

    return entryList;
  }
 public IDataWriter getDataWriter(
     String sourceNodeId,
     ISymmetricDialect symmetricDialect,
     TransformWriter transformWriter,
     List<IDatabaseWriterFilter> filters,
     List<IDatabaseWriterErrorHandler> errorHandlers,
     List<? extends Conflict> conflictSettings,
     List<ResolvedData> resolvedData) {
   int maxRowsBeforeFlush =
       parameterService.getInt("mssql.bulk.load.max.rows.before.flush", 100000);
   boolean fireTriggers = parameterService.is("mssql.bulk.load.fire.triggers", false);
   String uncPath = parameterService.getString("mssql.bulk.load.unc.path");
   String rowTerminator =
       StringEscapeUtils.unescapeJava(
           parameterService.getString("mssql.bulk.load.row.terminator", "\\r\\n"));
   String fieldTerminator =
       StringEscapeUtils.unescapeJava(
           parameterService.getString("mssql.bulk.load.field.terminator", "||"));
   return new MsSqlBulkDatabaseWriter(
       symmetricDialect.getPlatform(),
       stagingManager,
       jdbcExtractor,
       maxRowsBeforeFlush,
       fireTriggers,
       uncPath,
       fieldTerminator,
       rowTerminator);
 }
 public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
   response.setStatus(HttpServletResponse.SC_OK);
   String vsName = request.getParameter("name");
   VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
   if (logger.isInfoEnabled())
     logger.info(
         new StringBuilder()
             .append("Structure request for *")
             .append(vsName)
             .append("* received.")
             .toString());
   StringBuilder sb =
       new StringBuilder("<virtual-sensor name=\"")
           .append(vsName)
           .append("\" last-modified=\"")
           .append(new File(sensorConfig.getFileName()).lastModified())
           .append("\">\n");
   for (KeyValue df : sensorConfig.getAddressing())
     sb.append("<predicate key=\"")
         .append(StringEscapeUtils.escapeXml(df.getKey().toString()))
         .append("\">")
         .append(StringEscapeUtils.escapeXml(df.getValue().toString()))
         .append("</predicate>\n");
   sb.append("</virtual-sensor>");
   response.setHeader("Cache-Control", "no-store");
   response.setDateHeader("Expires", 0);
   response.setHeader("Pragma", "no-cache");
   response.getWriter().write(sb.toString());
 }
Example #7
0
  /** Returns the contents of this page (title + text). */
  public String getContent() {
    String s = getWikiMarkup();

    // Bliki doesn't seem to properly handle inter-language links, so remove manually.
    s = LANG_LINKS.matcher(s).replaceAll(" ");

    wikiModel.setUp();
    s = getTitle() + "\n" + wikiModel.render(textConverter, s);
    wikiModel.tearDown();

    // The way the some entities are encoded, we have to unescape twice.
    s = StringEscapeUtils.unescapeHtml(StringEscapeUtils.unescapeHtml(s));

    s = REF.matcher(s).replaceAll(" ");
    s = HTML_COMMENT.matcher(s).replaceAll(" ");

    // Sometimes, URL bumps up against comments e.g., <!-- http://foo.com/-->
    // Therefore, we want to remove the comment first; otherwise the URL pattern might eat up
    // the comment terminator.
    s = URL.matcher(s).replaceAll(" ");
    s = DOUBLE_CURLY.matcher(s).replaceAll(" ");
    s = HTML_TAG.matcher(s).replaceAll(" ");

    return s;
  }
Example #8
0
 /**
  * 根据条件查询站内信(管理员与用户,用户与用户)
  *
  * @throws SQLException
  * @throws DataException
  */
 public void queryMailByCondition(
     PageBean pageBean, Integer mailType, String sender, String beginTime, String endTime)
     throws SQLException, DataException {
   Connection conn = connectionManager.getConnection();
   StringBuffer condition = new StringBuffer("and backgroundStatus!=2 ");
   if (mailType != null) {
     condition.append("and mailType=");
     condition.append(mailType);
   }
   if (StringUtils.isNotBlank(sender)) {
     condition.append(" and sender LIKE '%");
     condition.append(StringEscapeUtils.escapeSql(sender));
     condition.append("%'");
   }
   if (StringUtils.isNotBlank(beginTime)) {
     condition.append(" and sendTime >= '");
     condition.append(StringEscapeUtils.escapeSql(beginTime));
     condition.append("'");
   }
   if (StringUtils.isNotBlank(endTime)) {
     condition.append(" and sendTime <= '");
     condition.append(StringEscapeUtils.escapeSql(endTime));
     condition.append("'");
   }
   try {
     dataPage(conn, pageBean, "t_mail", "*", " order by sendTime desc ", condition.toString());
   } catch (DataException e) {
     log.error(e);
     e.printStackTrace();
   } finally {
     conn.close();
   }
 }
Example #9
0
  public static Document toDocument(ResultSet rs)
      throws ParserConfigurationException, SQLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
      Element row = doc.createElement("Row");
      results.appendChild(row);

      for (int i = 1; i <= colCount; i++) {
        String columnName = StringEscapeUtils.escapeXml(rsmd.getColumnName(i));
        String value = StringEscapeUtils.escapeXml(oscar.Misc.getString(rs, i));

        Element node = doc.createElement(columnName);
        node.appendChild(doc.createTextNode(value));
        row.appendChild(node);
      }
    }
    rs.close();
    return doc;
  }
 /**
  * Replace the separator with whitespaces and unescape the String
  *
  * @param name
  * @return
  */
 public static String unSanitizeName(String name) {
   final String SEPARATOR = "_";
   if (name.contains(SEPARATOR)) {
     return StringEscapeUtils.unescapeJavaScript(name).replaceAll(SEPARATOR, " ").trim();
   }
   return StringEscapeUtils.unescapeJavaScript(name).trim();
 }
 private String genTemplate(String tableId, String tmplId) throws Exception {
   BpmFormTable bpmFormTable = bpmFormTableService.getBpmFormTableById(tableId);
   List<BpmFormField> fields = this.bpmFormFieldService.getBpmFormFieldByTableId(tableId);
   for (BpmFormField field : fields) {
     field.setFieldName(
         new StringBuilder()
             .append(bpmFormTable.getIsMain().equals("1") ? "m:" : "s:")
             .append(bpmFormTable.getTableName())
             .append(":")
             .append(field.getFieldName())
             .toString());
   }
   Map<String, Object> fieldsMap = new HashMap<String, Object>();
   fieldsMap.put("table", bpmFormTable);
   fieldsMap.put("fields", fields);
   BpmFormTemplate mainTemplate = bpmFormTemplateService.getBpmFormTemplateById(tmplId);
   BpmFormTemplate macroTemplate =
       bpmFormTemplateService.getBpmFormTemplateByAlias(mainTemplate.getMacroTemplateAlias());
   String macroHtml = "";
   if (macroTemplate != null) {
     macroHtml = StringEscapeUtils.unescapeHtml(macroTemplate.getHtml());
   }
   String mainTplHtml = StringEscapeUtils.unescapeHtml(mainTemplate.getHtml());
   String result =
       this.freemarkEngine.parseByStringTemplate(
           fieldsMap, new StringBuilder().append(macroHtml).append(mainTplHtml).toString());
   return result;
 }
 private String getPart(String str, int beginIndex, int endIndex) {
   return StringEscapeUtils.escapeJavaScript(
       StringEscapeUtils.unescapeJavaScript(str)
           .substring(
               beginIndex,
               Math.min(endIndex, StringEscapeUtils.unescapeJavaScript(str).length())));
 }
Example #13
0
 public void send() {
   EventBus eventBus = EventBusFactory.getDefault().eventBus();
   eventBus.publish(
       CHANNEL,
       new FacesMessage(
           StringEscapeUtils.escapeHtml(summary), StringEscapeUtils.escapeHtml(detail)));
 }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(
      CWE643_Unsafe_Treatment_of_XPath_Input__fromFile_67a.Container data_container)
      throws Throwable {
    String data = data_container.a;

    final String xmldoc =
        "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml";

    /* assume username||password as source */
    String[] tokens = data.split("||");
    if (tokens.length < 2) {
      return;
    }

    /* FIX: validate input using StringEscapeUtils */
    String uname = StringEscapeUtils.escapeXml(tokens[0]);
    String pword = StringEscapeUtils.escapeXml(tokens[1]);

    /* build xpath */
    XPath xp = XPathFactory.newInstance().newXPath();
    InputSource inxml = new InputSource(xmldoc);

    String query =
        "//users/user[name/text()='"
            + uname
            + "' and pass/text()='"
            + pword
            + "']"
            + "/secret/text()";
    String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING);
  }
Example #15
0
  @SuppressWarnings({"unchecked"})
  private void handleIssueRequest(
      PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp, String uri)
      throws IOException {
    if (req.getParameter("embed") == null) {
      show404(resp);
      return;
    }
    Pattern p = Pattern.compile("/issues/([^/?]+)");
    Matcher m = p.matcher(uri);
    if (!m.matches()) {
      show404(resp);
      return;
    }
    String hash = m.group(1);
    Map<String, DbIssue> map = persistenceHelper.findIssues(pm, Lists.<String>newArrayList(hash));
    DbIssue issue = map.get(hash);
    if (issue == null) {
      printHtmlPreface(resp);
      resp.getWriter()
          .println("<p>This issue has not been submitted to the " + getCloudName() + "</p>");
      LOGGER.info("Not in cloud");
      return;
    }

    List<DbEvaluation> list = Lists.newArrayList(sortAndFilterEvaluations(issue.getEvaluations()));
    LOGGER.info("Issue " + issue.getPrimaryClass() + " - " + list.size() + " comments");
    if (list.isEmpty()) {
      printHtmlPreface(resp);
      resp.getWriter().println("<p>No comments have been submitted for this issue</p>");
      return;
    }
    Collections.reverse(list);

    PrintWriter out = resp.getWriter();
    printHtmlPreface(resp);
    out.println("<table border=0 class=popup-evals cellspacing=15>");
    for (DbEvaluation evaluation : list) {
      out.println("<tr>");
      out.println(
          "<td>"
              + StringEscapeUtils.escapeHtml(evaluation.getEmail())
              + "<br><span class=timestamp>"
              + TIMESTAMP_FORMAT().format(new Date(evaluation.getWhen()))
              + " </span></td>");

      out.println(
          "<td><strong>"
              + StringEscapeUtils.escapeHtml(evaluation.getDesignation())
              + "</strong>"
              + " &mdash; "
              + StringEscapeUtils.escapeHtml(evaluation.getComment())
              + "</td>");
      out.println("</tr>");
    }
    out.println("</table>");
  }
  /**
   * DB환경 정보 파일을 올바른 정보로 바꾸어준다.
   *
   * @param dbInfo
   * @return
   * @throws Exception
   */
  private static String getConfig(UserDBDAO dbInfo) throws Exception {
    String config = getFileToString(dbInfo.getDBDefine().getLocation());

    config = config.replace(URL, StringEscapeUtils.escapeXml(dbInfo.getUrl()));
    config = config.replace(USERNAME, StringEscapeUtils.escapeXml(dbInfo.getUsers()));
    config = config.replace(PASSWORD, StringEscapeUtils.escapeXml(dbInfo.getPasswd()));

    return config;
  }
 private String encodeHLink(String uri_string, String name) throws URISyntaxException {
   // System.out.println("linking: >>"+uri_string);
   // URI uri = new URI(uri_string);
   return ("<a href="
       + StringEscapeUtils.escapeHtml(uri_string)
       + ">"
       + StringEscapeUtils.escapeHtml(name)
       + "</a>");
 }
Example #18
0
 @Override
 public void setXML(Element textElem) {
   setMultiLine(Boolean.parseBoolean(textElem.getAttributeValue("multiLine")));
   setReadOnly(Boolean.parseBoolean(textElem.getAttributeValue("readOnly")));
   setLabel(StringEscapeUtils.unescapeXml(textElem.getAttributeValue("label")));
   savedText = textElem.getText();
   setText(StringEscapeUtils.unescapeXml(savedText));
   checkCursorPosition();
 }
Example #19
0
  public static String highlight(String text, String[] words) {
    if (text == null) {
      return null;
    }
    if (words == null || words.length == 0) {
      return text;
    }
    // TODO Consider using a primitive array
    List<Pair<Integer, Integer>> positions = Lists.newArrayList();
    String lower = text.toLowerCase();
    for (int i = 0; i < words.length; i++) {
      String word = words[i].toLowerCase();
      int start = 0;
      while (start != -1) {
        start = lower.indexOf(word, start);
        if (start != -1) {
          int end = start + word.length();
          positions.add(Pair.of(start, end));
          start++;
        }
      }
    }
    if (positions.isEmpty()) {
      return text;
    }
    Collections.sort(
        positions,
        new Comparator<Pair<Integer, Integer>>() {

          @Override
          public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
            int comparison = o1.getKey().compareTo(o2.getKey());
            if (comparison == 0) {
              return o2.getValue().compareTo(o1.getValue());
            }
            return comparison;
          }
        });

    StringBuilder out = new StringBuilder();
    int pos = 0;
    for (Pair<Integer, Integer> position : positions) {
      int from = position.getKey();
      int to = position.getValue();
      if (from >= pos) {
        String sub = text.substring(pos, from);
        out.append(StringEscapeUtils.escapeXml(sub));
        out.append("<em>");
        out.append(StringEscapeUtils.escapeXml(text.substring(from, to)));
        out.append("</em>");
        pos = to;
      }
    }
    out.append(text.substring(pos));
    return out.toString();
  }
Example #20
0
 @Override
 public boolean onCommand(
     final CommandSender sender, final Command cmd, final String label, final String args[]) {
   if (cmd.getName().equalsIgnoreCase("punish")) {
     if (args.length < 2) {
       sender.sendMessage(ChatColor.RED + "Not enough parameters!");
       sender.sendMessage(ChatColor.RED + "Usage: /punish [@]<player> <reason>");
     } else {
       Boolean pOffline = false;
       String ofpl = "";
       if (args[0].startsWith("@")) {
         pOffline = true;
         StringBuilder sb = new StringBuilder();
         sb.append(args[0]);
         sb.deleteCharAt(0);
         ofpl = sb.toString();
         ofpl = StringEscapeUtils.escapeSql(ofpl);
       } else if (plugin.getServer().getPlayer(args[0]) == null) {
         sender.sendMessage(
             args[0] + " is not online! Use /p @<player> to punish offline players!");
         return true;
       }
       ArrayList<String> arguments = new ArrayList<String>();
       for (String s : args) {
         if (s != args[0]) arguments.add(s);
       }
       if (pOffline && sender instanceof Player) {
         Player player = (Player) sender;
         punishOffline(
             sender.getName(),
             StringEscapeUtils.escapeSql(player.getDisplayName()),
             ofpl,
             arguments);
       } else if (pOffline && sender instanceof ConsoleCommandSender) {
         punishOffline("(console)", ChatColor.GOLD + "(console)", ofpl, arguments);
       } else if (!pOffline && sender instanceof Player) {
         Player player = (Player) sender;
         punish(
             sender.getName(),
             StringEscapeUtils.escapeSql(player.getDisplayName()),
             plugin.getServer().getPlayer(args[0]).getName(),
             plugin.getServer().getPlayer(args[0]).getDisplayName(),
             arguments);
       } else if (!pOffline && sender instanceof ConsoleCommandSender) {
         punish(
             "(console)",
             ChatColor.GOLD + "(console)",
             plugin.getServer().getPlayer(args[0]).getName(),
             plugin.getServer().getPlayer(args[0]).getDisplayName(),
             arguments);
       }
     }
     return true;
   }
   return false;
 }
 /*
  * We're updating a key--make sure it is active as well
  */
 public boolean updateKeyValue(String billingNo, String key, String value) {
   List<BillingONExt> results =
       extDao.findByBillingNoAndKey(Integer.parseInt(billingNo), StringEscapeUtils.escapeSql(key));
   for (BillingONExt result : results) {
     result.setValue(StringEscapeUtils.escapeSql(value));
     result.setStatus('1');
     extDao.merge(result);
   }
   return true;
 }
Example #22
0
 private void appendHeader(RulesProfile profile, Writer writer) throws IOException {
   writer.append(
       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
           + "<!-- Generated by Sonar -->"
           + "<profile><name>");
   StringEscapeUtils.escapeXml(writer, profile.getName());
   writer.append("</name><language>");
   StringEscapeUtils.escapeXml(writer, profile.getLanguage());
   writer.append("</language>");
 }
Example #23
0
 private void appendRuleParameter(Writer writer, ActiveRuleParam activeRuleParam)
     throws IOException {
   if (StringUtils.isNotBlank(activeRuleParam.getValue())) {
     writer.append("<parameter><key>");
     StringEscapeUtils.escapeXml(writer, activeRuleParam.getKey());
     writer.append("</key><value>");
     StringEscapeUtils.escapeXml(writer, activeRuleParam.getValue());
     writer.append("</value>");
     writer.append("</parameter>");
   }
 }
    @Override
    public String getStringValue() {

      if (this.object != null) {
        return JsonFormatter.format(StringEscapeUtils.unescapeJavaScript(this.object.toString()));
      } else if (this.array != null) {
        return JsonFormatter.format(StringEscapeUtils.unescapeJavaScript(this.array.toString()));
      } else {
        return null;
      }
    }
  public String serializeComponentData() throws Exception {
    // Serialize visible properties and options.
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    int indent = 0;
    printIndent(out, indent);
    out.println("<dashboard_filter>");
    Iterator it = properties.iterator();
    while (it.hasNext()) {
      DashboardFilterProperty dashboardFilterProperty = (DashboardFilterProperty) it.next();
      printIndent(out, indent + 1);
      out.println(
          "<property id=\""
              + StringEscapeUtils.escapeXml(dashboardFilterProperty.getPropertyId())
              + "\" providerCode =\""
              + StringEscapeUtils.escapeXml(dashboardFilterProperty.getDataProviderCode())
              + "\">");
      printIndent(out, indent + 2);
      out.println("<visible>" + dashboardFilterProperty.isVisible() + "</visible>");
      if (dashboardFilterProperty.getSectionId() != null) {
        printIndent(out, indent + 2);
        out.println("<section>" + dashboardFilterProperty.getSectionId() + "</section>");
      }
      printIndent(out, indent + 1);
      out.println("</property>");
    }

    // Serialize options.
    printIndent(out, indent + 1);
    out.println("<options>");
    printIndent(out, indent + 2);
    out.println("<shortViewMode>" + isShortMode + "</shortViewMode>");
    printIndent(out, indent + 2);
    out.println("<showLegend>" + showLegend + "</showLegend>");
    printIndent(out, indent + 2);
    out.println("<showRefreshButton>" + showRefreshButton + "</showRefreshButton>");
    printIndent(out, indent + 2);
    out.println("<showApplyhButton>" + showApplyButton + "</showApplyhButton>");
    printIndent(out, indent + 2);
    out.println("<showClearButton>" + showClearButton + "</showClearButton>");
    printIndent(out, indent + 2);
    out.println("<showPropertyNames>" + showPropertyNames + "</showPropertyNames>");
    printIndent(out, indent + 2);
    out.println("<showSubmitOnChange>" + showSubmitOnChange + "</showSubmitOnChange>");
    printIndent(out, indent + 1);
    out.println("<showAutoRefresh>" + showAutoRefresh + "</showAutoRefresh>");
    printIndent(out, indent + 1);
    out.println("</options>");
    printIndent(out, indent);

    out.println("</dashboard_filter>");
    serializedProperties = sw.toString();
    return sw.toString();
  }
Example #26
0
 private void exportProperty(String name, String value, String type) {
   m_out.println(
       "  <sv:property sv:name='"
           + StringEscapeUtils.escapeXml(name)
           + "' sv:type='"
           + type
           + "'>");
   m_out.print("    <sv:value>");
   m_out.print(StringEscapeUtils.escapeXml(value));
   m_out.println("</sv:value>");
   m_out.println("  </sv:property>");
 }
  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    //   return new ModelAndView(getSuccessView());
    //  }

    /*    protected ModelAndView onSubmit(
    HttpServletRequest request,
    HttpServletResponse response,
    Object command,
    BindException errors)
    throws ServletException, Exception {*/

    StringEscapeUtils esc = new StringEscapeUtils();

    setTitle(esc.escapeXml(request.getParameter("title")));
    setLink(esc.escapeXml(request.getParameter("link")));
    setDescription(esc.escapeXml(request.getParameter("description")));

    // create timestamp
    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    Date date = new Date();
    publishDate = formatter.format(date);
    String item = "";
    item =
        (new StringBuilder())
            .append("<item>" + NEW_LINE)
            .append("<title>")
            .append(title)
            .append("</title>" + NEW_LINE)
            .append("<link>")
            .append(link)
            .append("</link>" + NEW_LINE)
            .append("<description>")
            .append(description)
            .append("</description>" + NEW_LINE)
            .append("<pubDate>")
            .append(publishDate)
            .append("</pubDate>" + NEW_LINE)
            .append("</item>" + NEW_LINE)
            .toString();
    try {
      BufferedWriter out =
          new BufferedWriter(new FileWriter(getFileLocation() + getFileName(), true));
      out.write(item);
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new ModelAndView(getSuccessView());
  }
 protected void setTableAttributes(TableHandler tableHandler) {
   Table table = tableHandler.getTable();
   setAttribute("currentpage", table.getCurrentPage());
   setAttribute("rowcount", table.getRowCount());
   setAttribute("maxrowspage", table.getMaxRowsPerPage());
   setAttribute("headerposition", table.getHeaderPosition());
   setAttribute(
       "htmlstyleedit",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getHtmlStyle())));
   setAttribute(
       "rowevenstyleedit",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getRowEvenStyle())));
   setAttribute(
       "rowoddstyleedit",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getRowOddStyle())));
   setAttribute(
       "rowhoverstyleedit",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getRowHoverStyle())));
   setAttribute(
       "htmlclass", StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getHtmlClass())));
   setAttribute(
       "rowevenclass",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getRowEventClass())));
   setAttribute(
       "rowoddclass",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getRowOddClass())));
   setAttribute(
       "rowhoverclass",
       StringUtils.defaultString(StringEscapeUtils.escapeHtml(table.getRowHoverClass())));
   setAttribute("htmlstyleview", table.getHtmlStyle());
 }
Example #29
0
 /**
  * Build the HTML anchor link to a topic page for a given WikLink object.
  *
  * @param context The servlet context for the link that is being created.
  * @param virtualWiki The virtual wiki for the link that is being created.
  * @param wikiLink The WikiLink object containing all relevant information about the link being
  *     generated.
  * @param text The text to display as the link content.
  * @param style The CSS class to use with the anchor HTML tag. This value can be <code>null</code>
  *     or empty if no custom style is used.
  * @param target The anchor link target, or <code>null</code> or empty if no target is needed.
  * @param escapeHtml Set to <code>true</code> if the link caption should be HTML escaped. This
  *     value should be <code>true</code> in any case where the caption is not guaranteed to be
  *     free from potentially malicious HTML code.
  * @return An HTML anchor link that matches the given input parameters.
  * @throws DataAccessException Thrown if any error occurs while retrieving topic information.
  */
 public static String buildInternalLinkHtml(
     String context,
     String virtualWiki,
     WikiLink wikiLink,
     String text,
     String style,
     String target,
     boolean escapeHtml)
     throws DataAccessException {
   String url = LinkUtil.buildTopicUrl(context, virtualWiki, wikiLink);
   String topic = wikiLink.getDestination();
   if (StringUtils.isBlank(text)) {
     text = topic;
   }
   if (!StringUtils.isBlank(topic) && StringUtils.isBlank(style)) {
     if (!StringUtils.isEmpty(virtualWiki) && InterWikiHandler.isInterWiki(virtualWiki)) {
       style = "interwiki";
     } else if (!LinkUtil.isExistingArticle(virtualWiki, topic)) {
       style = "edit";
     }
   }
   if (!StringUtils.isBlank(style)) {
     style = " class=\"" + style + "\"";
   } else {
     style = "";
   }
   if (!StringUtils.isBlank(target)) {
     target = " target=\"" + target + "\"";
   } else {
     target = "";
   }
   if (StringUtils.isBlank(topic) && !StringUtils.isBlank(wikiLink.getSection())) {
     topic = wikiLink.getSection();
   }
   StringBuffer html = new StringBuffer();
   html.append("<a href=\"").append(url).append('\"').append(style);
   html.append(" title=\"")
       .append(StringEscapeUtils.escapeHtml(topic))
       .append('\"')
       .append(target)
       .append('>');
   if (escapeHtml) {
     html.append(StringEscapeUtils.escapeHtml(text));
   } else {
     html.append(text);
   }
   html.append("</a>");
   return html.toString();
 }
  /* goodB2G1() - use badsource and goodsink by changing second privateReturnsTrue() to privateReturnsFalse() */
  private void goodB2G1() throws Throwable {
    String data;
    if (privateReturnsTrue()) {
      /* get system property user.home */
      /* POTENTIAL FLAW: Read data from a system property */
      data = System.getProperty("user.home");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (privateReturnsFalse()) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      String xmlFile = null;
      if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        /* running on Windows */
        xmlFile = "\\src\\testcases\\CWE643_Xpath Injection\\CWE643_Xpath_Injection__Helper.xml";
      } else {
        /* running on non-Windows */
        xmlFile = "./src/testcases/CWE643_Xpath Injection/CWE643_Xpath_Injection__Helper.xml";
      }

      if (data != null) {
        /* assume username||password as source */
        String[] tokens = data.split("||");
        if (tokens.length < 2) {
          return;
        }
        /* FIX: validate input using StringEscapeUtils */
        String username = StringEscapeUtils.escapeXml(tokens[0]);
        String password = StringEscapeUtils.escapeXml(tokens[1]);
        /* build xpath */
        XPath xPath = XPathFactory.newInstance().newXPath();
        InputSource inputXml = new InputSource(xmlFile);
        String query =
            "//users/user[name/text()='"
                + username
                + "' and pass/text()='"
                + password
                + "']"
                + "/secret/text()";
        String secret = (String) xPath.evaluate(query, inputXml, XPathConstants.STRING);
      }
    }
  }