com.google.common.escape.Escaper Java Examples

The following examples show how to use com.google.common.escape.Escaper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpRequest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public String getPathAndQuery() {

    String url = this.path;
    boolean isFirst = true;
    for (Map.Entry<String, String> queryParameter : this.queryParameters.entries()) {
      if (isFirst) {
        url += "?";
        isFirst = false;
      } else {
        url += "&";
      }
      Escaper escaper = UrlEscapers.urlFormParameterEscaper();
      url += escaper.escape(queryParameter.getKey()) + "=" + escaper.escape(queryParameter.getValue());
    }

    return url;
  }
 
Example #2
Source File: Breadcrumbs.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
public Builder add ( final String label, final String targetPattern, final String... pathSegments )
{
    Objects.requireNonNull ( targetPattern );
    Objects.requireNonNull ( pathSegments );

    final Escaper esc = UrlEscapers.urlPathSegmentEscaper ();

    final Object[] encoded = new String[pathSegments.length];
    for ( int i = 0; i < pathSegments.length; i++ )
    {
        encoded[i] = esc.escape ( pathSegments[i] );
    }

    this.entries.add ( new Entry ( label, MessageFormat.format ( targetPattern, encoded ) ) );
    return this;
}
 
Example #3
Source File: FooBarProcessorFactory.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Processor create ( final String configuration ) throws IllegalArgumentException
{
    final FooBarConfiguration cfg = FooBarConfiguration.fromJson ( configuration );

    return new Processor () {

        @Override
        public void process ( final Object context )
        {
            System.out.format ( "Foo bar: %s - %s%n", cfg.getString1 (), context );
        }

        @Override
        public void streamHtmlState ( final PrintWriter writer )
        {
            final Escaper esc = HtmlEscapers.htmlEscaper ();
            writer.format ( "<p>This action is doing foo bar: <code>%s</code></p>", esc.escape ( cfg.getString1 () ) );
        }
    };
}
 
Example #4
Source File: OptionsParser.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a description of all the options this parser can digest. In addition to {@link Option}
 * annotations, this method also interprets {@link OptionsUsage} annotations which give an
 * intuitive short description for the options.
 */
public String describeOptionsHtml(Escaper escaper, String productName) {
  StringBuilder desc = new StringBuilder();
  LinkedHashMap<OptionDocumentationCategory, List<OptionDefinition>> optionsByCategory =
      getOptionsSortedByCategory();
  ImmutableMap<OptionDocumentationCategory, String> optionCategoryDescriptions =
      OptionFilterDescriptions.getOptionCategoriesEnumDescription(productName);

  for (Map.Entry<OptionDocumentationCategory, List<OptionDefinition>> e :
      optionsByCategory.entrySet()) {
    desc.append("<dl>");
    String categoryDescription = optionCategoryDescriptions.get(e.getKey());
    List<OptionDefinition> categorizedOptionsList = e.getValue();

    // Describe the category if we're going to end up using it at all.
    if (!categorizedOptionsList.isEmpty()) {
      desc.append(escaper.escape(categoryDescription)).append(":\n");
    }
    // Describe the options in this category.
    for (OptionDefinition optionDef : categorizedOptionsList) {
      OptionsUsage.getUsageHtml(optionDef, desc, escaper, impl.getOptionsData(), true);
    }
    desc.append("</dl>\n");
  }
  return desc.toString();
}
 
Example #5
Source File: UrlUtils.java    From short-url with Apache License 2.0 6 votes vote down vote up
public static String encodePath(String path) {
	if (path.isEmpty() || path.equals("/")) {
		return path;
	}
	
	StringBuilder sb = new StringBuilder();
	Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
	Iterable<String> iterable = pathSplitter.split(path);
	Iterator<String> iterator = iterable.iterator();
	while (iterator.hasNext()) {
		String part = iterator.next();
		if (part.isEmpty()) {
			sb.append("/");
			continue;
		}
		
		part = escaper.escape(part);
		sb.append(part);
		if (iterator.hasNext()) {
			sb.append("/");
		}
	}
	
	return sb.toString();
}
 
Example #6
Source File: BinanceHistoryFilter.java    From java-binance-api with MIT License 6 votes vote down vote up
public String getAsQuery() {
    StringBuffer sb = new StringBuffer();
    Escaper esc = UrlEscapers.urlFormParameterEscaper();

    if (!Strings.isNullOrEmpty(asset)) {
        sb.append("&asset=").append(esc.escape(asset));
    }
    if (startTime != null) {
        sb.append("&startTime=").append(startTime.getTime());
    }
    if (endTime != null) {
        sb.append("&endTime=").append(endTime.getTime());
    }
    String s = sb.toString();
    return s.length() > 1 ? s.substring(1) : s; // skipping the first &
}
 
Example #7
Source File: DefaultDockerCmdExecFactory.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public InvocationBuilder request() {
    String resource = StringUtils.join(path, "/");

    if (!resource.startsWith("/")) {
        resource = "/" + resource;
    }

    if (!queryParams.isEmpty()) {
        Escaper urlFormParameterEscaper = UrlEscapers.urlFormParameterEscaper();
        resource = queryParams.asMap().entrySet().stream()
            .flatMap(entry -> {
                return entry.getValue().stream().map(s -> {
                    return entry.getKey() + "=" + urlFormParameterEscaper.escape(s);
                });
            })
            .collect(Collectors.joining("&", resource + "?", ""));
    }

    return new DefaultInvocationBuilder(
        dockerHttpClient, objectMapper, resource
    );
}
 
Example #8
Source File: OauthRawGcsService.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public void composeObject(Iterable<String> source, GcsFilename dest, long timeoutMillis)
    throws IOException {
  StringBuilder xmlContent = new StringBuilder(Iterables.size(source) * 50);
  Escaper escaper = XmlEscapers.xmlContentEscaper();
  xmlContent.append("<ComposeRequest>");
  for (String srcFileName : source) {
    xmlContent.append("<Component><Name>")
        .append(escaper.escape(srcFileName))
        .append("</Name></Component>");
  }
  xmlContent.append("</ComposeRequest>");
  HTTPRequest req = makeRequest(
      dest, COMPOSE_QUERY_STRINGS, PUT, timeoutMillis, xmlContent.toString().getBytes(UTF_8));
  HTTPResponse resp;
  try {
    resp = urlfetch.fetch(req);
  } catch (IOException e) {
    throw createIOException(new HTTPRequestInfo(req), e);
  }
  if (resp.getResponseCode() != 200) {
    throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
  }
}
 
Example #9
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public PropertyStats getStats(String user, String source, String propertyName) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/data?user=" + escaper.escape(user)
                        + "&propertyName=" + escaper.escape(propertyName)
                        + (source != null ? "&source=" + escaper.escape(source) : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), PropertyStats.class);
}
 
Example #10
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public UserHighScore topUsers(String propertyName, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/users/top?propertyName=" + escaper.escape(propertyName)
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), UserHighScore.class);
}
 
Example #11
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public ListSearch usersOnline(String propertyName, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/users/online?"
                        + (propertyName != null ? "&propertyName=" + escaper.escape(propertyName) : "")
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), ListSearch.class);
}
 
Example #12
Source File: HttpRequest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public String getPathAndQuery() {
  String url = this.path;
  boolean isFirst = true;
  for (Map.Entry<String, String> queryParameter : this.queryParameters.entries()) {
    if (isFirst) {
      url += "?";
      isFirst = false;
    } else {
      url += "&";
    }
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    url += escaper.escape(queryParameter.getKey()) + "=" + escaper.escape(queryParameter.getValue());
  }

  return url;
}
 
Example #13
Source File: RequestForwardUtils.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void forwardRequestRelativeToCurrentContext(String fwdPath, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {

  if (fwdPath == null || request == null || response == null) {
    String msg = "Path, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToCurrentContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();

  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = request.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example #14
Source File: RequestForwardUtils.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void forwardRequestRelativeToGivenContext(String fwdPath, ServletContext targetContext,
    HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  if (fwdPath == null || targetContext == null || request == null || response == null) {
    String msg = "Path, context, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToGivenContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();
  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = targetContext.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example #15
Source File: Utils.java    From rmlmapper-java with MIT License 6 votes vote down vote up
public static String encodeURI(String url) {
    Escaper escaper = UrlEscapers.urlFragmentEscaper();
    String result = escaper.escape(url);

    result = result.replaceAll("!", "%21");
    result = result.replaceAll("#", "%23");
    result = result.replaceAll("\\$", "%24");
    result = result.replaceAll("&", "%26");
    result = result.replaceAll("'", "%27");
    result = result.replaceAll("\\(", "%28");
    result = result.replaceAll("\\)", "%29");
    result = result.replaceAll("\\*", "%2A");
    result = result.replaceAll("\\+", "%2B");
    result = result.replaceAll(",", "%2C");
    result = result.replaceAll("/", "%2F");
    result = result.replaceAll(":", "%3A");
    result = result.replaceAll(";", "%3B");
    result = result.replaceAll("=", "%3D");
    result = result.replaceAll("\\?", "%3F");
    result = result.replaceAll("@", "%40");
    result = result.replaceAll("\\[", "%5B");
    result = result.replaceAll("]", "%5D");

    return result;
}
 
Example #16
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public ListSearch sourcesOnline(String propertyName, String user, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/sources/online?propertyName=" + escaper.escape(propertyName)
                        + "&user=" + escaper.escape(user)
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), ListSearch.class);
}
 
Example #17
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public SourceHighScore topSources(String user, String propertyName, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/sources/top?propertyName=" + escaper.escape(propertyName)
                        + "&user=" + user
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), SourceHighScore.class);
}
 
Example #18
Source File: Show3D2ThreeJS.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * A 3D Graphics command like
 * 
 * <pre>
 *     Graphics3D(Polygon({{0,0,0}, {0,1,1}, {1,0,0}}))
 * </pre>
 * 
 * will be converted to:
 * 
 * <pre>
 * &lt;graphics3d data="{&quot;viewpoint&quot;: [1.3, -2.4, 2.0], &quot;elements&quot;: [{&quot;coords&quot;:......
 * </pre>
 * </p>
 * 
 * <p>
 * It's a bit messy because of all the HTML escaping. What we are interested in is the data field. It's a JSON dict
 * describing the 3D graphics in terms of graphics primitives. This JSON can be used in
 * <a href="http://threejs.org/">threejs.org</a> to construct a 3D div.
 * </p>
 * 
 * @param ast
 * @param buf
 * @throws IOException
 */
protected static void graphics3dToSVG(IAST ast, StringBuilder buf) {
	EvalEngine engine = EvalEngine.get();
	IAST numericAST = (IAST) engine.evalN(ast);
	double[] viewpoints = new double[] { 1.3, -2.4, 2.0 };
	if (numericAST.size() > 2) {
		final OptionArgs options = new OptionArgs(numericAST.topHead(), numericAST, 2, engine);
		optionViewPoint(options, viewpoints);
	}
	int width = 400;
	int height = 200;
	Dimensions2D dim = new Dimensions2D(width, height);
	buf.append("<graphics3d data=\"{");

	StringBuilder builder = new StringBuilder(1024);
	appendDoubleArray(builder, "viewpoint", viewpoints);
	try {
		for (int i = 1; i < numericAST.size(); i++) {
			// if (numericAST.get(i).isASTSizeGE(F.Line, 2)) {
			// lineToSVG(numericAST.getAST(i), buf, dim);
			// } else
			if (numericAST.get(i).isSameHeadSizeGE(F.Polygon, 2)) {
				elements("polygon", numericAST.getAST(i), builder, dim);
			} else if (numericAST.get(i).isSameHeadSizeGE(F.Point, 2)) {
				elements("point", numericAST.getAST(i), builder, dim);
			}
		}
	} finally {
		builder.append("\"lighting\": [{\"color\": [0.3, 0.2, 0.4], \"type\": \"Ambient\"}, "
				+ "{\"color\": [0.8, 0.0, 0.0], \"position\": [2.0, 0.0, 2.0], \"type\": \"Directional\"}, "
				+ "{\"color\": [0.0, 0.8, 0.0], \"position\": [2.0, 2.0, 2.0], \"type\": \"Directional\"}, "
				+ "{\"color\": [0.0, 0.0, 0.8], \"position\": [0.0, 2.0, 2.0], \"type\": \"Directional\"}], "
				+ "\"axes\": {\"hasaxes\": [false, false, false], "
				+ "\"ticks\": [[[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0], [0.05, 0.1, 0.15000000000000002, 0.25, 0.30000000000000004, 0.35000000000000003, 0.45, 0.5, 0.55, 0.65, 0.7000000000000001, 0.75, 0.8500000000000001, 0.9, 0.9500000000000001], [\"0.0\", \"0.2\", \"0.4\", \"0.6\", \"0.8\", \"1.0\"]], [[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0], [0.05, 0.1, 0.15000000000000002, 0.25, 0.30000000000000004, 0.35000000000000003, 0.45, 0.5, 0.55, 0.65, 0.7000000000000001, 0.75, 0.8500000000000001, 0.9, 0.9500000000000001], [\"0.0\", \"0.2\", \"0.4\", \"0.6\", \"0.8\", \"1.0\"]], [[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0], [0.05, 0.1, 0.15000000000000002, 0.25, 0.30000000000000004, 0.35000000000000003, 0.45, 0.5, 0.55, 0.65, 0.7000000000000001, 0.75, 0.8500000000000001, 0.9, 0.9500000000000001], [\"0.0\", \"0.2\", \"0.4\", \"0.6\", \"0.8\", \"1.0\"]]]}, "
				+ "\"extent\": {\"zmax\": 1.0, \"ymax\": 1.0, \"zmin\": 0.0, \"xmax\": 1.0, \"xmin\": 0.0, \"ymin\": 0.0}");
		Escaper escaper = HtmlEscapers.htmlEscaper();
		buf.append(escaper.escape(builder.toString()));
		buf.append("}\" />");
	}
}
 
Example #19
Source File: OptionsParser.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a description of all the options this parser can digest. In addition to {@link Option}
 * annotations, this method also interprets {@link OptionsUsage} annotations which give an
 * intuitive short description for the options.
 *
 * @param categoryDescriptions a mapping from category names to category descriptions. Options of
 *     the same category (see {@link Option#category}) will be grouped together, preceded by the
 *     description of the category.
 */
@Deprecated
public String describeOptionsHtmlWithDeprecatedCategories(
    Map<String, String> categoryDescriptions, Escaper escaper) {
  OptionsData data = impl.getOptionsData();
  StringBuilder desc = new StringBuilder();
  if (!data.getOptionsClasses().isEmpty()) {
    List<OptionDefinition> allFields = new ArrayList<>();
    for (Class<? extends OptionsBase> optionsClass : data.getOptionsClasses()) {
      allFields.addAll(OptionsData.getAllOptionDefinitionsForClass(optionsClass));
    }
    Collections.sort(allFields, OptionDefinition.BY_CATEGORY);
    String prevCategory = null;

    for (OptionDefinition optionDefinition : allFields) {
      String category = optionDefinition.getOptionCategory();
      if (!category.equals(prevCategory)
          && optionDefinition.getDocumentationCategory()
              != OptionDocumentationCategory.UNDOCUMENTED) {
        String description = categoryDescriptions.get(category);
        if (description == null) {
          description = "Options category '" + category + "'";
        }
        if (prevCategory != null) {
          desc.append("</dl>\n\n");
        }
        desc.append(escaper.escape(description)).append(":\n");
        desc.append("<dl>");
        prevCategory = category;
      }

      if (optionDefinition.getDocumentationCategory()
          != OptionDocumentationCategory.UNDOCUMENTED) {
        OptionsUsage.getUsageHtml(optionDefinition, desc, escaper, impl.getOptionsData(), false);
      }
    }
    desc.append("</dl>\n");
  }
  return desc.toString();
}
 
Example #20
Source File: EmbeddedGobblin.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * This returns the set of jars required by a basic Gobblin ingestion job. In general, these need to be distributed
 * to workers in a distributed environment.
 */
private void loadCoreGobblinJarsToDistributedJars() {
  // Gobblin-api
  distributeJarByClassWithPriority(State.class, 0);
  // Gobblin-core
  distributeJarByClassWithPriority(ConstructState.class, 0);
  // Gobblin-core-base
  distributeJarByClassWithPriority(InstrumentedExtractorBase.class, 0);
  // Gobblin-metrics-base
  distributeJarByClassWithPriority(MetricContext.class, 0);
  // Gobblin-metrics
  distributeJarByClassWithPriority(GobblinMetrics.class, 0);
  // Gobblin-metastore
  distributeJarByClassWithPriority(FsStateStore.class, 0);
  // Gobblin-runtime
  distributeJarByClassWithPriority(Task.class, 0);
  // Gobblin-utility
  distributeJarByClassWithPriority(PathUtils.class, 0);
  // joda-time
  distributeJarByClassWithPriority(ReadableInstant.class, 0);
  // guava
  distributeJarByClassWithPriority(Escaper.class, -10); // Escaper was added in guava 15, so we use it to identify correct jar
  // dropwizard.metrics-core
  distributeJarByClassWithPriority(MetricFilter.class, 0);
  // pegasus
  distributeJarByClassWithPriority(DataTemplate.class, 0);
  // commons-lang3
  distributeJarByClassWithPriority(ClassUtils.class, 0);
  // avro
  distributeJarByClassWithPriority(SchemaBuilder.class, 0);
  // guava-retry
  distributeJarByClassWithPriority(RetryListener.class, 0);
  // config
  distributeJarByClassWithPriority(ConfigFactory.class, 0);
  // reflections
  distributeJarByClassWithPriority(Reflections.class, 0);
  // javassist
  distributeJarByClassWithPriority(ClassFile.class, 0);
}
 
Example #21
Source File: AutoIndex.java    From armeria with Apache License 2.0 5 votes vote down vote up
static HttpData listingToHtml(String dirPath, String mappedDirPath, List<String> listing) {
    final Escaper htmlEscaper = HtmlEscapers.htmlEscaper();
    final Escaper urlEscaper = UrlEscapers.urlFragmentEscaper();
    final String escapedDirPath = htmlEscaper.escape(dirPath);
    final StringBuilder buf = new StringBuilder(listing.size() * 64);
    buf.append(PART1);
    buf.append(escapedDirPath);
    buf.append(PART2);
    buf.append(escapedDirPath);
    buf.append(PART3);
    buf.append(listing.size());
    buf.append(PART4);
    if (!"/".equals(mappedDirPath)) {
        buf.append("<li class=\"directory parent\"><a href=\"../\">../</a></li>\n");
    }
    for (String name : listing) {
        buf.append("<li class=\"");
        if (name.charAt(name.length() - 1) == '/') {
            buf.append("directory");
        } else {
            buf.append("file");
        }
        buf.append("\"><a href=\"");
        buf.append(urlEscaper.escape(name));
        buf.append("\">");
        buf.append(name);
        buf.append("</a></li>\n");
    }
    buf.append(PART5);
    return HttpData.ofUtf8(buf.toString());
}
 
Example #22
Source File: UrlFunctions.java    From presto with Apache License 2.0 5 votes vote down vote up
@Description("Escape a string for use in URL query parameter names and values")
@ScalarFunction
@LiteralParameters({"x", "y"})
@Constraint(variable = "y", expression = "min(2147483647, x * 12)")
@SqlType("varchar(y)")
public static Slice urlEncode(@SqlType("varchar(x)") Slice value)
{
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    return slice(escaper.escape(value.toStringUtf8()));
}
 
Example #23
Source File: GetContainer.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<HttpClientResponse> call(Void aVoid) {
    return auth.toHttpAuthorization()
            .flatMap(new Func1<String, Observable<HttpClientResponse>>() {
                @Override
                public Observable<HttpClientResponse> call(String s) {
                    final Escaper escaper = urlFormParameterEscaper();

                    Iterable<String> keyValues = from(queryParams.entries())
                            .transform(input -> escaper.escape(input.getKey()) + '=' + escaper.escape(input.getValue()));

                    String query = on('&').join(keyValues);

                    ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                    HttpClientRequest httpClientRequest =
                            httpClient.get("/openstackswift001/" + accountName + "/" + containerName + (query.length() > 0 ? "?" + query : ""), handler::complete)
                                    .exceptionHandler(handler::fail)
                                    .setTimeout(20000)
                                    .putHeader(AUTHORIZATION, s);
                    for (String entry : headerParams.keySet()) {
                        httpClientRequest = httpClientRequest.putHeader(entry, headerParams.get(entry));
                    }
                    httpClientRequest.end();
                    return handler
                            .single();
                }
            });
}
 
Example #24
Source File: VerifyRepairAllContainersExecute.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<HttpClientResponseAndBuffer> call(Void aVoid) {
    return auth.toHttpAuthorization()
            .flatMap(s -> {
                final Escaper escaper = urlFormParameterEscaper();

                Iterable<String> keyValues = FluentIterable.from(queryParams.entries())
                        .transform(input -> escaper.escape(input.getKey()) + '=' + escaper.escape(input.getValue()));

                String query = Joiner.on('&').join(keyValues);

                ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                HttpClientRequest httpClientRequest =
                        httpClient.post("/verify_repair_containers" + (query.length() > 0 ? "?" + query : ""), handler::complete)
                                .exceptionHandler(handler::fail)
                                .setTimeout(20000)
                                .putHeader(Jobs.Parameters.TIMEOUT, String.valueOf(TimeUnit.MINUTES.toMillis(1)))
                                .putHeader(HttpHeaders.AUTHORIZATION, s);
                for (String entry : headerParams.keySet()) {
                    httpClientRequest = httpClientRequest.putHeader(entry, headerParams.get(entry));
                }
                httpClientRequest.end();
                return handler
                        .flatMap(httpClientResponse ->
                                Defer.just(httpClientResponse)
                                        .flatMap(new HttpClientKeepAliveResponseBodyBuffer())
                                        .map(buffer -> new HttpClientResponseAndBuffer(httpClientResponse, buffer)))
                        .single();
            });
}
 
Example #25
Source File: ContainerExport.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<HttpClientResponseAndBuffer> call(Void aVoid) {
    return auth.toHttpAuthorization()
            .flatMap(s -> {
                final Escaper escaper = urlFormParameterEscaper();

                Iterable<String> keyValues = from(queryParams.entries())
                        .transform(input -> escaper.escape(input.getKey()) + '=' + escaper.escape(input.getValue()));

                String query = on('&').join(keyValues);

                ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                HttpClientRequest httpClientRequest =
                        httpClient.post("/export_container/" + accountName + "/" + containerName + (query.length() > 0 ? "?" + query : ""), handler::complete)
                                .exceptionHandler(handler::fail)
                                .setTimeout(20000)
                                .putHeader(AUTHORIZATION, s);
                for (String entry : headerParams.keySet()) {
                    httpClientRequest = httpClientRequest.putHeader(entry, headerParams.get(entry));
                }
                httpClientRequest = httpClientRequest.putHeader(X_SFS_DEST_DIRECTORY, destDirectory.toString());
                httpClientRequest.end();
                return handler
                        .flatMap(httpClientResponse ->
                                just(httpClientResponse)
                                        .flatMap(new HttpClientKeepAliveResponseBodyBuffer())
                                        .map(buffer -> new HttpClientResponseAndBuffer(httpClientResponse, buffer)))
                        .single();
            });
}
 
Example #26
Source File: GetAccount.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<HttpClientResponse> call(Void aVoid) {
    return auth.toHttpAuthorization()
            .flatMap(new Func1<String, Observable<HttpClientResponse>>() {
                @Override
                public Observable<HttpClientResponse> call(String s) {

                    final Escaper escaper = urlFormParameterEscaper();

                    Iterable<String> keyValues = from(queryParams.entries())
                            .transform(input -> escaper.escape(input.getKey()) + '=' + escaper.escape(input.getValue()));

                    String query = on('&').join(keyValues);

                    ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                    HttpClientRequest httpClientRequest = httpClient.get("/openstackswift001/" + accountName + (query.length() > 0 ? "?" + query : ""), handler::complete)
                            .exceptionHandler(handler::fail)
                            .setTimeout(10000)
                            .putHeader(AUTHORIZATION, s);

                    for (String entry : headerParams.keySet()) {
                        httpClientRequest = httpClientRequest.putHeader(entry, headerParams.get(entry));
                    }
                    httpClientRequest.end();
                    return handler
                            .single();
                }
            });

}
 
Example #27
Source File: UDFUrlEncode.java    From hive-third-functions with Apache License 2.0 5 votes vote down vote up
public Text evaluate(String value) {
    if (value == null) {
        return null;
    }
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    result.set(escaper.escape(value));
    return result;
}
 
Example #28
Source File: WebMvcConfig.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 配置格式化器
 * @author Frodez
 * @date 2019-05-10
 */
@Override
public void addFormatters(FormatterRegistry registry) {
	//对字符串进行转义
	registry.addConverter(new Converter<String, String>() {

		private final Escaper escaper = HtmlEscapers.htmlEscaper();

		@Override
		public String convert(String source) {
			return escaper.escape(source);
		}
	});

}
 
Example #29
Source File: ConfigurableUnwiseCharsEncoder.java    From styx with Apache License 2.0 5 votes vote down vote up
private static Escaper newEscaper(String unwiseChars) {
    if (isNullOrEmpty(unwiseChars)) {
        return nullEscaper();
    }
    CharEscaperBuilder builder = new CharEscaperBuilder();

    stream(unwiseChars.split(","))
            .filter(Strings::isNotEmpty)
            .map(token -> token.charAt(0))
            .forEach(c -> builder.addEscape(c, "%" + toHexString(c).toUpperCase()));

    return builder.toEscaper();
}
 
Example #30
Source File: BugReportCommandHandler.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static String formatReportUrl() {
  String body = MessageFormat.format(BODY_TEMPLATE, CloudToolsInfo.getToolsVersion(),
      getCloudSdkVersion(), getCloudSdkManagementOption(),
      CloudToolsInfo.getEclipseVersion(),
      System.getProperty("os.name"), System.getProperty("os.version"),
      System.getProperty("java.version"));

  Escaper escaper = UrlEscapers.urlFormParameterEscaper();
  return BUG_REPORT_URL + "?body=" + escaper.escape(body);
}