Example usage for com.google.common.escape Escaper escape

List of usage examples for com.google.common.escape Escaper escape

Introduction

In this page you can find the example usage for com.google.common.escape Escaper escape.

Prototype

public abstract String escape(String string);

Source Link

Document

Returns the escaped form of a given literal string.

Usage

From source file:org.sfs.integration.java.func.GetAccount.java

@Override
public Observable<HttpClientResponse> call(Void aVoid) {
    return auth.toHttpAuthorization().flatMap(new Func1<String, Observable<HttpClientResponse>>() {
        @Override/*from w  ww.j  ava  2  s.  c  o m*/
        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();
        }
    });

}

From source file:brooklyn.networking.vclouddirector.NatMicroserviceClient.java

@Beta
public String list() {
    HttpClient client = HttpTool.httpClientBuilder().uri(microserviceUri).trustSelfSigned().build();

    Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
    URI uri = URI.create(Urls.mergePaths(microserviceUri,
            "/v1/nat" + "?endpoint=" + escaper.escape(endpoint)
                    + (Strings.isNonBlank(vDC) ? "&vdc=" + escaper.escape(vDC) : "") + "&identity="
                    + escaper.escape(identity) + "&credential=" + escaper.escape(credential)));

    if (LOG.isDebugEnabled())
        LOG.debug("GET {}", uri.toString().replace(escaper.escape(credential), "xxxxxxxx"));

    HttpToolResponse response = HttpTool.httpGet(client, uri, ImmutableMap.<String, String>of());
    if (response.getResponseCode() < 200 || response.getResponseCode() >= 300) {
        String msg = "List NAT Rules failed for " + endpoint + ": " + response.getResponseCode() + "; "
                + response.getReasonPhrase() + ": " + response.getContentAsString();
        LOG.info(msg + "; rethrowing");
        throw new RuntimeException(msg);
    }//from   w w w .j  a v a  2s  .c  o m
    return response.getContentAsString();
}

From source file:brooklyn.networking.vclouddirector.NatMicroserviceClient.java

@Override
public HostAndPort closePortForwarding(PortForwardingConfig args) {
    HttpClient client = HttpTool.httpClientBuilder().uri(microserviceUri).trustSelfSigned().build();

    Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
    URI uri = URI.create(Urls.mergePaths(microserviceUri,
            "/v1/nat" + "?endpoint=" + escaper.escape(endpoint)
                    + (Strings.isNonBlank(vDC) ? "&vdc=" + escaper.escape(vDC) : "") + "&identity="
                    + escaper.escape(identity) + "&credential=" + escaper.escape(credential) + "&protocol="
                    + args.getProtocol() + "&original=" + args.getPublicEndpoint() + "&translated="
                    + args.getTargetEndpoint()));

    if (LOG.isDebugEnabled())
        LOG.debug("DELETE {}", uri.toString().replace(escaper.escape(credential), "xxxxxxxx"));

    HttpToolResponse response = HttpTool.httpDelete(client, uri, ImmutableMap.<String, String>of());
    if (response.getResponseCode() < 200 || response.getResponseCode() >= 300) {
        String msg = "Delete NAT Rule failed for " + args + ": " + response.getResponseCode() + "; "
                + response.getReasonPhrase() + ": " + response.getContentAsString();
        LOG.info(msg + "; rethrowing");
        throw new RuntimeException(msg);
    }/*from   w  w  w  .  ja v a  2  s  .  c o  m*/
    return args.getPublicEndpoint();
}

From source file:brooklyn.networking.vclouddirector.NatMicroserviceClient.java

@Override
public HostAndPort openPortForwarding(PortForwardingConfig args) {
    HttpClient client = HttpTool.httpClientBuilder().uri(microserviceUri).trustSelfSigned().build();

    Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
    URI uri = URI.create(Urls.mergePaths(microserviceUri,
            "/v1/nat" + "?endpoint=" + escaper.escape(endpoint)
                    + (Strings.isNonBlank(vDC) ? "&vdc=" + escaper.escape(vDC) : "") + "&identity="
                    + escaper.escape(identity) + "&credential=" + escaper.escape(credential) + "&protocol="
                    + args.getProtocol() + "&original=" + args.getPublicEndpoint()
                    + (args.getPublicPortRange() == null ? ""
                            : "&originalPortRange=" + args.getPublicPortRange().toString())
                    + "&translated=" + args.getTargetEndpoint()));

    if (LOG.isDebugEnabled())
        LOG.debug("PUT {}", uri.toString().replace(escaper.escape(credential), "xxxxxxxx"));

    HttpToolResponse response = HttpTool.httpPut(client, uri, ImmutableMap.<String, String>of(), new byte[0]);
    if (response.getResponseCode() < 200 || response.getResponseCode() >= 300) {
        String msg = "Open NAT Rule failed for " + args + ": " + response.getResponseCode() + "; "
                + response.getReasonPhrase() + ": " + response.getContentAsString();
        LOG.info(msg + "; rethrowing");
        throw new RuntimeException(msg);
    }/*from w ww.  j av  a 2s.  c om*/
    return HostAndPort.fromString(response.getContentAsString());
}

From source file:org.eobjects.analyzer.beans.codec.XmlEncoderTransformer.java

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

From source file:org.gradle.plugin.use.resolve.service.internal.PluginResolutionServiceClient.java

@Nullable
Response<PluginUseMetaData> queryPluginMetadata(final PluginRequest pluginRequest, String portalUrl) {
    Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
    String escapedId = escaper.escape(pluginRequest.getId().toString());
    String escapedPluginVersion = escaper.escape(pluginRequest.getVersion());
    String escapedGradleVersion = escaper.escape(GradleVersion.current().getVersion());

    final String requestUrl = String.format(portalUrl + REQUEST_URL, escapedGradleVersion, escapedId,
            escapedPluginVersion);//from   w w w.j  ava2s.c om
    final URI requestUri = toUri(requestUrl, "plugin request");

    HttpResponseResource response = null;
    try {
        response = resourceAccessor.getRawResource(requestUri);
        final int statusCode = response.getStatusCode();
        if (!response.getContentType().equalsIgnoreCase("application/json")) {
            final String message = String.format(
                    "Response from '%s' was not a valid plugin resolution service response (returned content type '%s', not 'application/json')",
                    requestUri, response.getContentType());
            if (LOGGER.isInfoEnabled()) {
                response.withContent(new Action<InputStream>() {
                    public void execute(InputStream inputStream) {
                        try {
                            String content = IOUtils.toString(inputStream, "utf8"); // might not be UTF8, but good enough
                            LOGGER.info("{}, content:\n{}", message, content);
                        } catch (IOException e) {
                            LOGGER.info(String.format("exception raised while trying to log response from %s",
                                    requestUri), e);
                        }
                    }
                });
            }
            throw new GradleException(message);
        }

        return response.withContent(new Transformer<Response<PluginUseMetaData>, InputStream>() {
            public Response<PluginUseMetaData> transform(InputStream inputStream) {
                Reader reader;
                try {
                    reader = new InputStreamReader(inputStream, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new AssertionError(e);
                }
                try {
                    if (statusCode == 200) {
                        PluginUseMetaData metadata = new Gson().fromJson(reader, PluginUseMetaData.class);
                        metadata.verify();
                        return new SuccessResponse<PluginUseMetaData>(metadata, statusCode);
                    } else if (statusCode >= 400 && statusCode < 600) {
                        ErrorResponse errorResponse = new Gson().fromJson(reader, ErrorResponse.class);
                        return new ErrorResponseResponse<PluginUseMetaData>(errorResponse, statusCode);
                    } else {
                        throw new GradleException("Received unexpected HTTP response status " + statusCode
                                + " from " + requestUrl);
                    }
                } catch (JsonSyntaxException e) {
                    throw new GradleException("Failed to parse plugin resolution service JSON response.", e);
                } catch (JsonIOException e) {
                    throw new GradleException("Failed to read plugin resolution service JSON response.", e);
                }
            }
        });
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOGGER.warn("Error closing HTTP resource", e);
        }
    }
}

From source file:annis.sqlgen.AnnotationConditionProvider.java

/**
 * 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/*w  w  w.  ja  va  2  s  .  c o m*/
 * @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 + "))$'");
    }
}

From source file:com.addthis.hydra.task.source.DataSourceHttp.java

@Override
public void init() {
    HttpURLConnection conn = null;
    try {/* ww w.  j  a v a2 s .c o  m*/
        StringBuilder urlMaker = new StringBuilder(url);
        if (!params.isEmpty()) {
            Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
            urlMaker.append('?');
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlMaker.append(escaper.escape(entry.getKey()));
                urlMaker.append('=');
                urlMaker.append(escaper.escape(entry.getValue()));
                urlMaker.append('&');
            }
        }
        URL javaUrl = new URL(urlMaker.toString());
        conn = (HttpURLConnection) javaUrl.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        if (!data.isNull()) {
            writeData(conn);
        }
        underlyingInputStream = conn.getInputStream();
        bundleizer = format.createBundleizer(underlyingInputStream, new ListBundle());
    } catch (Exception outer) {
        if (conn != null && conn.getErrorStream() != null) {
            try {
                log.error("URL connection was unsuccessful. Response is {}",
                        new String(ByteStreams.toByteArray(conn.getErrorStream())));
            } catch (IOException inner) {
                log.error("During connection error failure to read error stream: ", inner);
            }
        }
        throw Throwables.propagate(outer);
    }
}

From source file:jeeves.config.springutil.MultiNodeAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final SecurityContext context = SecurityContextHolder.getContext();
    if (context != null) {
        final Authentication user = context.getAuthentication();

        if (user != null) {
            final ConfigurableApplicationContext appContext = getApplicationContextFromServletContext(
                    getServletContext());
            final String nodeId = appContext.getBean(NodeInfo.class).getId();

            final HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            final String lang = getRequestLanguage(appContext, httpServletRequest);
            final String redirectedFrom = httpServletRequest.getRequestURI();

            String oldNodeId = null;

            for (GrantedAuthority grantedAuthority : user.getAuthorities()) {
                String authName = grantedAuthority.getAuthority();
                if (authName.startsWith(User.NODE_APPLICATION_CONTEXT_KEY)) {
                    oldNodeId = authName.substring(User.NODE_APPLICATION_CONTEXT_KEY.length());
                    break;
                }// w w  w  .j a  va2 s .  c o m
            }

            if (getServletContext().getAttribute(User.NODE_APPLICATION_CONTEXT_KEY + oldNodeId) == null) {
                // the application context associated with the node id doesn't exist so log user out.
                SecurityContextHolder.clearContext();
            } else if (_location != null) {
                if (oldNodeId != null && !oldNodeId.equals(nodeId)) {
                    final Escaper escaper = UrlEscapers.urlFormParameterEscaper();
                    final String location = getServletContext().getContextPath()
                            + _location.replace("@@lang@@", escaper.escape(lang))
                                    .replace("@@nodeId@@", escaper.escape(nodeId))
                                    .replace("@@redirectedFrom@@", escaper.escape(redirectedFrom))
                                    .replace("@@oldNodeId@@", escaper.escape(oldNodeId))
                                    .replace("@@oldUserName@@", escaper.escape(user.getName()));

                    String requestURI = httpServletRequest.getRequestURI();
                    // drop the ! at the end so we can view the xml of the warning page
                    if (requestURI.endsWith("!")) {
                        requestURI = requestURI.substring(0, requestURI.length() - 1);
                    }
                    final boolean isNodeWarningPage = requestURI.equals(location.split("\\?")[0]);
                    if (!isNodeWarningPage) {
                        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                        httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(location));
                        return;
                    }
                }
            } else {
                throwAuthError();
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:org.eclipse.mylyn.internal.wikitext.commonmark.inlines.PotentialBracketEndDelimiter.java

private String normalizeUri(String uriWithEscapes) {
    String uriWithoutBackslashEscapes = unescapeBackslashEscapes(uriWithEscapes);
    try {/*from  w ww .j a  v  a2 s.c  o m*/
        String uriWithoutHtmlEntities = replaceHtmlEntities(uriWithoutBackslashEscapes,
                UrlEscapers.urlFormParameterEscaper());
        String decoded = URLDecoder.decode(uriWithoutHtmlEntities, StandardCharsets.UTF_8.name());
        Escaper escaper = UrlEscapers.urlFragmentEscaper();
        return escaper.escape(decoded);
    } catch (Exception e) {
        return uriWithoutBackslashEscapes;
    }
}