Example usage for com.google.common.net UrlEscapers urlFormParameterEscaper

List of usage examples for com.google.common.net UrlEscapers urlFormParameterEscaper

Introduction

In this page you can find the example usage for com.google.common.net UrlEscapers urlFormParameterEscaper.

Prototype

public static Escaper urlFormParameterEscaper() 

Source Link

Document

Returns an Escaper instance that escapes strings so they can be safely included in <a href="http://goo.gl/OQEc8">URL form parameter names and values</a>.

Usage

From source file:com.gamejolt.net.QueryStringBuilder.java

private String encode(String value) {
    return UrlEscapers.urlFormParameterEscaper().escape(value);
}

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

@Override
public String[] transform(final InputRow inputRow) {
    final String value = inputRow.getValue(column);
    if (value == null) {
        return new String[1];
    }//  ww w .j  a v a2 s  . c  om
    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 };
}

From source file:common.UrlEncodedPath.java

public String build() {
    if (query.isEmpty()) {
        return path;
    } else {/*w  w  w .  ja  v  a 2 s . com*/
        int size = path.length();
        for (Map.Entry<String, String> entry : query.entrySet()) {
            //                                =                               &
            size += entry.getKey().length() + 1 + entry.getValue().length() + 1;
        }
        // size has one extra &, and one missing ?, so it works out
        StringBuilder builder = new StringBuilder(size);
        builder.append(path);
        builder.append('?');
        Iterator<Map.Entry<String, String>> iter = query.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            builder.append(entry.getKey());
            builder.append('=');
            builder.append(UrlEscapers.urlFormParameterEscaper().escape(entry.getValue()));
            if (iter.hasNext()) {
                builder.append('&');
            }
        }
        return builder.toString();
    }
}

From source file:ratpack.http.internal.DefaultHttpUriBuilder.java

private void buildParameterString() {
    Set<String> keySet = this.params.keySet();

    for (String key : keySet) {

        Object[] paramValues = this.params.get(key).toArray();
        for (Object param : paramValues) {
            if (queryParams.equals("")) {
                queryParams = String.format("?%s=%s", key, param);
            } else {
                queryParams += String.format("&%s=%s", key, param);
            }//from   ww  w  .  j  av  a2s  . c  o  m
        }
    }
    escaper = UrlEscapers.urlFormParameterEscaper();
    queryParams = escaper.escape(queryParams);
}

From source file:org.dllearner.algorithms.qtl.experiments.PathDetectionTask.java

@Override
public List<Path> call() throws Exception {
    if (!cancelled) {

        // check if class was already processed
        String filename = UrlEscapers.urlFormParameterEscaper().escape(cls.toStringID()) + "-" + depth + ".log";
        File file = new File(dataDir, filename);

        if (file.exists()) {
            System.out.println(Thread.currentThread().getId() + ":" + cls.toStringID() + " already analyzed.");
            // load from disk
            List<String> lines;
            try {
                lines = Files.readLines(file, Charsets.UTF_8);

                List<Path> paths = new ArrayList<>();

                // each 5th line contains the path
                for (int i = 0; i < lines.size(); i += 4) {
                    String line = lines.get(i);
                    ArrayList<String> split = Lists.newArrayList(Splitter.on("\t").split(line));
                    String object = split.remove(split.size() - 1);
                    List<Set<String>> propertyClusters = new ArrayList<>();

                    for (String clusterString : split) {
                        Set<String> cluster = new TreeSet<>();
                        for (String property : Splitter.on(",").trimResults().split(clusterString)) {
                            cluster.add(property.replace("[", "").replace("]", ""));
                        }/*from w  w w. j  ava  2s. c o m*/
                        propertyClusters.add(cluster);
                    }

                    paths.add(new Path(cls, propertyClusters, object));
                }

                return paths;
            } catch (IOException e) {
                throw new RuntimeException("Path loading failed. ", e);
            }
        } else {

            QueryExecutionFactory qef;
            if (localMode) {
                // load data
                System.out.println(Thread.currentThread().getId() + ":" + "Loading data of depth " + depth
                        + " for " + cls.toStringID() + "...");
                long s = System.currentTimeMillis();
                Model data = loadDataFromCacheOrCompute(cls, depth, true);
                System.out.println(Thread.currentThread().getId() + ":" + "Got " + data.size() + " triples for "
                        + cls.toStringID() + " in " + (System.currentTimeMillis() - s) + "ms");

                qef = new QueryExecutionFactoryModel(data);
            } else {
                qef = ks.getQueryExecutionFactory();
            }

            // analyze
            System.out.println(Thread.currentThread().getId() + ":" + "Searching for " + cls.toStringID()
                    + " path of length " + depth + "...");
            long s = System.currentTimeMillis();
            List<Path> paths = findPathsOfDepthN(cls, qef, depth, maxPathsPerClass);
            System.out
                    .println(Thread.currentThread().getId() + ":" + "Finished searching for " + cls.toStringID()
                            + " path of length " + depth + " in " + (System.currentTimeMillis() - s) + "ms");

            if (paths.isEmpty()) {
                System.out.println(Thread.currentThread().getId() + ":" + "Could not find " + cls.toStringID()
                        + " path of length " + depth + ".");
            } else {
                System.out.println(Thread.currentThread().getId() + ":" + "Paths found:" + paths);

                // serialize
                String delimiter = "\t";
                try {
                    for (Path path : paths) {
                        String content = Joiner.on(delimiter).join(path.getProperties()) + delimiter
                                + path.getObject() + "\n";
                        content += path.asSPARQLQuery(Var.alloc("s")) + "\n";
                        content += path.asSPARQLPathQuery(Var.alloc("s"));
                        content += "\n#\n";
                        Files.append(content, file, Charsets.UTF_8);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return paths;
        }
    }
    return null;
}

From source file:com.facebook.presto.operator.scalar.UrlFunctions.java

@Description("escape a string for use in URL query parameter names and values")
@ScalarFunction//from www  . ja  v  a 2  s.  c  o  m
@SqlType(StandardTypes.VARCHAR)
public static Slice urlEncode(@SqlType(StandardTypes.VARCHAR) Slice value) {
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    return slice(escaper.escape(value.toString(UTF_8)));
}

From source file:com.google.cloud.tools.eclipse.util.io.HttpUtil.java

@VisibleForTesting
static String getParametersString(Map<String, String> parametersMap) {
    StringBuilder resultBuilder = new StringBuilder();
    boolean ampersandNeeded = false;
    for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
        if (ampersandNeeded) {
            resultBuilder.append('&');
        } else {/*  w  w w.jav a2s  . com*/
            ampersandNeeded = true;
        }
        resultBuilder.append(entry.getKey());
        resultBuilder.append('=');
        resultBuilder.append(UrlEscapers.urlFormParameterEscaper().escape(entry.getValue()));
    }
    return resultBuilder.toString();
}

From source file:io.prestosql.operator.scalar.UrlFunctions.java

@Description("escape a string for use in URL query parameter names and values")
@ScalarFunction//from  ww  w  .j  av  a 2s. co m
@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()));
}

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

private void writeData(HttpURLConnection conn) throws IOException {
    conn.setRequestProperty("Content-Type", contentType);
    try (OutputStream os = conn.getOutputStream()) {
        switch (contentType) {
        case "application/json":
            Jackson.defaultMapper().writeValue(os, data);
            break;
        case "application/x-www-form-urlencoded": {
            Escaper escaper = UrlEscapers.urlFormParameterEscaper();
            StringBuilder content = new StringBuilder();
            Iterator<Map.Entry<String, JsonNode>> fields = data.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> field = fields.next();
                content.append(escaper.escape(field.getKey()));
                content.append("=");
                content.append(escaper.escape(field.getValue().asText()));
                if (fields.hasNext()) {
                    content.append("&");
                }//from w ww  . j  av  a 2  s .  c  o m
            }
            String contentString = content.toString();
            log.info("First {} characters of POST body are {}", LOG_TRUNCATE_CHARS,
                    LessStrings.trunc(contentString, LOG_TRUNCATE_CHARS));
            os.write(contentString.getBytes());
            break;
        }
        default:
            throw new IllegalStateException("Unknown content type " + contentType);
        }
        os.flush();
    }
}

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  .ja  v a2 s.  com
            }

            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);
}