Java com.google.common.escape.Escaper 代码实例

・11 分钟阅读

以下是展示如何使用com.google.common.escape.Escaper的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Asserts that an escaper behaves correctly with respect to null inputs.
 *
 * @param escaper the non-null escaper to test
 * @throws IOException
 */
public static void assertBasic(Escaper escaper) throws IOException {
  // Escapers operate on characters: no characters, no escaping.
  Assert.assertEquals("", escaper.escape(""));
  // Assert that escapers throw null pointer exceptions.
  try {
    escaper.escape((String) null);
    Assert.fail("exception not thrown when escaping a null string");
  } catch (NullPointerException e) {
    // pass
  }
}
 

实例 2


private String normalizeUri(final String uri) {
        try {
                final String decoded= URLDecoder.decode(uri, StandardCharsets.UTF_8.name());
                final Escaper escaper= UrlEscapers.urlFragmentEscaper();
                final int indexOfHash= decoded.indexOf('#');
                if (indexOfHash != -1) {
                        String uriWithHash= escaper.escape(decoded.substring(0, indexOfHash)) + '#';
                        if ((indexOfHash + 1) < decoded.length()) {
                                uriWithHash += escaper.escape(decoded.substring(indexOfHash + 1));
                        }
                        return uriWithHash;
                }
                return escaper.escape(decoded);
        } catch (final Exception e) {
                return uri;
        }
}
 

实例 3


@Override
public String apply(final RuleSetModel config) {
    final Escaper escaper = XmlEscapers.xmlAttributeEscaper();
    final String name = escaper.escape(nullToEmpty(config.getName()));
    final String ref = escaper.escape(nullToEmpty(config.getLocation().getPath()));
    final String refcontext = getContext(config);
    return String.format(Locale.ENGLISH, "<%s %s="%s" %s="%s" %s="%s" />",
                         TAG_NAME_RULESET, ATTRIBUTE_NAME_NAME, name, ATTRIBUTE_NAME_REF, ref, ATTRIBUTE_NAME_REFCONTEXT, refcontext);
}
 

实例 4


private void uiReportMentionValueOccurrences(final Map<String, Object> model,
        final URI entityID, @Nullable final URI property) throws Throwable {
    // Do nothing in case the entity ID is missing
    if (entityID == null || property == null) {
        return;
    }
    // Compute the # of occurrences of all the values of the given property in entity mentions
    final Multiset<Value> propertyValues = HashMultiset.create();
    for (final Record mention : getEntityMentions(entityID, Integer.MAX_VALUE, null)) {
        propertyValues.addAll(mention.get(property, Value.class));
    }
    // Render the table
    final Escaper esc = UrlEscapers.urlFormParameterEscaper();
    final String linkTemplate = "ui?action=entity-mentions&entity="
            + esc.escape(entityID.stringValue()) + "&property="
            + esc.escape(Data.toString(property, Data.getNamespaceMap()))
            + "&value=${element}";
    model.put("valueOccurrencesTable", RenderUtils.renderMultisetTable(new StringBuilder(),
            propertyValues, "Property value", "# Mentions", linkTemplate));
}
 

实例 5


@Override protected void dispatchPost(HttpServletRequest req, HttpServletResponse resp, String truckId)
    throws IOException {
  Truck truck = truckDAO.findById(truckId);
  Escaper escaper = HtmlEscapers.htmlEscaper();
  String name = req.getParameter("name"),
      url = req.getParameter("url"),
      phone = req.getParameter("phone"),
      email = req.getParameter("email"),
      description = req.getParameter("description");
  try {
    Preconditions.checkState(!Strings.isNullOrEmpty(name), "Name cannot be unspecified");
    url = url == null ? null : escaper.escape(url);
    if (!Strings.isNullOrEmpty(url) && !url.startsWith("http")) {
      url = "http://" + url;
    }
    truck = Truck.builder(truck)
        .name(escaper.escape(name))
        .url(url)
        .phone(phone == null ? null : escaper.escape(phone))
        .email(email == null ? null : escaper.escape(email))
        .description(description == null ? null : escaper.escape(description)).build();
    log.log(Level.INFO, "Saving truck {0}", truck);
    truckDAO.save(truck);
    req.setAttribute("flash", "Successfully saved");
  } catch (Exception e) {
    log.log(Level.SEVERE, e.getMessage(), e);
    resp.setStatus(400);
    resp.getWriter().println(e.getMessage());
  }
}
 

实例 6


@Override
public String[] transform(final InputRow inputRow) {
    final String value = inputRow.getValue(column);
    if (value == null) {
        return new String[1];
    }
    final Escaper escaper;
    if (targetFormat == TargetFormat.Content) {
        escaper = XmlEscapers.xmlContentEscaper();
    } else {
        escaper = XmlEscapers.xmlAttributeEscaper();
    }
    final String escaped = escaper.escape(value);
    return new String[] { escaped };
}
 

实例 7


/**
 * Asserts that an escaper behaves correctly with respect to null inputs.
 *
 * @param escaper the non-null escaper to test
 * @throws IOException
 */
public static void assertBasic(Escaper escaper) throws IOException {
  // Escapers operate on characters: no characters, no escaping.
  Assert.assertEquals("", escaper.escape(""));
  // Assert that escapers throw null pointer exceptions.
  try {
    escaper.escape((String) null);
    Assert.fail("exception not thrown when escaping a null string");
  } catch (NullPointerException e) {
    // pass
  }
}
 

实例 8


private String normalizeUri(String uriWithEscapes) {
        String uriWithoutBackslashEscapes = unescapeBackslashEscapes(uriWithEscapes);
        try {
                String uriWithoutHtmlEntities = replaceHtmlEntities(uriWithoutBackslashEscapes,
                                UrlEscapers.urlFormParameterEscaper());
                String decoded = URLDecoder.decode(uriWithoutHtmlEntities, StandardCharsets.UTF_8.name());
                Escaper escaper = UrlEscapers.urlFragmentEscaper();
                int indexOfHash = decoded.indexOf('#');
                if (indexOfHash != -1) {
                        String uri = escaper.escape(decoded.substring(0, indexOfHash)) + '#';
                        if ((indexOfHash + 1) < decoded.length()) {
                                uri += escaper.escape(decoded.substring(indexOfHash + 1));
                        }
                        return uri;
                }
                return escaper.escape(decoded);
        } catch (Exception e) {
                return uriWithoutBackslashEscapes;
        }
}
 

实例 9


/**
 * Adds annotation conditions for a single node.
 * @param conditions Condition list where the conditions should be added to
 * @param index Index for a specific annotation
 * @param annotation The annotation to add
 * @param table Table to operate on
 * @param tas {@link TableAccessStrategy} for the given node.
 */
public void addAnnotationConditions(Collection<String> conditions,
  int index, QueryAnnotation annotation, String table,
  TableAccessStrategy tas)
{
  TextMatching tm = annotation.getTextMatching();
  String column = annotation.getNamespace() == null
    ? "annotext" : "qannotext";
  Escaper escaper = tm != null && tm.isRegex() ? regexEscaper : likeEscaper;
  String val;
  if (tm == null)
  {
    val = "%";
  }
  else
  {
    val = escaper.escape(annotation.getValue());
  }
  String prefix;
  if (annotation.getNamespace() == null)
  {
    prefix = escaper.escape(annotation.getName()) + ":";
  }
  else
  {
    prefix = escaper.escape(annotation.getNamespace())
      + ":" + escaper.escape(annotation.getName()) + ":";
  }
  if (tm == null || tm == TextMatching.EXACT_EQUAL)
  {
    conditions.add(tas.aliasedColumn(table, column, index)
      + " LIKE '" + prefix + val + "'");
  }
  else if (tm == TextMatching.EXACT_NOT_EQUAL)
  {
    conditions.add(tas.aliasedColumn(table, column, index)
      + " LIKE '" + prefix +  "%'");
    conditions.add(tas.aliasedColumn(table, column, index)
      + " NOT LIKE '" + prefix + val + "'");
  }
  else if (tm == TextMatching.REGEXP_EQUAL)
  {
    conditions.add(tas.aliasedColumn(table, column, index)
      + " ~ '^(" + prefix + "(" + val + "))$'");
  }
  else if (tm == TextMatching.REGEXP_NOT_EQUAL)
  {
    conditions.add(tas.aliasedColumn(table, column, index)
      + " LIKE '" + prefix +  "%'");
    conditions.add(tas.aliasedColumn(table, column, index)
      + " !~ '^(" + prefix + "(" +  val + "))$'");
  }
}
 
讨论
淘淘あ西西 profile image