Java Code Examples for com.google.common.escape.Escaper

The following are top voted examples for showing how to use com.google.common.escape.Escaper. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: packagedrone   File: FooBarProcessorFactory.java   View source code 7 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 2
Project: java-binance-api   File: BinanceHistoryFilter.java   View source code 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 3
Project: short-url   File: UrlUtils.java   View source code 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 4
Project: feedsucker   File: DatabaseTools.java   View source code 6 votes vote down vote up
/** Export as table for statistical software (R, pandas, ...) */ 
public void exportDatabaseAsTable() throws IOException {
    List<FeedArticle> articles = getAllArticles();
    BufferedWriter table = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("table.txt"), "UTF-8"));                                
    char delimit = '\t';        
    // to make it readable for pandas read_table, quote strings and remove newlines
    Function<String,String> strProcess = new Function<String,String>() {
      private Escaper rmquote = Escapers.builder().addEscape('"', "").build();        
      private Escaper rmnewline = Escapers.builder().addEscape('\n', "").build();        
      @Override public String apply(String s) {
        if (s == null) s = "";
        s = rmquote.escape(s);
        return new StringBuilder(s.length()+2).append('"').append(s).append('"').toString();
      }
    };       
    table.append(tableHeader(delimit)).append("\n");
    for (FeedArticle art : articles) {
        table.append(toTableRow(art, delimit, strProcess)).append("\n");            
    }
    table.close();
}
 
Example 5
Project: packagedrone   File: Breadcrumbs.java   View source code 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 6
Project: knowledgestore   File: Root.java   View source code 6 votes vote down vote up
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));
}
 
Example 7
Project: knowledgestore   File: Root.java   View source code 6 votes vote down vote up
private void uiReportMentionPropertyOccurrences(final Map<String, Object> model,
        final URI entityID) throws Throwable {

    // Do nothing in case the entity ID is missing
    if (entityID == null) {
        return;
    }

    // Compute the # of occurrences of each property URI in entity mentions
    final Multiset<URI> propertyURIs = HashMultiset.create();
    for (final Record mention : getEntityMentions(entityID, Integer.MAX_VALUE, null)) {
        propertyURIs.addAll(mention.getProperties());
    }

    // Render the table
    final Escaper esc = UrlEscapers.urlFormParameterEscaper();
    final String linkTemplate = "ui?action=entity-mentions&entity="
            + esc.escape(entityID.stringValue()) + "&property=${element}";
    model.put("propertyOccurrencesTable", RenderUtils.renderMultisetTable(new StringBuilder(),
            propertyURIs, "Property", "# Mentions", linkTemplate));
}
 
Example 8
Project: gerrit   File: BazelBuild.java   View source code 6 votes vote down vote up
public void display(String rule, HttpServletResponse res) throws IOException {
  res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  res.setContentType("text/html");
  res.setCharacterEncoding(UTF_8.name());
  CacheHeaders.setNotCacheable(res);

  Escaper html = HtmlEscapers.htmlEscaper();
  try (PrintWriter w = res.getWriter()) {
    w.write("<html><title>BUILD FAILED</title><body>");
    w.format("<h1>%s FAILED</h1>", html.escape(rule));
    w.write("<pre>");
    w.write(html.escape(RawParseUtils.decode(why)));
    w.write("</pre>");
    w.write("</body></html>");
  }
}
 
Example 9
Project: DataCleaner   File: UrlEncoderTransformer.java   View source code 6 votes vote down vote up
@Override
public String[] transform(final InputRow inputRow) {
    final String value = inputRow.getValue(column);
    if (value == null) {
        return new String[1];
    }
    final Escaper escaper;
    switch (targetFormat) {
    case FORM_PARAMETER:
        escaper = UrlEscapers.urlFormParameterEscaper();
        break;
    case FRAGMENT:
        escaper = UrlEscapers.urlFragmentEscaper();
        break;
    case PATH_SEGMENT:
        escaper = UrlEscapers.urlPathSegmentEscaper();
        break;
    default:
        throw new UnsupportedOperationException();
    }
    final String escaped = escaper.escape(value);
    return new String[] { escaped };
}
 
Example 10
Project: ds3_java_sdk   File: NetUtils.java   View source code 6 votes vote down vote up
public static URL buildUrl(final ConnectionDetails connectionDetails, final String path, final Map<String, String> params) throws MalformedURLException {
    final StringBuilder builder = new StringBuilder();
    if (!connectionDetails.getEndpoint().startsWith("http")) {
        builder.append(connectionDetails.isHttps() ? "https" : "http").append("://");
    }
    builder.append(connectionDetails.getEndpoint());
    if(!path.startsWith("/")) {
        builder.append('/');
    }

    final Escaper urlEscaper = SafeStringManipulation.getDs3Escaper();

    builder.append(urlEscaper.escape(path));

    if(params != null && params.size() > 0) {
        builder.append('?');
        builder.append(urlEscaper.escape(buildQueryString(params)));
    }
    return new URL(builder.toString());
}
 
Example 11
Project: AnalyzerBeans   File: UrlEncoderTransformer.java   View source code 6 votes vote down vote up
@Override
public String[] transform(final InputRow inputRow) {
    final String value = inputRow.getValue(column);
    if (value == null) {
        return new String[1];
    }
    final Escaper escaper;
    switch (targetFormat) {
    case FORM_PARAMETER:
        escaper = UrlEscapers.urlFormParameterEscaper();
        break;
    case FRAGMENT:
        escaper = UrlEscapers.urlFragmentEscaper();
        break;
    case PATH_SEGMENT:
        escaper = UrlEscapers.urlPathSegmentEscaper();
        break;
    default:
        throw new UnsupportedOperationException();
    }
    final String escaped = escaper.escape(value);
    return new String[] { escaped };
}
 
Example 12
Project: bazel   File: OptionsParser.java   View source code 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 (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 13
Project: appengine-gcs-client   File: OauthRawGcsService.java   View source code 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 14
Project: timbuctoo   File: HttpRequest.java   View source code 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 15
Project: timbuctoo   File: HttpRequest.java   View source code 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 16
Project: guava-mock   File: EscaperAsserts.java   View source code 5 votes vote down vote up
/**
 * Asserts that an escaper behaves correctly with respect to null inputs.
 *
 * @param escaper the non-null escaper to test
 */
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
  }
}
 
Example 17
Project: ARCLib   File: SolrParams.java   View source code 5 votes vote down vote up
/** Returns this SolrParams as a properly URL encoded string, starting with {@code "?"}, if not empty. */
public String toQueryString() {
    Escaper escaper = UrlEscapers.urlFragmentEscaper();

    final StringBuilder sb = new StringBuilder(128);
    boolean first = true;
    for (final Iterator<String> it = getParameterNamesIterator(); it.hasNext();) {
        final String name = it.next(), nameEnc = escaper.escape(name);
        for (String val : getParams(name)) {
            sb.append(first ? '?' : '&').append(nameEnc).append('=').append(escaper.escape(val));
            first = false;
        }
    }
    return sb.toString();
}
 
Example 18
Project: googles-monorepo-demo   File: EscaperAsserts.java   View source code 5 votes vote down vote up
/**
 * Asserts that an escaper behaves correctly with respect to null inputs.
 *
 * @param escaper the non-null escaper to test
 */
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
  }
}
 
Example 19
Project: google-options   File: OptionsParser.java   View source code 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.
 */
public String describeOptionsHtml(Map<String, String> categoryDescriptions, Escaper escaper) {
  StringBuilder desc = new StringBuilder();
  if (!impl.getOptionsClasses().isEmpty()) {
    List<Field> allFields = Lists.newArrayList();
    for (Class<? extends OptionsBase> optionsClass : impl.getOptionsClasses()) {
      allFields.addAll(impl.getAnnotatedFieldsFor(optionsClass));
    }
    Collections.sort(allFields, OptionsUsage.BY_CATEGORY);
    String prevCategory = null;

    for (Field optionField : allFields) {
      String category = optionField.getAnnotation(Option.class).category();
      DocumentationLevel level = documentationLevel(category);
      if (!category.equals(prevCategory) && level == DocumentationLevel.DOCUMENTED) {
        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 (level == DocumentationLevel.DOCUMENTED) {
        OptionsUsage.getUsageHtml(optionField, desc, escaper);
      }
    }
    desc.append("</dl>\n");
  }
  return desc.toString();
}
 
Example 20
Project: feedsucker   File: BasicTests.java   View source code 5 votes vote down vote up
private static void testEscaping() {
    char delimit = '\t';
    String text = "who can\tescape the tab\tmonster";
    Escaper e = Escapers.builder().addEscape(delimit, "\\"+delimit).build();
    System.out.println(text);
    System.out.println(e.escape(text));
}
 
Example 21
Project: google-cloud-eclipse   File: BugReportCommandHandler.java   View source code 5 votes vote down vote up
@VisibleForTesting
static String formatReportUrl() {
  String body = MessageFormat.format(BODY_TEMPLATE, CloudToolsInfo.getToolsVersion(),
      getCloudSdkVersion(), 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);
}
 
Example 22
Project: sfs   File: ContainerImport.java   View source code 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("/import_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_SRC_DIRECTORY, srcDirectory.toString());
                httpClientRequest.end();
                return handler
                        .flatMap(httpClientResponse ->
                                just(httpClientResponse)
                                        .flatMap(new HttpClientKeepAliveResponseBodyBuffer())
                                        .map(buffer -> new HttpClientResponseAndBuffer(httpClientResponse, buffer)))
                        .single();
            });
}
 
Example 23
Project: sfs   File: GetAccount.java   View source code 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 24
Project: sfs   File: ContainerExport.java   View source code 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 25
Project: sfs   File: VerifyRepairAllContainersExecute.java   View source code 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 26
Project: sfs   File: GetContainer.java   View source code 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 27
Project: spike.x   File: InfluxDb.java   View source code 5 votes vote down vote up
@Override
protected void doRequest(final HttpClient client) {

    // Build query URI
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    StringBuilder queryUri = new StringBuilder(INFLUXDB_QUERY_URI);
    queryUri.append(escaper.escape(m_query));

    m_logger.debug("Executing query: {} (host: {})",
            queryUri, getConnection().getAddress());

    HttpClientRequest request = doGet(queryUri.toString(), new HttpClientResponseAdapter() {

        @Override
        protected void handleFailure(final HttpClientResponse response) {
            if (response.statusCode() != 200) {
                m_logger.error("Failed to execute query: {} (host: {})",
                        m_query,
                        getConnection().getAddress(),
                        new IllegalStateException("HTTP get failure: "
                                + response.statusCode()
                                + "/"
                                + response.statusMessage()));
            }
        }
    });

    // HTTP basic authentication
    if (!Strings.isNullOrEmpty(m_adminUser)) {
        request.putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic "
                + base64UserAndPassword(m_adminUser, m_adminPassword));
    }

    request.exceptionHandler(new DefaultConnectionExceptionHandler(
            getConnection()));
    request.end();
}
 
Example 28
Project: knowledgestore   File: RenderUtils.java   View source code 5 votes vote down vote up
public static <T extends Appendable> T renderMultisetTable(final T out,
        final Multiset<?> multiset, final String elementHeader,
        final String occurrencesHeader, @Nullable final String linkTemplate)
        throws IOException {

    final String tableID = "table" + COUNTER.getAndIncrement();
    out.append("<table id=\"").append(tableID).append("\" class=\"display datatable\">\n");
    out.append("<thead>\n<tr><th>").append(MoreObjects.firstNonNull(elementHeader, "Value"))
            .append("</th><th>")
            .append(MoreObjects.firstNonNull(occurrencesHeader, "Occurrences"))
            .append("</th></tr>\n</thead>\n");
    out.append("<tbody>\n");
    for (final Object element : multiset.elementSet()) {
        final int occurrences = multiset.count(element);
        out.append("<tr><td>");
        RenderUtils.render(element, out);
        out.append("</td><td>");
        if (linkTemplate == null) {
            out.append(Integer.toString(occurrences));
        } else {
            final Escaper esc = UrlEscapers.urlFormParameterEscaper();
            final String e = esc.escape(Data.toString(element, Data.getNamespaceMap()));
            final String u = linkTemplate.replace("${element}", e);
            out.append("<a href=\"").append(u).append("\">")
                    .append(Integer.toString(occurrences)).append("</a>");
        }
        out.append("</td></tr>\n");
    }
    out.append("</tbody>\n</table>\n");
    out.append("<script>$(document).ready(function() { applyDataTable('").append(tableID)
            .append("', false, {}); });</script>");
    return out;
}
 
Example 29
Project: knowledgestore   File: Client.java   View source code 5 votes vote down vote up
private String query(final Object... queryNameValues) {
    final StringBuilder builder = new StringBuilder();
    final Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    String separator = "?";
    for (int i = 0; i < queryNameValues.length; i += 2) {
        final Object name = queryNameValues[i].toString();
        final Object value = queryNameValues[i + 1];
        if (value == null) {
            continue;
        }
        final Iterable<?> iterable = value instanceof Iterable<?> ? (Iterable<?>) value
                : ImmutableSet.of(value);
        for (final Object element : iterable) {
            if (element == null) {
                continue;
            }
            String encoded;
            if (element instanceof Value && !name.equals(Protocol.PARAMETER_DEFAULT_GRAPH)
                    && !name.equals(Protocol.PARAMETER_NAMED_GRAPH)) {
                encoded = Data.toString(element, Data.getNamespaceMap());
            } else {
                encoded = element.toString();
            }
            builder.append(separator).append(name).append("=");
            builder.append(escaper.escape(encoded));
            separator = "&";
        }
    }
    return builder.toString();
}
 
Example 30
Project: guava-libraries   File: EscaperAsserts.java   View source code 5 votes vote down vote up
/**
 * 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
  }
}
 
Example 31
Project: presto   File: UrlFunctions.java   View source code 5 votes vote down vote up
@Description("escape a string for use in URL query parameter names and values")
@ScalarFunction
@SqlType(StandardTypes.VARCHAR)
public static Slice urlEncode(@SqlType(StandardTypes.VARCHAR) Slice value)
{
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    return slice(escaper.escape(value.toStringUtf8()));
}
 
Example 32
Project: DataCleaner   File: XmlEncoderTransformer.java   View source code 5 votes vote down vote up
@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 };
}
 
Example 33
Project: Editor2PDF   File: EditorAnnotation__BehaviorDescriptor.java   View source code 5 votes vote down vote up
static Map<String, String> getIdRefHints_id3xJFGTMthu4(@NotNull org.jetbrains.mps.openapi.model.SNode __thisNode__, String id, String ref) {
  Map<String, String> result = new HashMap<String, String>();
  Escaper htmlEscaper = HtmlEscapers.htmlEscaper();
  result.put("id", htmlEscaper.escape(id));
  if (ref != null) {
    result.put("ref", htmlEscaper.escape(ref));
  }
  return result;
}
 
Example 34
Project: guava   File: EscaperAsserts.java   View source code 5 votes vote down vote up
/**
 * Asserts that an escaper behaves correctly with respect to null inputs.
 *
 * @param escaper the non-null escaper to test
 */
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
  }
}
 
Example 35
Project: guava   File: EscaperAsserts.java   View source code 5 votes vote down vote up
/**
 * Asserts that an escaper behaves correctly with respect to null inputs.
 *
 * @param escaper the non-null escaper to test
 */
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
  }
}
 
Example 36
Project: incubator-gobblin   File: EmbeddedGobblin.java   View source code 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 37
Project: AnalyzerBeans   File: XmlEncoderTransformer.java   View source code 5 votes vote down vote up
@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 };
}
 
Example 38
Project: bazel   File: OptionsParser.java   View source code 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 39
Project: jooby   File: Jooby.java   View source code 5 votes vote down vote up
private void xss(final Env env) {
  Escaper ufe = UrlEscapers.urlFragmentEscaper();
  Escaper fpe = UrlEscapers.urlFormParameterEscaper();
  Escaper pse = UrlEscapers.urlPathSegmentEscaper();
  Escaper html = HtmlEscapers.htmlEscaper();

  env.xss("urlFragment", ufe::escape)
      .xss("formParam", fpe::escape)
      .xss("pathSegment", pse::escape)
      .xss("html", html::escape);
}
 
Example 40
Project: symja_android_library   File: Show3D2ThreeJS.java   View source code 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 Options options = new Options(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).isASTSizeGE(F.Polygon, 2)) {
				elements("polygon", numericAST.getAST(i), builder, dim);
			} else if (numericAST.get(i).isASTSizeGE(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("}\" />");
	}
}