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:com.facebook.presto.operator.scalar.UrlFunctions.java

@Description("escape a string for use in URL query parameter names and values")
@ScalarFunction//from  ww w .  j a  v a2s  .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.spectralogic.ds3client.networking.NetUtils.java

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("://");
    }/*  w  w w. j  av a2s. c  o  m*/
    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());
}

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

@Description("escape a string for use in URL query parameter names and values")
@ScalarFunction/*from   w ww  .j a  v a 2  s  . c o  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.android.ide.common.res2.StringResourceEscaper.java

@NonNull
static String escape(@NonNull String string, boolean escapeMarkupDelimiters) {
    if (string.isEmpty()) {
        return "";
    }//from  w w w.  j a  v a2  s . co m

    StringBuilder builder = new StringBuilder(string.length() * 3 / 2);

    if (startsOrEndsWithSpace(string)) {
        builder.append('"');
    } else if (startsWithQuestionMarkOrAtSign(string)) {
        builder.append('\\');
    }

    Escaper escaper = buildEscaper(!startsOrEndsWithSpace(string), escapeMarkupDelimiters);
    builder.append(escaper.escape(string));

    if (startsOrEndsWithSpace(string)) {
        builder.append('"');
    }

    return builder.toString();
}

From source file:org.robotframework.ide.eclipse.main.plugin.project.RedEclipseProjectConfig.java

@VisibleForTesting
static IPath resolveToAbsolutePath(final IPath base, final IPath child) throws PathResolvingException {
    if (child.isAbsolute()) {
        return child;
    } else {/*from  w  w w .j av  a2 s. c om*/
        try {
            final Escaper escaper = RedURI.URI_SPECIAL_CHARS_ESCAPER;

            final String portablePath = base.toPortableString();
            final URI filePath = new URI(escaper.escape(portablePath));
            final URI pathUri = filePath.resolve(escaper.escape(child.toString()));
            return new Path(RedURI.reverseUriSpecialCharsEscapes(pathUri.toString()));
        } catch (final Exception e) {
            throw new PathResolvingException("Unable to parse path", e);
        }
    }
}

From source file:com.google.gerrit.httpd.raw.BuckUtils.java

static void displayFailure(String rule, byte[] why, HttpServletResponse res) throws IOException {
    res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    res.setContentType("text/html");
    res.setCharacterEncoding(UTF_8.name());
    CacheHeaders.setNotCacheable(res);//from   www.j  a va  2  s  . co  m

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

From source file:com.google.gapid.views.ErrorDialog.java

public static void showErrorDialog(Shell shell, String text, String detailString) {
    new IconAndMessageDialog(shell) {
        private Group details;

        @Override//from ww  w  .  j a  v a 2s  .c  o m
        protected void configureShell(Shell newShell) {
            super.configureShell(newShell);
            newShell.setText("Error");
        }

        @Override
        protected boolean isResizable() {
            return true;
        }

        @Override
        protected Control createDialogArea(Composite parent) {
            Composite container = (Composite) super.createDialogArea(parent);
            ((GridLayout) container.getLayout()).numColumns = 2;
            createMessageArea(container);

            String msg = String.format(Messages.ERROR_MESSAGE, text);
            withLayoutData(createTextbox(container, SWT.WRAP | SWT.READ_ONLY, msg),
                    withSizeHints(new GridData(SWT.FILL, SWT.CENTER, true, false), getWidthHint(), SWT.DEFAULT))
                            .setBackground(container.getBackground());

            if (detailString != null) {
                ExpandBar bar = withLayoutData(new ExpandBar(container, SWT.NONE),
                        withSpans(new GridData(SWT.FILL, SWT.TOP, true, false), 2, 1));
                new ExpandItem(bar, SWT.NONE, 0).setText("Details...");

                bar.addListener(SWT.Expand, e -> {
                    createDetails(container);
                    Point curr = getShell().getSize();
                    Point want = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
                    if (want.y > curr.y) {
                        getShell().setSize(
                                new Point(curr.x, curr.y + Math.min(MAX_DETAILS_SIZE, want.y - curr.y)));
                    } else {
                        details.requestLayout();
                    }
                });

                bar.addListener(SWT.Collapse, e -> {
                    Point curr = getShell().getSize();
                    if (details != null) {
                        details.dispose();
                        details = null;
                    }
                    Point want = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
                    if (want.y < curr.y) {
                        getShell().setSize(new Point(curr.x, want.y));
                    }
                });
            }

            return container;
        }

        private int getWidthHint() {
            return convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
        }

        private void createDetails(Composite container) {
            details = createGroup(container, "");
            GridDataFactory.fillDefaults().grab(true, true).span(2, 1).applyTo(details);
            Composite inner = createComposite(details, new GridLayout(1, false));
            withLayoutData(createTextbox(inner, DETAILS_STYLE, detailString),
                    new GridData(SWT.FILL, SWT.FILL, true, true));
            withLayoutData(createLink(inner, "<a>File a bug</a> on GitHub", e -> {
                Program.launch(getFileBugUrl());
            }), new GridData(SWT.RIGHT, SWT.BOTTOM, false, false));
            withLayoutData(createLink(inner, "<a>Show logs</a> directory", e -> {
                AboutDialog.showLogDir();
            }), new GridData(SWT.RIGHT, SWT.BOTTOM, false, false));
        }

        private String getFileBugUrl() {
            Escaper esc = UrlEscapers.urlFormParameterEscaper();
            return String.format(FILE_BUG_URL, esc.escape(text), esc.escape(Messages.BUG_BODY));
        }

        @Override
        protected void createButtonsForButtonBar(Composite parent) {
            createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true).setFocus();
        }

        @Override
        protected Image getImage() {
            return getErrorImage();
        }
    }.open();
}

From source file:org.micromanager.utils.ReportingUtils.java

private static String formatAlertMessage(String[] lines) {
    com.google.common.escape.Escaper escaper = com.google.common.html.HtmlEscapers.htmlEscaper();
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    for (String line : lines) {
        sb.append("<div width='640'>");
        sb.append(escaper.escape(line));
        sb.append("</div>");
    }//from ww  w .  j av  a 2  s .  co m
    sb.append("</html>");
    return sb.toString();
}

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

private static void writePostBody(HttpURLConnection conn, Map<String, String> parameters) throws IOException {
    try (OutputStream os = conn.getOutputStream()) {
        Escaper escaper = UrlEscapers.urlFormParameterEscaper();
        // Select non-null (key, value) pairs and join them
        List<String> kvpairs = parameters.entrySet().stream().filter((e) -> (e.getValue() != null))
                .map((e) -> (escaper.escape(e.getKey()) + "=" + escaper.escape(e.getValue())))
                .collect(Collectors.toList());
        String content = AMPERSAND_JOINER.join(kvpairs);
        log.info("First {} characters of POST body are {}", LOG_TRUNCATE_CHARS,
                LessStrings.trunc(content, LOG_TRUNCATE_CHARS));
        os.write(content.getBytes());/*from   w  w w.  j a v a2s  .c o m*/
        os.flush();
    }
}

From source file:com.kamike.misc.FsNameUtils.java

public static String escapeName(String name) {

    Escaper myEscaper = Escapers.builder().addEscape('\'', "").addEscape(' ', "").addEscape('&', "")
            .addEscape('$', "").addEscape('~', "").addEscape('`', "").addEscape('#', "").addEscape('@', "")
            .addEscape('(', "").addEscape('+', "").addEscape(')', "").addEscape('<', "").addEscape('>', "")
            .addEscape('%', "").addEscape('\"', "").addEscape('.', "").addEscape('=', "").addEscape('-', "")
            .addEscape(';', "").addEscape(':', "").addEscape('?', "").addEscape('*', "").addEscape('|', "")
            .addEscape('\\', "").addEscape('/', "").build();

    return myEscaper.escape(name);
}