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

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

Introduction

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

Prototype

public static Escaper urlPathSegmentEscaper() 

Source Link

Document

Returns an Escaper instance that escapes strings so they can be safely included in <a href="http://goo.gl/swjbR">URL path segments</a>.

Usage

From source file:com.offbytwo.jenkins.model.ComputerWithDetails.java

public void toggleOffline(boolean crumbFlag) throws IOException {
    // curl --data "json=init" -X POST "http://192.168.99.100:8080/computer/(master)/toggleOffline"
    String name;// w w w.j a va 2s.  com
    if ("master".equals(displayName)) {
        name = "(master)";
    } else {
        name = UrlEscapers.urlPathSegmentEscaper().escape(displayName);
    }

    Map<String, String> data = new HashMap<String, String>();
    data.put("json", "init");
    client.post("/computer/" + name + "/toggleOffline", crumbFlag);
}

From source file:com.google.inject.servlet.ServletUtils.java

/** Normalizes a path by unescaping all safe, percent encoded characters. */
static String normalizePath(String path) {
    StringBuilder sb = new StringBuilder(path.length());
    int queryStart = path.indexOf('?');
    String query = null;//from   www .j a  v a 2  s.  c om
    if (queryStart != -1) {
        query = path.substring(queryStart);
        path = path.substring(0, queryStart);
    }
    // Normalize the path.  we need to decode path segments, normalize and rejoin in order to
    // 1. decode and normalize safe percent escaped characters.  e.g. %70 -> 'p'
    // 2. decode and interpret dangerous character sequences. e.g. /%2E/ -> '/./' -> '/'
    // 3. preserve dangerous encoded characters. e.g. '/%2F/' -> '///' -> '/%2F'
    List<String> segments = new ArrayList<String>();
    for (String segment : SLASH_SPLITTER.split(path)) {
        // This decodes all non-special characters from the path segment.  so if someone passes
        // /%2E/foo we will normalize it to /./foo and then /foo
        String normalized = UrlEscapers.urlPathSegmentEscaper().escape(lenientDecode(segment, UTF_8, false));
        if (".".equals(normalized)) {
            // skip
        } else if ("..".equals(normalized)) {
            if (segments.size() > 1) {
                segments.remove(segments.size() - 1);
            }
        } else {
            segments.add(normalized);
        }
    }
    SLASH_JOINER.appendTo(sb, segments);
    if (query != null) {
        sb.append(query);
    }
    return sb.toString();
}

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

@Override
public void init() {
    HttpURLConnection conn = null;
    try {//from  w w w  .  j  a  v a 2  s. c om
        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:org.apache.servicecomb.foundation.common.http.HttpUtils.java

/**
 * Encode path params. For example, if the path of an operation is {@code /over/there/{pathParam}/tail}, this method
 * should be used to encoded {@code {pathParam}}. In order to keep the path structure, the slash '/' will be encoded
 * into {@code %2F} to avoid path matching problem.
 *
 * @see UrlEscapers#urlPathSegmentEscaper()
 *
 * @param pathParam the path param to be encoded
 * @return the encoded path param//from  w  w w  .  j  av  a  2s .c  o  m
 */
public static String encodePathParam(String pathParam) {
    return UrlEscapers.urlPathSegmentEscaper().escape(pathParam);
}

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];
    }// w w  w  .j  a v  a  2s .  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:org.eclipse.packagedrone.repo.channel.web.artifact.ArtifactController.java

@RequestMapping(value = "/channel/{channelId}/artifacts/{artifactId}/generate", method = RequestMethod.GET)
@HttpConstraint(PERMIT)// w w  w .java 2 s  .  c o  m
public ModelAndView generate(@PathVariable("channelId") final String channelId,
        @PathVariable("artifactId") final String artifactId) {
    return Channels.withArtifact(this.service, channelId, artifactId, ModifiableChannel.class,
            (channel, artifact) -> {
                channel.getContext().regenerate(artifact.getId());
                return new ModelAndView("redirect:/channel/"
                        + UrlEscapers.urlPathSegmentEscaper().escape(artifact.getChannelId().getId())
                        + "/view");
            });
}

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);
    }//  ww w.  j a  v  a  2 s.  c  om
    return response.getContentAsString();
}

From source file:org.eclipse.packagedrone.web.LinkTarget.java

public LinkTarget expandSource(final ReplaceSource source) {
    if (this.url == null || source == null) {
        return this;
    }//  w w w.j  ava  2  s .c o  m

    final ReplaceSource encodeSource = new EscaperSource(source, UrlEscapers.urlPathSegmentEscaper());

    return new LinkTarget(StringReplacer.replace(this.url, encodeSource, PATTERN, false));
}

From source file:com.google.android.apps.forscience.whistlepunk.sensorapi.SensorChoice.java

/**
 * Get the storage strategy for default options that are set on this sensor
 *
 * By default, this can store a Map of Strings mapped to Strings, stored in
 * SharedPreferences.  If you need something more sophisticated or structured, please override
 * with a new OptionsStorage subclass.//from  www.  j a  va2 s  .c  o m
 *
 * These are the _default_ options for any new card opened with this sensor selected.  The user
 * may also be given a UI that will override these defaults on the current card.
 *
 * TODO: actually use and apply these defaults, create a UI to change them.
 */
public NewOptionsStorage getStorageForSensorDefaultOptions(Context context) {
    return new PrefsNewOptionsStorage("sensor_options_" + UrlEscapers.urlPathSegmentEscaper().escape(getId()),
            context);
}

From source file:de.anycook.einkaufszettel.tasks.LoadRecipeIngredientsTask.java

@Override
protected List<Ingredient> doInBackground(String... recipeNames) {
    String recipeName = recipeNames[0];
    RecipeIngredientsStore recipeIngredientsStore = new RecipeIngredientsStore(context);
    recipeIngredientsStore.open();/*from   w w  w.j ava  2  s.  c o m*/
    try {
        //check DB first
        List<Ingredient> ingredients = recipeIngredientsStore.getIngredients(recipeName);
        if (ingredients.size() > 0) {
            return ingredients;
        }

        // if ingredient not in db check if internet connection is available
        // if not stop activity
        if (!ConnectionStatus.isConnected(context)) {
            shownOfflineMessage();
            return ingredients;
        }

        String urlString = String.format(URL_PATTERN, UrlEscapers.urlPathSegmentEscaper().escape(recipeName));
        URL url = new URL(urlString);
        LOGGER.d("Loading ingredients from %s", url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(httpURLConnection.getResponseMessage());
        }
        Reader reader = new InputStreamReader(httpURLConnection.getInputStream());
        Gson gson = new Gson();
        Type collectionType = new TypeToken<ArrayList<Ingredient>>() {
        }.getType();
        ingredients = gson.fromJson(reader, collectionType);

        //add ingredients to DB
        recipeIngredientsStore.addIngredients(recipeName, ingredients);
        return ingredients;
    } catch (IOException e) {
        LOGGER.e(e, "Failed to load recipe ingredients");
        return Collections.emptyList();
    } finally {
        recipeIngredientsStore.close();
    }
}