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;
 }
예제 #2
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;
  }
예제 #3
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;
  }
  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;
  }
 private static ColumnMappingVO init(EAAttributeVO ea, ColumnMappingVO v) {
   EAAttributteDecorator.init(ea, v);
   v.columnName = ea.name;
   // Unescape HTML entities used by EA
   v.expression = StringEscapeUtils.unescapeHtml(ea.notes);
   return v;
 }
예제 #6
0
 public NutMap _topic(Topic topic, Map<Integer, UserProfile> authors, String mdrender) {
   yvrService.fillTopic(topic, authors);
   NutMap tp = new NutMap();
   tp.put("id", topic.getId());
   tp.put("author_id", "" + topic.getAuthor().getUserId());
   tp.put("tab", topic.getType().toString());
   tp.put(
       "content",
       "false".equals(mdrender)
           ? topic.getContent()
           : Markdowns.toHtml(topic.getContent(), urlbase));
   tp.put("title", StringEscapeUtils.unescapeHtml(topic.getTitle()));
   if (topic.getLastComment() != null)
     tp.put("last_reply_at", _time(topic.getLastComment().getCreateTime()));
   tp.put("good", topic.isGood());
   tp.put("top", topic.isTop());
   tp.put("reply_count", topic.getReplyCount());
   tp.put("visit_count", topic.getVisitCount());
   tp.put("create_at", _time(topic.getCreateTime()));
   UserProfile profile = topic.getAuthor();
   if (profile != null) {
     profile.setScore(yvrService.getUserScore(topic.getUserId()));
   }
   tp.put("author", _author(profile));
   return tp;
 }
예제 #7
0
 private static String[] parseLetv(String url) {
   String[] result = new String[2];
   String id = "";
   String html = getUrlContent(url);
   Pattern pId = Pattern.compile("(?<=vplay/)([0-9]*)");
   Matcher mId = pId.matcher(url);
   if (mId.find()) {
     id = mId.group();
     Pattern pVideo = Pattern.compile("(?<=value=\")([^\"]*swf\\?id=" + id + "&amp[^\"]*)(?=\")");
     Matcher mVideo = pVideo.matcher(html);
     if (mVideo.find()) {
       result[0] = StringEscapeUtils.unescapeHtml(mVideo.group());
     } else {
       return null;
     }
   } else {
     return null;
   }
   Pattern pImage = Pattern.compile("(?<=pic:\")([^\"]*)(?=\")");
   Matcher mImage = pImage.matcher(html);
   if (mImage.find()) {
     result[1] = mImage.group();
   } else {
     return null;
   }
   return result;
 }
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView show(
      @ModelAttribute("form") EditRegisterRequest form,
      @PathVariable String nick,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    Template tmpl = Template.getTemplate(request);
    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not authorized");
    }
    if (!tmpl.getNick().equals(nick)) {
      throw new AccessViolationException("Not authorized");
    }
    User user = tmpl.getCurrentUser();
    UserInfo userInfo = userDao.getUserInfoClass(user);

    ModelAndView mv = new ModelAndView("edit-reg");

    form.setEmail(user.getEmail());
    form.setUrl(userInfo.getUrl());
    form.setTown(userInfo.getTown());
    form.setName(user.getName());
    form.setInfo(StringEscapeUtils.unescapeHtml(userDao.getUserInfo(user)));

    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

    return mv;
  }
예제 #9
0
 private void compareDecodes(String orig) {
   String htmlparserDecoded = Translate.decode(orig);
   String apacheDecoded = StringEscapeUtils.unescapeHtml(orig);
   System.out.format("ORIGINAL:(%s)\n", orig);
   System.out.format("htmlparser:(%s)\n", htmlparserDecoded);
   System.out.format("apache:(%s)\n", apacheDecoded);
 }
예제 #10
0
 /**
  * Sets space for this ui component to work with.
  *
  * @param space
  * @throws Exception
  */
 public void setValue(Space space) throws Exception {
   invokeGetBindingBean(space);
   UIFormTextAreaInput description = getUIFormTextAreaInput(SPACE_DESCRIPTION);
   description.setValue(StringEscapeUtils.unescapeHtml(description.getValue()));
   // TODO: have to find the way to don't need the line code below.
   getUIStringInput(SPACE_TAG).setValue(space.getTag());
 }
  @Override
  public List<String> extractValueFromNode(Object node, String expression) {
    Jerry doc = Jerry.jerry(node.toString());
    List<String> list = new ArrayList();
    String replacement = null;

    if (expression.equals("*")) {
      list.add(node.toString());
      return list;
    }

    /*if (expression.equals("#")) {
        list.add(Integer.toString(enumerator++));
        return list;
    }*/

    Node doc2 = doc.get(0);
    NodeSelector nodeSelector = new NodeSelector(doc2);
    List<Node> selectedNodes; // = nodeSelector.select(expression);
    if (expression.contains("href")) selectedNodes = nodeSelector.select("a");
    else selectedNodes = nodeSelector.select(expression);

    for (Node snode : selectedNodes) {
      if (expression.contains("href")) {
        list.add(
            StringEscapeUtils.unescapeHtml(
                snode
                    .getAttribute("href")
                    .toString()
                    .replaceAll(expression, replacement)
                    .trim()
                    .replaceAll("[\\t\\n\\r\\s]{2,}", " ")));
      } else {
        String value =
            StringEscapeUtils.unescapeHtml(
                snode.getTextContent().replaceAll("[\\t\\n\\r\\s]{2,}", " ").trim());
        if (value != null & !value.equals("")) list.add(StringEscapeUtils.unescapeHtml(value));
      }
    }
    /*for (Node snode : selectedNodes) {
        if (snode.getInnerHtml().toString() != null && !snode.getInnerHtml().toString().trim().replaceAll("[\\t\\n\\r\\s]{2,}", " ").equals("")) {
            list.add(snode.getInnerHtml().toString().trim().replaceAll("[\\t\\n\\r\\s]{2,}", " "));
        }
    }*/
    return list;
  }
예제 #12
0
 private long doExecuteSparql(VitroRequest vreq) {
   OntModel jenaOntModel = ModelAccess.on(getServletContext()).getOntModel();
   OntModel source = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
   String[] sourceModel = vreq.getParameterValues("sourceModelName");
   for (int i = 0; i < sourceModel.length; i++) {
     Model m = getModel(sourceModel[i], vreq);
     source.addSubModel(m);
   }
   Model destination = getModel(vreq.getParameter("destinationModelName"), vreq);
   String sparqlQueryStr = vreq.getParameter("sparqlQueryStr");
   String savedQueryURIStr = vreq.getParameter("savedQuery");
   String queryStr;
   if (savedQueryURIStr.length() == 0) {
     log.debug("Using entered query");
     queryStr = sparqlQueryStr;
   } else {
     Property queryStrProp = ResourceFactory.createProperty(SPARQL_QUERYSTR_PROP);
     jenaOntModel.enterCriticalSection(Lock.READ);
     try {
       Individual ind = jenaOntModel.getIndividual(savedQueryURIStr);
       log.debug("Using query " + savedQueryURIStr);
       queryStr = ((Literal) ind.getPropertyValue(queryStrProp)).getLexicalForm();
       queryStr =
           StringEscapeUtils.unescapeHtml(
               queryStr); // !!! We need to turn off automatic HTML-escaping for data property
                          // editing.
     } finally {
       jenaOntModel.leaveCriticalSection();
     }
   }
   Model tempModel = ModelFactory.createDefaultModel();
   Query query = SparqlQueryUtils.create(queryStr);
   QueryExecution qexec = QueryExecutionFactory.create(query, source);
   try {
     qexec.execConstruct(tempModel);
   } catch (QueryExecException qee) {
     qexec.execDescribe(tempModel);
   }
   destination.enterCriticalSection(Lock.WRITE);
   try {
     if (destination instanceof OntModel) {
       ((OntModel) destination).getBaseModel().notifyEvent(new EditEvent(null, true));
     } else {
       destination.notifyEvent(new EditEvent(null, true));
     }
     destination.add(tempModel);
   } finally {
     if (destination instanceof OntModel) {
       ((OntModel) destination).getBaseModel().notifyEvent(new EditEvent(null, false));
     } else {
       destination.notifyEvent(new EditEvent(null, false));
     }
     destination.leaveCriticalSection();
   }
   return tempModel.size();
 }
예제 #13
0
  public void setValue(String value) {
    this.value = value;
    if (unHtmlEncodedValue == null && value != null) {
      setUnHtmlEncodedValue(StringEscapeUtils.unescapeHtml(value));
    }

    if (rawValue == null && value != null) {
      setRawValue(value);
    }
  }
예제 #14
0
  @SuppressWarnings("unchecked")
  public void test() throws Exception {
    final SyndFeedInput input = new SyndFeedInput(true);
    final SyndFeed feed = input.build(new File("c:\\temp\\google.xml"));

    logger.debug("Successfully parsed the RSS feed");
    logger.debug("Author      = " + feed.getAuthors());
    logger.debug("Categories  = " + feed.getCategories());
    final List<SyndEntry> entries = feed.getEntries();
    for (final SyndEntry entry : entries) {
      logger.debug("Title = " + StringEscapeUtils.unescapeHtml(entry.getTitle()));
      logger.debug(
          "Description = " + StringEscapeUtils.unescapeHtml(entry.getDescription().getValue()));
      logger.debug(entry.getUri());
      logger.debug("Updated date = " + entry.getUpdatedDate());
      logger.debug("Published date = " + entry.getPublishedDate());
      logger.debug("====================================================");
    }
  }
  @Override
  public PostData getPostData() {

    PostData formData =
        new PostData() {

          @Override
          public void setCredentials(String username, String password) {
            add("IDToken1", username);
            add("IDToken2", password);
          }
        };
    formData.add("IDButton");
    formData.add("goto", StringEscapeUtils.unescapeHtml(getSamlResponse()));
    formData.add("SunQueryParamsString", StringEscapeUtils.unescapeHtml(getRelayState()));
    formData.add("encoded", "true");
    formData.add("gx_charset", "UTF-8");
    formData.add("gx_charset", "UTF-8");
    return formData;
  }
 private String prepareMailBodyContentPart(Content content, String defaultLang, boolean isHtml) {
   NewsletterContentType contentType =
       this.getConfig().getContentTypes().get(content.getTypeCode());
   int modelId = isHtml ? contentType.getHtmlModel() : contentType.getSimpleTextModel();
   String mailContentBody = this.getContentRenderer().render(content, modelId, defaultLang, null);
   mailContentBody = this.getLinkResolver().resolveLinks(mailContentBody, null);
   if (!isHtml) {
     return StringEscapeUtils.unescapeHtml(mailContentBody);
   }
   return mailContentBody;
 }
예제 #17
0
 @RequestMapping(
     value = ApiConstants.PUSH_DATA,
     method = RequestMethod.POST,
     produces = MediaType.APPLICATION_JSON_VALUE)
 @Transactional
 public String pushData(@RequestBody String body) {
   try {
     Map dataMap = new ObjectMapper().readValue(URLDecoder.decode(body, "utf-8"), Map.class);
     leadProcessingService.pushLead(
         new JSONObject((Map) dataMap.get(ApiConstants.PUSH_DATA_FORM_DATA_PARAM)).toString(),
         StringEscapeUtils.unescapeHtml((String) dataMap.get(ApiConstants.PUSH_DATA_PARAMS_PARAM)),
         StringEscapeUtils.unescapeHtml(
             (String) dataMap.get(ApiConstants.PUSH_DATA_REFERRER_PARAM)),
         InternetDomainName.from((String) dataMap.get(ApiConstants.PUSH_DATA_HOST_PARAM))
             .toString(),
         LeadType.FORM);
     return ApiResponseStatuses.toJson(ApiResponseStatuses.OK);
   } catch (IOException e) {
     return ApiResponseStatuses.toJson(ApiResponseStatuses.BAD_REQUEST);
   }
 }
예제 #18
0
 /**
  * Unescapes a string containing entity escapes to a string containing the actual Unicode
  * characters corresponding to the escapes. Supports HTML 4.0 entities.
  *
  * <p>For example, the string "&amp;lt;Fran&amp;ccedil;ais&amp;gt;" will become
  * "&lt;Fran&ccedil;ais&gt;"
  *
  * <p>If an entity is unrecognized, it is left alone, and inserted verbatim into the result
  * string. e.g. "&amp;gt;&amp;zzzz;x" will become "&gt;&amp;zzzz;x".
  *
  * @param str the <code>String</code> to unescape, may be null
  * @return a new unescaped <code>String</code>, <code>null</code> if null string input
  * @see #escapeHtml(Writer, String)
  */
 public static String unescapeHtml(String str) {
   if (str == null) {
     return null;
   }
   try {
     StringWriter writer = new StringWriter((int) (str.length() * 1.5));
     unescapeHtml(writer, str);
     return writer.toString();
   } catch (IOException ioe) {
     // should be impossible
     throw new UnhandledException(ioe);
   }
 }
예제 #19
0
  /**
   * Returns text cleaned from HTML markup.
   *
   * <p>All HTML entity escapes will be unescaped to the actual Unicode characters corresponding to
   * the escapes. Supports HTML 4.0 entities. For example, the string
   * "&amp;lt;Fran&amp;ccedil;ais&amp;gt;" will become "&lt;Fran&ccedil;ais&gt;".
   *
   * <p>All multi-whitespace characters [ \t\n\x0B\f\r] and any kind of Unicode whitespace or
   * invisible separator will be replaced by one space [ ]. For example, the string "fix &nbsp;
   * &nbsp; multi-spaces" will become "fix multi-spaces".
   */
  public static String getPlainText(String inputHtml) {
    LOG.debug("Gettig plain text from input HTML...");

    String plainText = getInstance().filter(inputHtml, ANTISAMY_POLICY_FILE_PLAIN_TEXT);
    if (!StringUtils.isBlank(plainText)) {
      // Unescape HTML entities to Unicode equivalents.
      plainText = StringEscapeUtils.unescapeHtml(plainText);

      // Replace all multi-whitespace characters by one space.
      plainText = plainText.replaceAll("[\\s\\p{Z}]+", " ");
    }

    return plainText;
  }
 /**
  * Prepara il body della mail in base al contenuto e al modello.
  *
  * @param content Il Contenuto per cui costruire il body della mail.
  * @param modelId L'id del modello utilizzato.
  * @param html Indica se il modello è di tipo html o testo semplice.
  * @return Il body della mail completo di blocchi iniziale e finale.
  * @throws ApsSystemException
  */
 private String buildMailBody(Content content, long modelId, boolean html)
     throws ApsSystemException {
   NewsletterConfig config = this.getConfig();
   String header = html ? config.getHtmlHeader() : config.getTextHeader();
   String defaultLang = this.getLangManager().getDefaultLang().getCode();
   String mailContentBody = this.getContentRenderer().render(content, modelId, defaultLang, null);
   mailContentBody = this.getLinkResolver().resolveLinks(mailContentBody, null);
   String footer = html ? config.getHtmlFooter() : config.getTextFooter();
   String mailBody = header.concat(mailContentBody).concat(footer);
   if (!html) {
     return StringEscapeUtils.unescapeHtml(mailBody);
   }
   return mailBody;
 }
예제 #21
0
 protected String getContent() throws OperationException, IOException {
   message = message.trim();
   if (message.startsWith("template:")) {
     String name = message.substring("template:".length()).trim();
     URL url = MailTemplateHelper.getTemplate(name);
     if (url == null) {
       throw new OperationException("No such mail template: " + name);
     }
     InputStream in = url.openStream();
     return FileUtils.read(in);
   } else {
     return StringEscapeUtils.unescapeHtml(message);
   }
 }
  public String view() throws Exception {
    try {
      String success = DomDocumentHelper.toString(this.getDoc());

      String result = new StoreTransformer(this.getTransformInfoInterface()).translate(success);
      return StringEscapeUtils.unescapeHtml(result);
    } catch (Exception e) {
      String error = "Failed to view Generic Body";
      if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
          abcs.logic.communication.log.config.type.LogConfigType.TAGHELPERERROR)) {
        LogUtil.put(LogFactory.getInstance(error, this, "view()", e));
      }
      throw e;
    }
  }
예제 #23
0
  @Override
  protected void processPage(String s) {
    this.language = LANGUAGE_CODE;

    // parse out title
    int start = s.indexOf(XML_START_TAG_TITLE);
    int end = s.indexOf(XML_END_TAG_TITLE, start);
    this.title = StringEscapeUtils.unescapeHtml(s.substring(start + 7, end));

    // determine if article belongs to the article namespace
    start = s.indexOf(XML_START_TAG_NAMESPACE);
    end = s.indexOf(XML_END_TAG_NAMESPACE);
    this.isArticle = s.substring(start + 4, end).trim().equals("0");

    // parse out the document id
    start = s.indexOf(XML_START_TAG_ID);
    end = s.indexOf(XML_END_TAG_ID);
    this.mId = s.substring(start + 4, end);

    // parse out actual text of article
    this.textStart = s.indexOf(XML_START_TAG_TEXT);
    this.textEnd = s.indexOf(XML_END_TAG_TEXT, this.textStart);

    // determine if article is a disambiguation, redirection, and/or stub page.
    Matcher matcher = disambPattern.matcher(page);
    this.isDisambig = matcher.find();
    this.isRedirect =
        s.substring(
                        this.textStart + XML_START_TAG_TEXT.length(),
                        this.textStart
                            + XML_START_TAG_TEXT.length()
                            + IDENTIFIER_REDIRECTION_UPPERCASE.length())
                    .compareTo(IDENTIFIER_REDIRECTION_UPPERCASE)
                == 0
            || s.substring(
                        this.textStart + XML_START_TAG_TEXT.length(),
                        this.textStart
                            + XML_START_TAG_TEXT.length()
                            + IDENTIFIER_REDIRECTION_LOWERCASE.length())
                    .compareTo(IDENTIFIER_REDIRECTION_LOWERCASE)
                == 0;
    this.isStub =
        s.indexOf(IDENTIFIER_STUB_TEMPLATE, this.textStart) != -1
            || s.indexOf(IDENTIFIER_STUB_WIKIPEDIA_NAMESPACE) != -1;
  }
예제 #24
0
 private static String removeMarkupTagsAndUnescapeEntities(
     String string, final boolean unescapeEntities) {
   if (string == null) {
     return null;
   }
   final StringBuilder sb = new StringBuilder();
   final int length = string.length();
   boolean inTag = false;
   boolean inComments = false;
   boolean hasText = false;
   for (int i = 0; i < length; i++) {
     final char c = string.charAt(i);
     if (c == '<'
         && i < length - 1
         && (Character.isLetterOrDigit(string.charAt(i + 1)) || string.charAt(i + 1) == '/')) {
       inTag = true;
     } else if (i < length - 4 && "<!--".equals(string.substring(i, i + 4))) {
       inComments = true;
       i += 3;
     } else if (inComments && i < length - 3 && "-->".equals(string.substring(i, i + 3))) {
       inComments = false;
       hasText = false;
       i += 2;
     } else if (c == '>') {
       inTag = false;
       hasText = false;
     } else if (!inTag && !inComments) {
       if (!hasText) {
         // Append an space if this is the first text right after a tag
         hasText = true;
         if (sb.length() > 0) {
           // But not before the first output character
           sb.append(' ');
         }
       }
       sb.append(c);
     }
   }
   string = sb.toString();
   if (unescapeEntities) {
     string = StringEscapeUtils.unescapeHtml(string);
   }
   return string;
 }
  /**
   * Add a published assessment to gradebook.
   *
   * @param publishedAssessment the published assessment
   * @param g the Gradebook Service
   * @return false: cannot add to gradebook
   * @throws java.lang.Exception
   */
  public boolean addToGradebook(PublishedAssessmentData publishedAssessment, GradebookService g)
      throws Exception {
    // log.info("total point(s) is/are =" +
    //          publishedAssessment.getTotalScore().longValue());
    // log.info("gradebookId =" + GradebookFacade.getGradebookUId());
    boolean added = false;
    // log.info("GradebookService instance=" + g);
    String gradebookUId = GradebookFacade.getGradebookUId();
    if (gradebookUId == null) {
      return false;
    }

    // log.info("inside addToGradebook, gradebook exists? " +
    //          g.isGradebookDefined(gradebookUId));
    if (g.isGradebookDefined(gradebookUId)) {

      // Tool name code added by Josh Holtzman
      Tool tool = ToolManager.getTool("sakai.samigo");
      String appName = null;

      if (tool == null) {
        log.warn(
            "could not get tool named sakai.samigo, "
                + "so we're going to assume we're called 'Tests & Quizzes'");
        appName = "Tests & Quizzes";
      } else {
        appName = tool.getTitle();
      }

      String title = StringEscapeUtils.unescapeHtml(publishedAssessment.getTitle());
      if (!g.isAssignmentDefined(gradebookUId, title)) {
        g.addExternalAssessment(
            gradebookUId,
            publishedAssessment.getPublishedAssessmentId().toString(),
            null,
            title,
            publishedAssessment.getTotalScore().doubleValue(),
            publishedAssessment.getAssessmentAccessControl().getDueDate(),
            appName); // Use the app name from sakai
        added = true;
      }
    }
    return added;
  }
예제 #26
0
  /**
   * Adds the CSS errors.
   *
   * @param errors the array of errors
   * @param sourcePath the source path
   * @param manager the validation manager
   * @param items the list that stores the added validation items
   */
  private void addErrors(
      String[] errors, String sourcePath, List<IProblem> items, List<String> filters) {
    Map<String, String> map;
    for (String error : errors) {
      map = getProperties(error);

      int lineNumber = Integer.parseInt(map.get("line")); // $NON-NLS-1$
      String message = map.get("message"); // $NON-NLS-1$
      String context = map.get("context"); // $NON-NLS-1$
      String property = map.get("property"); // $NON-NLS-1$
      String skippedstring = map.get("skippedstring"); // $NON-NLS-1$
      String errorsubtype = map.get("errorsubtype"); // $NON-NLS-1$

      // Don't attempt to add errors if there are already errors on this line
      if (hasErrorOrWarningOnLine(items, lineNumber)) {
        continue;
      }

      if (message == null) {
        if (property == null) {
          property = context;
        }
        if (skippedstring.equals("[empty string]")) // $NON-NLS-1$
        {
          // alters the text a bit
          skippedstring = "no properties defined"; // $NON-NLS-1$
        }
        message =
            MessageFormat.format(
                "{0} : {1} for {2}", errorsubtype, skippedstring, property); // $NON-NLS-1$
      }
      message = StringEscapeUtils.unescapeHtml(message);
      message = message.replaceAll("\\s+", " "); // $NON-NLS-1$ //$NON-NLS-2$

      if (!isIgnored(message, filters)
          && !containsCSS3Property(message)
          && !containsCSS3AtRule(message)
          && !isFiltered(message)) {
        // there is no info on the line offset or the length of the errored text
        items.add(createError(message, lineNumber, 0, 0, sourcePath));
      }
    }
  }
예제 #27
0
  private static String unescapeHTML(String value, boolean escapeXml) {
    if (value == null) {
      return "";
    }

    /*
       There is a problem with unescapeHtml(String) method  only for apostrophe - ' character.
       When is used entity name &apos; the unscapeHtml(String) doesn't  converts to normal form.
       If it is replaced by entity number &#39; the unscapeHtml(String)  converts to normal form as intended.
    */
    String result = value.replaceAll("&apos;", "&#39;");

    result = StringEscapeUtils.unescapeHtml(result);

    if (escapeXml) {
      result = StringEscapeUtils.escapeXml(result);
    }

    return result;
  }
 @FXML
 private void HandleValidateButtonAction(ActionEvent event) {
   String s = StringEscapeUtils.unescapeHtml(markdownToHtml(SourceText.getText()));
   if (corrector == null) {
     corrector = new Corrector();
   }
   try {
     String result = corrector.checkHtmlContent(s);
     WebEngine webEngine = renderView.getEngine();
     webEngine.loadContent(
         "<!doctype html><html lang='fr'><head><meta charset='utf-8'><base href='file://"
             + MainApp.class.getResource(".").getPath()
             + "' /></head><body>"
             + result
             + "</body></html>");
     webEngine.setUserStyleSheetLocation(
         MainApp.class.getResource("css/content.css").toExternalForm());
   } catch (DOMException e) {
     logger.error(e.getMessage(), e);
   }
 }
  // TODO Use SWEBLE
  private String getText(Revision rev) {
    String text = rev.getRevisionText();

    if (outputPlainText) {
      text = StringEscapeUtils.unescapeHtml(text);

      ParsedPage pp = parser.parse(text);

      if (pp == null) {
        return "";
      }

      text = pp.getText();

      // text = WikiUtils.mediaWikiMarkup2PlainText(text);

      // replace multiple white space with single white space
      text = WikiUtils.cleanText(text);
    }

    return text;
  }
예제 #30
0
  public void testXSSInjection() throws Exception {
    WikiPageInfo wikiPage = null;
    WikiPageInfo wikiPageNew = null;
    try {
      wikiPage = this.wikiService.createWikiPage(SITE_SHORT_NAME_WIKI, "test_wiki", "[[Test]]");
      wikiPageNew = this.wikiService.createWikiPage(SITE_SHORT_NAME_WIKI, "Test", "test_content");
      Pattern LINK_PATTERN_MATCH = Pattern.compile("\\[\\[([^\\|\\]]+)");
      Matcher m = LINK_PATTERN_MATCH.matcher(wikiPage.getContents());
      while (m.find()) {
        String link = m.group(1);
        link += "?title=<script>alert('xss');</script>";
        WikiPageInfo wikiPage2 = this.wikiService.getWikiPage(SITE_SHORT_NAME_WIKI, link);
        WikiPageInfo wikiPage1 =
            this.wikiService.getWikiPage(
                SITE_SHORT_NAME_WIKI, StringEscapeUtils.unescapeHtml(link));
        assertEquals(wikiPage2, wikiPage1);
      }

    } finally {
      this.wikiService.deleteWikiPage(wikiPage);
      this.wikiService.deleteWikiPage(wikiPageNew);
    }
  }