private String serializeStackTrace(ExceptionInfo exception) {
    StringBuffer text = new StringBuffer();

    if (exception.getStackTrace() != null
        && exception.getStackTrace().length > getMaxStackTraceLength()) {
      text.append("<s more=\"")
          .append(exception.getStackTrace().length - getMaxStackTraceLength())
          .append("\">");
    } else {
      text.append("<s>");
    }
    StackTraceElement[] stackTrace = exception.getStackTrace();
    if (stackTrace != null) {

      for (int i = 0; i < stackTrace.length && i < getMaxStackTraceLength(); i++) {
        text.append("<e ");
        text.append("c=\"")
            .append(StringEscapeUtils.escapeXml(stackTrace[i].getClassName()))
            .append("\" ");
        text.append("m=\"")
            .append(StringEscapeUtils.escapeXml(stackTrace[i].getMethodName()))
            .append("\" ");
        text.append("f=\"")
            .append(StringEscapeUtils.escapeXml(stackTrace[i].getFileName()))
            .append("\" ");
        text.append("l=\"").append(stackTrace[i].getLineNumber()).append("\" ");
        text.append("/>");
      }
    }
    text.append("</s>");
    return text.toString();
  }
Example #2
0
  public static void main(String args[]) {

    // handling xml special character & in Java String
    String xmlWithSpecial = "Java & HTML"; // xml String with & as special
    // characters
    System.out.println("Original unescaped XML String: " + xmlWithSpecial);
    System.out.println(
        "Escaped XML String in Java: " + StringEscapeUtils.escapeXml(xmlWithSpecial));

    // handling xml special character > in String on Java
    xmlWithSpecial = "Java > HTML"; // xml String with & as special
    // characters
    System.out.println("Original unescaped XML String: " + xmlWithSpecial);
    System.out.println("Escaped XML String : " + StringEscapeUtils.escapeXml(xmlWithSpecial));

    // handling xml and html special character < in String
    xmlWithSpecial = "Java < HTML"; // xml String with & as special
    // characters
    System.out.println("Original unescaped XML String: " + xmlWithSpecial);
    System.out.println("Escaped XML String: " + StringEscapeUtils.escapeXml(xmlWithSpecial));

    // handling html and xml special character " in Java
    xmlWithSpecial = "Java \" HTML"; // xml String with & as special
    // characters
    System.out.println("Original unescaped XML String: " + xmlWithSpecial);
    System.out.println("Escaped XML String: " + StringEscapeUtils.escapeXml(xmlWithSpecial));

    // handling xml special character ' in String from Java
    xmlWithSpecial = "Java ' HTML"; // xml String with & as special
    // characters
    System.out.println("Original unescaped XML String: " + xmlWithSpecial);
    System.out.println("Escaped XML String: " + StringEscapeUtils.escapeXml(xmlWithSpecial));
  }
Example #3
0
  public void delegateBooleanAssertion(
      final Type[] types, final int i2, final int i1, final boolean expected) {
    final Type type1 = types[i1];
    final Type type2 = types[i2];
    final boolean isAssignable = TypeUtils.isAssignable(type2, type1);

    if (expected) {
      Assert.assertTrue(
          "["
              + i1
              + ", "
              + i2
              + "]: From "
              + StringEscapeUtils.escapeHtml4(String.valueOf(type2))
              + " to "
              + StringEscapeUtils.escapeHtml4(String.valueOf(type1)),
          isAssignable);
    } else {
      Assert.assertFalse(
          "["
              + i1
              + ", "
              + i2
              + "]: From "
              + StringEscapeUtils.escapeHtml4(String.valueOf(type2))
              + " to "
              + StringEscapeUtils.escapeHtml4(String.valueOf(type1)),
          isAssignable);
    }
  }
  /**
   * @param request The request object providing information about the HTTP request
   * @param response The response object providing functionality for modifying the response
   * @return The content to be set in the response
   * @throws Exception implementation can choose to throw exception
   */
  public String handlePostNewPost(Request request, Response response) throws Exception {

    String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject"));
    String post = StringEscapeUtils.escapeHtml4(request.queryParams("body"));
    String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags"));

    String username = sessionDAO.findUserNameBySessionId(request.cookie("session"));

    if (username == null) {
      response.redirect("/login"); // only logged in users can post to blog
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    } else if (title.equals("") || post.equals("")) {
      SimpleHash root = new SimpleHash();

      // redisplay page with errors
      root.put("errors", "post must contain a title and blog entry.");
      root.put("subject", title);
      root.put("username", username);
      root.put("tags", tags);
      root.put("body", post);
      return templateEngine.render(new ModelAndView(root, "newpost_template.ftl"));
    } else {
      // extract tags
      List<String> tagsArray = extractTags(tags);

      // substitute some <p> for the paragraph breaks
      post = post.replaceAll("\\r?\\n", "<p>");

      String permalink = blogPostDAO.addPost(title, post, tagsArray, username);

      // now redirect to the blog permalink
      response.redirect("/post/" + permalink);
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    }
  }
Example #5
0
    private void writeLogs(final cgCache cache) throws IOException {
      final List<LogEntry> logs = cache.getLogs();
      if (logs.size() <= 0) {
        return;
      }
      gpx.write("<groundspeak:logs>");

      for (LogEntry log : logs) {
        gpx.write("<groundspeak:log id=\"");
        gpx.write(Integer.toString(log.id));
        gpx.write("\">");

        gpx.write("<groundspeak:date>");
        gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(new Date(log.date))));
        gpx.write("</groundspeak:date>");

        gpx.write("<groundspeak:type>");
        gpx.write(StringEscapeUtils.escapeXml(log.type.type));
        gpx.write("</groundspeak:type>");

        gpx.write("<groundspeak:finder id=\"\">");
        gpx.write(StringEscapeUtils.escapeXml(log.author));
        gpx.write("</groundspeak:finder>");

        gpx.write("<groundspeak:text encoded=\"False\">");
        gpx.write(StringEscapeUtils.escapeXml(log.log));
        gpx.write("</groundspeak:text>");

        gpx.write("</groundspeak:log>");
      }

      gpx.write("</groundspeak:logs>");
    }
  /**
   * @param request The request object providing information about the HTTP request
   * @param response The response object providing functionality for modifying the response
   * @return The content to be set in the response
   * @throws Exception implementation can choose to throw exception
   */
  public String handlePostNewComment(Request request, Response response) throws Exception {

    String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName"));
    String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail"));
    String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody"));
    String permalink = request.queryParams("permalink");

    Document post = blogPostDAO.findByPermalink(permalink);
    if (post == null) {
      response.redirect("/post_not_found");
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    }

    // check that comment is good
    else if (name.equals("") || body.equals("")) {
      // bounce this back to the user for correction
      SimpleHash comment = new SimpleHash();
      comment.put("name", name);
      comment.put("email", email);
      comment.put("body", body);

      SimpleHash root = new SimpleHash();
      root.put("comment", comment);
      root.put("post", post);
      root.put("errors", "Post must contain your name and an actual comment");
      return templateEngine.render(new ModelAndView(root, "entry_template.ftl"));

    } else {
      blogPostDAO.addPostComment(name, email, body, permalink);
      response.redirect("/post/" + permalink);
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    }
  }
Example #7
0
  private String postCoupon(HttpServletRequest request) {
    if (request.getMethod().equals("GET")) return "postCoupon";
    String bizName = request.getParameter("bizName");
    String bogoDesc = request.getParameter("bogoDesc");
    String bizLoc = request.getParameter("bizLoc");
    String couponValue = request.getParameter("couponValue");
    //        Date couponDate = request.getParameter("couponDate");
    String zip1 = request.getParameter("zip1");
    String zip2 = request.getParameter("zip2");
    String zip3 = request.getParameter("zip3");

    if (bizName == null || bizName.length() < 1 || bizName.length() > 40) {
      request.setAttribute("flash", "Content must be between 1-40 characters.");
      request.setAttribute("bizName", bizName);
      return "postCoupon";
    }
    if (bogoDesc == null || bogoDesc.length() < 1 || bogoDesc.length() > 40) {
      request.setAttribute("flash", "Content must be between 1-40 characters.");
      request.setAttribute("bogoDesc", bogoDesc);
      return "postCoupon";
    }
    if (bizLoc == null || bizLoc.length() < 1 || bizLoc.length() > 60) {
      request.setAttribute("flash", "Content must be between 1-60 characters.");
      request.setAttribute("bizLoc", bizLoc);
      return "postCoupon";
    }
    if (!zip1.matches("^\\d{5}?$")) {
      request.setAttribute("flash", "Zipcode must be XXXXX or XXXXX-XXXX format");
      request.setAttribute("zip1", zip1);
      return "postCoupon";
    }
    if (!zip2.matches("^\\d{5}?$") || !zip3.matches("^\\d{5}?$")) {
      if (zip2.length() == 0 && zip3.length() == 0) return "postCoupon";
      else
        request.setAttribute(
            "flash", "Zipcode must be XXXXX or " + "XXXXX-XXXX format " + "or can be left blank");
      request.setAttribute("zip2", zip2);
      request.setAttribute("zip3", zip3);
      return "postCoupon";
    }
    if (couponValue == null || couponValue.length() < 1 || couponValue.length() > 10) {
      request.setAttribute("flash", "Value must be between 1-10 characters.");
      request.setAttribute("couponValue", couponValue);
      return "postCoupon";
    }
    bizName = StringEscapeUtils.escapeHtml4(bizName);
    bizName = bizName.replace("'", "&#39;");
    bogoDesc = StringEscapeUtils.escapeHtml4(bogoDesc);
    bogoDesc = bogoDesc.replace("'", "&#39;");
    bizLoc = StringEscapeUtils.escapeHtml4(bizLoc);
    bizLoc = bizLoc.replace("'", "&#39;");
    BogoDAO db = (BogoDAO) this.getServletContext().getAttribute("db");
    db.addCoupon(bizName, bogoDesc, bizLoc, couponValue, zip1, zip2, zip3);
    if (db.getLastError() != null) {
      request.setAttribute("flash", db.getLastError());
      return "postCoupon";
    }
    return "tyForPosting";
  }
Example #8
0
 static ECMAEscapedSavedQuery getFor(SavedQuery savedQuery) throws LensException {
   return new ECMAEscapedSavedQuery(
       savedQuery.getId(),
       StringEscapeUtils.escapeEcmaScript(savedQuery.getName()),
       StringEscapeUtils.escapeEcmaScript(savedQuery.getDescription()),
       StringEscapeUtils.escapeEcmaScript(savedQuery.getQuery()),
       StringEscapeUtils.escapeEcmaScript(serializeParameters(savedQuery)));
 }
  @Override
  protected void prepare(Activity context, LinearLayout items) {

    final RedditPost post = getArguments().getParcelable("post");

    items.addView(
        propView(
            context,
            R.string.props_title,
            StringEscapeUtils.unescapeHtml4(post.title.trim()),
            true));
    items.addView(propView(context, R.string.props_author, post.author, false));
    items.addView(
        propView(context, R.string.props_url, StringEscapeUtils.unescapeHtml4(post.url), false));
    items.addView(
        propView(
            context,
            R.string.props_created,
            RRTime.formatDateTime(post.created_utc * 1000, context),
            false));

    if (post.edited instanceof Long) {
      items.addView(
          propView(
              context,
              R.string.props_edited,
              RRTime.formatDateTime((Long) post.edited * 1000, context),
              false));
    } else {
      items.addView(propView(context, R.string.props_edited, R.string.props_never, false));
    }

    items.addView(propView(context, R.string.props_subreddit, post.subreddit, false));
    items.addView(
        propView(
            context,
            R.string.props_score,
            String.format(
                "%d (%d %s, %d %s)",
                post.score,
                post.ups,
                context.getString(R.string.props_up),
                post.downs,
                context.getString(R.string.props_down)),
            false));
    items.addView(
        propView(context, R.string.props_num_comments, String.valueOf(post.num_comments), false));

    if (post.selftext != null && post.selftext.length() > 0) {
      items.addView(
          propView(
              context,
              R.string.props_self_markdown,
              StringEscapeUtils.unescapeHtml4(post.selftext),
              false));
    }
  }
Example #10
0
 /**
  * Cuts off long queries. Actually they are restricted to 50 characters. The full query is
  * available with descriptions (tooltip in gui)
  *
  * @param text the query to display in the result view panel
  */
 public void setInfo(String text) {
   if (text != null && text.length() > 0) {
     String prefix = "Result for: <span class=\"" + Helper.CORPUS_FONT_FORCE + "\">";
     lblInfo.setDescription(prefix + text.replaceAll("\n", " ") + "</span>");
     lblInfo.setValue(
         text.length() < 50
             ? prefix + StringEscapeUtils.escapeHtml4(text.substring(0, text.length()))
             : prefix + StringEscapeUtils.escapeHtml4(text.substring(0, 50)) + " ... </span>");
   }
 }
  public String escapeHtml(String text) {

    String value = text;
    if (text == null) {
      return text;
    } else {
      value = StringEscapeUtils.escapeHtml3(value);
      value = StringEscapeUtils.escapeHtml4(value);
    }
    return value;
  }
  @Override
  public void endElement(String uri, String localName, String qName) {
    if (localName.equalsIgnoreCase("image")) {
      if (!isItem) {
        isImage = false;
      }
    } else if (localName.equalsIgnoreCase("url")) {
      if (isImage) {
        feed.setLogo(StringEscapeUtils.unescapeXml(chars.toString()));
      }
    } else if (localName.equalsIgnoreCase("ttl")) {
      if (!isItem) {
        feed.setTtl(Integer.parseInt(StringEscapeUtils.unescapeXml(chars.toString())));
      }
    } else if (localName.equalsIgnoreCase("title")) {
      if (!isImage) {
        if (isItem) {
          item.setTitle(StringEscapeUtils.unescapeXml(chars.toString()));
        } else {
          feed.setTitle(StringEscapeUtils.unescapeXml(chars.toString()));
        }
      }
    } else if (localName.equalsIgnoreCase("description")) {
      if (isItem) {
        item.setDescription(StringEscapeUtils.unescapeXml(chars.toString()));
      } else {
        feed.setDescription(StringEscapeUtils.unescapeXml(chars.toString()));
      }
    } else if (localName.equalsIgnoreCase("pubDate")) {
      if (isItem) {
        try {
          item.setDate(dateFormat.parse(StringEscapeUtils.unescapeXml(chars.toString())));
        } catch (Exception e) {
          Log.e(LOG_CAT, "pubDate", e);
        }
      } else {
        try {
          feed.setDate(dateFormat.parse(StringEscapeUtils.unescapeXml(chars.toString())));
        } catch (Exception e) {
          Log.e(LOG_CAT, "pubDate", e);
        }
      }
    } else if (localName.equalsIgnoreCase("item")) {
      isItem = false;
    } else if (localName.equalsIgnoreCase("link")) {
      if (isItem) {
        item.setLink(StringEscapeUtils.unescapeXml(chars.toString()));
      } else {
        feed.setLink(StringEscapeUtils.unescapeXml(chars.toString()));
      }
    }

    if (localName.equalsIgnoreCase("item")) {}
  }
  /**
   * Gets the map to represent a single milestone.
   *
   * @param m the milestone
   * @param projects the projects cache
   * @return the map representing a single milestone.
   */
  private static Map<String, String> getMilestoneJsonData(Milestone m, Map<Long, String> projects) {
    Map<String, String> item = new HashMap<String, String>();
    item.put("title", StringEscapeUtils.escapeHtml4(m.getName()));
    item.put("projectId", String.valueOf(m.getProjectId()));
    item.put("projectName", StringEscapeUtils.escapeHtml4(projects.get(m.getProjectId())));
    item.put("description", StringEscapeUtils.escapeHtml4(m.getDescription()));
    item.put(
        "date",
        MILESTONE_DATE_FORMAT.format(m.isCompleted() ? m.getCompletionDate() : m.getDueDate()));

    return item;
  }
  @FilterWith({XSRFFilter.class, AdminFilter.class})
  public Result exportSearches(Context context, @Params("id[]") String[] ids) {
    FlashScope flash = context.getFlashScope();
    Group group = context.getAttribute("group", Group.class);

    if (ids == null || ids.length == 0) {
      flash.error("error.noSearchSelected");
      return Results.redirect(
          router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }

    List<GoogleSearch> searches = new ArrayList<>();
    for (String id : ids) {
      GoogleSearch search = null;
      try {
        search = getSearch(context, Integer.parseInt(id));
      } catch (Exception ex) {
        search = null;
      }

      if (search == null) {
        flash.error("error.invalidSearch");
        return Results.redirect(
            router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
      }

      searches.add(search);
    }

    StringBuilder builder = new StringBuilder();
    for (GoogleSearch search : searches) {
      builder.append(StringEscapeUtils.escapeCsv(search.getKeyword())).append(",");
      builder.append(search.getTld() != null ? search.getTld() : "com").append(",");
      builder.append(search.getDatacenter() != null ? search.getDatacenter() : "").append(",");
      builder
          .append(
              search.getDevice() != null
                  ? (search.getDevice() == GoogleDevice.DESKTOP ? "desktop" : "mobile")
                  : "")
          .append(",");
      builder
          .append(StringEscapeUtils.escapeCsv(search.getLocal() != null ? search.getLocal() : ""))
          .append(",");
      builder
          .append(
              StringEscapeUtils.escapeCsv(
                  search.getCustomParameters() != null ? search.getCustomParameters() : ""))
          .append("\n");
    }

    return Results.ok().text().render(builder.toString());
  }
 @Override
 public String renderReasons(List<ReportReason> reasons) {
   StringBuffer text = new StringBuffer();
   text.append("<reasons>");
   for (ReportReason reason : reasons) {
     text.append("<reason level=\"")
         .append(StringEscapeUtils.escapeXml(reason.getLevel()))
         .append("\">")
         .append(StringEscapeUtils.escapeXml(reason.getReason()))
         .append("</reason>");
   }
   text.append("</reasons>");
   return text.toString();
 }
 @Override
 public void write(OsmRelation relation) {
   out.print("  <relation id=\"" + relation.getId() + "\"");
   if (printMetadata) {
     OsmMetadata metadata = relation.getMetadata();
     printMetadata(metadata);
   }
   if (relation.getNumberOfTags() == 0 && relation.getNumberOfMembers() == 0) {
     out.println("/>");
   } else {
     out.println(">");
     for (int i = 0; i < relation.getNumberOfMembers(); i++) {
       OsmRelationMember member = relation.getMember(i);
       EntityType type = member.getType();
       String t = type == EntityType.Node ? "node" : type == EntityType.Way ? "way" : "relation";
       String role = member.getRole();
       role = StringEscapeUtils.escapeXml(role);
       out.println(
           "    <member type=\""
               + t
               + "\" ref=\""
               + member.getId()
               + "\" role=\""
               + role
               + "\"/>");
     }
     printTags(relation);
     out.println("  </relation>");
   }
 }
Example #17
0
  /**
   * Create a CharacteristicBean.
   *
   * @param conn A connection to the database.
   * @param num_samples The number of samples in the database.
   * @param value The value of this sample.
   * @return
   * @throws SQLException
   */
  private static CharacteristicBean getCharacteristicBean(
      Connection conn, int num_samples, String dbname, String value) throws SQLException {
    CharacteristicBean chrbean = new CharacteristicBean();

    PreparedStatement getCount;
    String querystr = "SELECT COUNT(*) FROM `Samples` WHERE `" + dbname + "`";
    if (value != null) {
      chrbean.setValue(StringEscapeUtils.escapeHtml4(value));
      querystr += " = ?;";

      getCount = conn.prepareStatement(querystr);
      getCount.setString(1, value);
    } else {
      chrbean.setValue(NO_JAVASCRIPT);

      querystr += " IS NULL;";
      getCount = conn.prepareStatement(querystr);
    }

    ResultSet rs = getCount.executeQuery();
    rs.next();
    int count = rs.getInt(1);
    rs.close();
    chrbean.setInX(((double) num_samples) / ((double) count));
    chrbean.setBits(Math.abs(Math.log(chrbean.getInX()) / Math.log(2)));

    return chrbean;
  }
Example #18
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;

    if (convertView == null) v = inflater.inflate(R.layout.sem_details_listrow, null);

    semSubName = (TextView) v.findViewById(R.id.semSubName);
    semSubName.setSelected(true);
    semCCode = (TextView) v.findViewById(R.id.semCCode);
    semSubCredits = (TextView) v.findViewById(R.id.semSubCredits);
    semSubGrade = (TextView) v.findViewById(R.id.semSubGrade);

    HashMap<String, String> row = new HashMap<String, String>();

    row = adapterkeylist.get(position);

    temp = row.get("sub");
    temp = StringEscapeUtils.unescapeHtml4(temp);

    semSubName.setText(temp);
    semCCode.setText("Subject Code: " + row.get("subcode"));
    semSubCredits.setText("Subject Credits: " + row.get("credits"));
    semSubGrade.setText("Subject Grade: " + row.get("grade"));

    return v;
  }
  @Test
  public void testClensing() {
    String pageTitle =
        StringEscapeUtils.unescapeHtml4(Jsoup.clean("Jeppist&auml; jee", Whitelist.simpleText()));

    assertTrue("Jeppistä jee".equals(pageTitle));
  }
Example #20
0
    private void writeAttributes(final cgCache cache) throws IOException {
      if (!cache.hasAttributes()) {
        return;
      }
      // TODO: Attribute conversion required: English verbose name, gpx-id
      gpx.write("<groundspeak:attributes>");

      for (String attribute : cache.getAttributes()) {
        final CacheAttribute attr =
            CacheAttribute.getByGcRawName(CacheAttribute.trimAttributeName(attribute));
        final boolean enabled = CacheAttribute.isEnabled(attribute);

        gpx.write("<groundspeak:attribute id=\"");
        gpx.write(Integer.toString(attr.id));
        gpx.write("\" inc=\"");
        if (enabled) {
          gpx.write('1');
        } else {
          gpx.write('0');
        }
        gpx.write("\">");
        gpx.write(StringEscapeUtils.escapeXml(attr.getL10n(enabled)));
        gpx.write("</groundspeak:attribute>");
      }

      gpx.write("</groundspeak:attributes>");
    }
  public Result jsonSearchSuggest(Context context, @Param("query") String query) {

    StringBuilder builder = new StringBuilder("[");
    getSearches(context)
        .stream()
        .filter((g) -> query == null ? true : g.getKeyword().contains(query))
        .sorted((o1, o2) -> o1.getId() - o2.getId())
        .limit(10)
        .forEach(
            (g) -> {
              builder
                  .append("{")
                  .append("\"id\":")
                  .append(g.getId())
                  .append(",")
                  .append("\"name\":\"")
                  .append(StringEscapeUtils.escapeJson(g.getKeyword()))
                  .append("\"")
                  .append("},");
            });
    if (builder.length() > 1) {
      builder.deleteCharAt(builder.length() - 1);
    }
    builder.append("]");

    return Results.json().renderRaw(builder.toString());
  }
Example #22
0
 /** Parse a Mediawiki heading of the form "==heading==" and return the resulting HTML output. */
 public String parse(JFlexLexer lexer, String raw, Object... args) throws ParserException {
   if (logger.isTraceEnabled()) {
     logger.trace("heading: " + raw + " (" + lexer.yystate() + ")");
   }
   // the wikiheading tag may match a preceding newline, so strip it
   raw = raw.trim();
   int level = this.generateTagLevel(raw, args);
   String tagText = this.generateTagText(raw, args);
   String tocText = this.buildTocText(lexer, tagText);
   String tagName = this.buildTagName(lexer, tocText);
   if (lexer.getMode() <= JFlexParser.MODE_SLICE) {
     String sectionName = StringEscapeUtils.unescapeHtml4(tocText);
     lexer.getParserOutput().setSectionName(sectionName);
     return raw;
   }
   if (!(lexer instanceof JAMWikiLexer)) {
     throw new IllegalStateException(
         "Cannot parse heading tags except with instances of JAMWikiLexer or in slice/splice mode");
   }
   JAMWikiLexer jamwikiLexer = (JAMWikiLexer) lexer;
   if (jamwikiLexer.paragraphIsOpen()) {
     // close any open paragraph
     jamwikiLexer.popTag("p");
   }
   return this.generateOutput(jamwikiLexer, tagName, tocText, tagText, level, raw, args);
 }
 private void update()
     throws ControllerException, AuthorityException, ServiceException, Exception {
   this.checkFields();
   SysTwitterVO oldSysTwitter = new SysTwitterVO();
   oldSysTwitter.setOid(this.getFields().get("oid"));
   DefaultResult<SysTwitterVO> oldResult = this.sysTwitterService.findObjectByOid(oldSysTwitter);
   if (oldResult.getValue() == null) {
     throw new ServiceException(oldResult.getSystemMessage().getValue());
   }
   oldSysTwitter = oldResult.getValue();
   SysTwitterVO sysTwitter = new SysTwitterVO();
   sysTwitter.setOid(oldSysTwitter.getOid());
   sysTwitter.setSystem(oldSysTwitter.getSystem());
   sysTwitter.setTitle(this.getFields().get("title"));
   sysTwitter.setEnableFlag(
       ("true".equals(this.getFields().get("enableFlag")) ? YesNo.YES : YesNo.NO));
   sysTwitter.setContent(null); // 先清除之前的blob資料
   this.sysTwitterService.updateObject(sysTwitter); // 先清除之前的blob資料	
   String content = StringEscapeUtils.unescapeEcmaScript(this.getFields().get("content"));
   sysTwitter.setContent(content.getBytes());
   DefaultResult<SysTwitterVO> result = this.sysTwitterService.updateObject(sysTwitter);
   this.message = result.getSystemMessage().getValue();
   if (result.getValue() != null) {
     this.success = IS_YES;
   }
 }
  protected String printLdcInsnNode(LdcInsnNode ldc, ListIterator<?> it) {
    if (ldc.cst instanceof String)
      return nameOpcode(ldc.opcode())
          + " \""
          + StringEscapeUtils.escapeJava(ldc.cst.toString())
          + "\" ("
          + ldc.cst.getClass().getCanonicalName()
          + ")";

    return nameOpcode(ldc.opcode())
        + " "
        + StringEscapeUtils.escapeJava(ldc.cst.toString())
        + " ("
        + ldc.cst.getClass().getCanonicalName()
        + ")";
  }
Example #25
0
  void storeXml(ParseIndexContext ctx, Path xml) throws IOException {
    Files.createFile(xml);
    PrintWriter p = new PrintWriter(Files.newBufferedWriter(xml, utf8));
    p.print("<?xml version='1.1' encoding='" + NotesRetriever.utf8.name() + "'?><snotes>");

    ctx.list.sort(Comparator.comparing(o1 -> o1.number));
    for (NoteListItem i : ctx.list) {
      p.print("\n<n");
      p.print(" n='" + i.number + "'");
      if (i.mark != null) p.print(" m='" + i.mark + "'");
      p.print(" a='" + i.apparea + "'");
      p.print(" l='" + i.asklangu + "'");
      p.print(" d='" + DateTimeFormatter.ISO_LOCAL_DATE.format(i.date) + "'");
      p.print(" c='" + i.category + "'");
      p.print(" p='" + i.priority + "'");
      if (i.objid != null) p.print(" o='" + i.objid + "'");
      p.print(">" + StringEscapeUtils.escapeXml11(i.title) + "</n>");
    }
    p.flush();
    for (Pair<String, String> a : ctx.lareas) {
      p.print("\n<area rcode='" + a.getKey() + "' value='" + a.getValue() + "'/>");
    }
    p.flush();
    //		p.print("\n<!-- [Statistics]");
    //		if (dsd==0 && dod==0) {
    //			p.print("\tNotes collected: " + q + ", no duplicates found");
    //		} else {
    //			p.print("\nUnique notes collected: " + q);
    //			p.print("\nDuplicate notes with the same date: " + dsd);
    //			p.print("\nDuplocate notes with the other date: " + dod);
    //		}
    //		p.println("\t-->");
    p.print("\n</snotes>");
    p.close();
  }
Example #26
0
 private void makeDigest(KCPosting posting) {
   if (null == posting) {
     return;
   }
   digest = posting.content;
   int len = digest.length();
   if (len > 250) len = 250;
   digest = digest.substring(0, len);
   digest = digest.replaceAll("[\n\r\u0085\u2028\u2029]", " ").replaceAll(" +", " ").trim();
   digest = StringEscapeUtils.unescapeHtml4(digest);
   digest = digest.replaceAll("<span class=\"spoiler\">.+?</span>", "");
   digest = digest.replaceAll("\\<.*?\\>", " ");
   digest = digest.replaceAll("https?://.+? ", " ");
   digest = digest.replaceAll(" +", " ");
   len = digest.length();
   if (len > 200) len = 200;
   digest = digest.substring(0, len);
   digest = digest.replaceAll("\\<.*", "");
   int pos = digest.length() - 1;
   char c = digest.charAt(pos);
   while ((c != ' ') && (pos > 150)) {
     pos--;
     c = digest.charAt(pos);
   }
   digest = digest.trim();
   for (String img : posting.thumbs) {
     if ((img != null) && (img.length() > 0)) {
       digest += "\n   " + img;
     }
   }
 }
  @RequestMapping(value = "/profileedit", method = RequestMethod.POST)
  public View profileEditPost(
      @ModelAttribute("profile") ProfileVO profileVO, HttpSession httpSession, Model model) {
    String error = "";
    User user = userDAO.findByUserId(profileVO.getUserId());
    String email = profileVO.getEmail();
    if (ValidatorUtil.isValidEmail(email)) {
      if (userDAO.findByEmail(email) == null) {
        user.setEmail(email);
      } else {
        error +=
            "Email address "
                + StringEscapeUtils.escapeHtml4(email)
                + " is taken or unavailable<br/>";
      }
    } else {
      error += "Email address " + StringEscapeUtils.escapeHtml4(email) + " is invalid<br/>";
    }

    String newPassword = profileVO.getPassword();
    String newPasswordConfirm = profileVO.getConfirmPassword();
    if (ValidatorUtil.isNotNull(newPassword)) {
      if (newPassword.equals(newPasswordConfirm)) {
        try {
          user.setPassword(PasswordHash.createHash(newPassword));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
          _log.error(e);
        }
      } else {
        error += "Password Mismatch<br/>";
      }
    }
    user.setMovieView(profileVO.isMovieView() ? 1 : 0);
    user.setMusicView(profileVO.isMusicView() ? 1 : 0);
    user.setConsoleView(profileVO.isConsoleView() ? 1 : 0);
    List<Integer> exCatIds = profileVO.getExCatIds();
    // TODO update excats

    if (ValidatorUtil.isNull(error)) {
      userDAO.update(user);
    }
    httpSession.setAttribute("errors", error);

    return safeRedirect("/profileedit");
  }
 private String getPointsMsg(SubmissionResult result) {
   if (!result.getPoints().isEmpty()) {
     String msg =
         "Points permanently awarded: " + StringUtils.join(result.getPoints(), ", ") + ".";
     return "<html>" + StringEscapeUtils.escapeHtml4(msg).replace("\n", "<br />\n") + "</html>";
   } else {
     return "";
   }
 }
Example #29
0
  /**
   * Recursively write the XML data for the node tree starting at <code>node</code>.
   *
   * @param indent white space to indent child nodes
   * @param printWriter writer where child nodes are written
   */
  @Override
  protected void printXml(final String indent, final PrintWriter printWriter) {
    printWriter.print(indent + "<");
    printOpeningTagContentAsXml(printWriter);

    printWriter.print(">");
    printWriter.print(StringEscapeUtils.escapeXml(getText()));
    printWriter.print("</textarea>");
  }
 /**
  * Setting an ID lets the browser keep track of the last event fired so that if, the connection to
  * the server is dropped, a special HTTP header (Last-Event-ID) is set with the new request. This
  * lets the browser determine which event is appropriate to fire.
  *
  * @param eventId Unique event id.
  * @param data data associated with event
  */
 public void sendDataById(String eventId, String data) {
   out.write(
       "id: "
           + eventId
           + "\r\n"
           + "data: "
           + StringEscapeUtils.escapeEcmaScript(data)
           + "\r\n\r\n");
 }