com.google.api.client.util.escape.CharEscapers Java Examples

The following examples show how to use com.google.api.client.util.escape.CharEscapers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UrlEncodedContent.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void writeTo(OutputStream out) throws IOException {
  Writer writer = new BufferedWriter(new OutputStreamWriter(out, getCharset()));
  boolean first = true;
  for (Map.Entry<String, Object> nameValueEntry : Data.mapOf(data).entrySet()) {
    Object value = nameValueEntry.getValue();
    if (value != null) {
      String name = CharEscapers.escapeUri(nameValueEntry.getKey());
      Class<? extends Object> valueClass = value.getClass();
      if (value instanceof Iterable<?> || valueClass.isArray()) {
        for (Object repeatedValue : Types.iterableOf(value)) {
          first = appendParam(first, writer, name, repeatedValue);
        }
      } else {
        first = appendParam(first, writer, name, value);
      }
    }
  }
  writer.flush();
}
 
Example #2
Source File: UrlEncodedContent.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
private static boolean appendParam(boolean first, Writer writer, String name, Object value)
    throws IOException {
  // ignore nulls
  if (value == null || Data.isNull(value)) {
    return first;
  }
  // append value
  if (first) {
    first = false;
  } else {
    writer.write("&");
  }
  writer.write(name);
  String stringValue =
      CharEscapers.escapeUri(
          value instanceof Enum<?> ? FieldInfo.of((Enum<?>) value).getName() : value.toString());
  if (stringValue.length() != 0) {
    writer.write("=");
    writer.write(stringValue);
  }
  return first;
}
 
Example #3
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the portion of the URL containing the scheme, host and port.
 *
 * <p>For the URL {@code "http://example.com/something?action=add"} this method would return
 * {@code "http://example.com"}.
 *
 * @return scheme://[user-info@]host[:port]
 * @since 1.9
 */
public final String buildAuthority() {
  // scheme, [user info], host, [port]
  StringBuilder buf = new StringBuilder();
  buf.append(Preconditions.checkNotNull(scheme));
  buf.append("://");
  if (userInfo != null) {
    buf.append(verbatim ? userInfo : CharEscapers.escapeUriUserInfo(userInfo)).append('@');
  }
  buf.append(Preconditions.checkNotNull(host));
  int port = this.port;
  if (port != -1) {
    buf.append(':').append(port);
  }
  return buf.toString();
}
 
Example #4
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the path parts (decoded if not {@code verbatim}).
 *
 * @param encodedPath slash-prefixed encoded path, for example {@code
 *     "/m8/feeds/contacts/default/full"}
 * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and
 *     escaping)
 * @return path parts (decoded if not {@code verbatim}), with each part assumed to be preceded by
 *     a {@code '/'}, for example {@code "", "m8", "feeds", "contacts", "default", "full"}, or
 *     {@code null} for {@code null} or {@code ""} input
 */
public static List<String> toPathParts(String encodedPath, boolean verbatim) {
  if (encodedPath == null || encodedPath.length() == 0) {
    return null;
  }
  List<String> result = new ArrayList<String>();
  int cur = 0;
  boolean notDone = true;
  while (notDone) {
    int slash = encodedPath.indexOf('/', cur);
    notDone = slash != -1;
    String sub;
    if (notDone) {
      sub = encodedPath.substring(cur, slash);
    } else {
      sub = encodedPath.substring(cur);
    }
    result.add(verbatim ? sub : CharEscapers.decodeUriPath(sub));
    cur = slash + 1;
  }
  return result;
}
 
Example #5
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/** Adds query parameters from the provided entrySet into the buffer. */
static void addQueryParams(
    Set<Entry<String, Object>> entrySet, StringBuilder buf, boolean verbatim) {
  // (similar to UrlEncodedContent)
  boolean first = true;
  for (Map.Entry<String, Object> nameValueEntry : entrySet) {
    Object value = nameValueEntry.getValue();
    if (value != null) {
      String name =
          verbatim
              ? nameValueEntry.getKey()
              : CharEscapers.escapeUriQuery(nameValueEntry.getKey());
      if (value instanceof Collection<?>) {
        Collection<?> collectionValue = (Collection<?>) value;
        for (Object repeatedValue : collectionValue) {
          first = appendParam(first, buf, name, repeatedValue, verbatim);
        }
      } else {
        first = appendParam(first, buf, name, value, verbatim);
      }
    }
  }
}
 
Example #6
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
private static boolean appendParam(
    boolean first, StringBuilder buf, String name, Object value, boolean verbatim) {
  if (first) {
    first = false;
    buf.append('?');
  } else {
    buf.append('&');
  }
  buf.append(name);
  String stringValue =
      verbatim ? value.toString() : CharEscapers.escapeUriQuery(value.toString());
  if (stringValue.length() != 0) {
    buf.append('=').append(stringValue);
  }
  return first;
}
 
Example #7
Source File: TestingHttpTransport.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
private String build() {
  checkArgument(!Strings.isNullOrEmpty(this.baseUrl));
  checkArgument(!Strings.isNullOrEmpty(this.sourceId));
  checkArgument(!Strings.isNullOrEmpty(this.type));
  // "id", "operations" and "options" are not required
  return String.format(
          URL_FORMAT,
          this.baseUrl,
          this.sourceId,
          this.type
              + (this.id.isEmpty() ? "" : "/" + CharEscapers.escapeUriPath(this.id))
              + (operation.isEmpty() ? "" : ":" + operation))
      + this.options;
}
 
Example #8
Source File: ImplicitResponseUrl.java    From mirror with Apache License 2.0 5 votes vote down vote up
private ImplicitResponseUrl(String scheme, String host, int port, String path, String fragment,
                            String query, String userInfo) {
    setScheme(scheme);
    setHost(host);
    setPort(port);
    setPathParts(toPathParts(path));
    setFragment(fragment != null ? CharEscapers.decodeUri(fragment) : null);
    if (fragment != null) {
        UrlEncodedParser.parse(fragment, this);
    }
    // no need for query parameters
    setUserInfo(userInfo != null ? CharEscapers.decodeUri(userInfo) : null);
}
 
Example #9
Source File: UriTemplate.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes the specified value. If reserved expansion is turned on, then percent-encoded
 * triplets and characters are allowed in the reserved set.
 *
 * @param value the string to be encoded
 * @return the encoded string
 */
private String getEncodedValue(String value) {
  String encodedValue;
  if (reservedExpansion) {
    // Reserved expansion allows percent-encoded triplets and characters in the reserved set.
    encodedValue = CharEscapers.escapeUriPathWithoutReserved(value);
  } else {
    encodedValue = CharEscapers.escapeUriConformant(value);
  }
  return encodedValue;
}
 
Example #10
Source File: UriTemplate.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Expand the template of a composite list property. Eg: If d := ["red", "green", "blue"] then
 * {/d*} is expanded to "/red/green/blue"
 *
 * @param varName the name of the variable the value corresponds to. E.g. "d"
 * @param iterator the iterator over list values. E.g. ["red", "green", "blue"]
 * @param containsExplodeModifiersSet to true if the template contains the explode modifier "*"
 * @param compositeOutput an instance of CompositeOutput. Contains information on how the
 *     expansion should be done
 * @return the expanded list template
 * @throws IllegalArgumentException if the required list path parameter is empty
 */
private static String getListPropertyValue(
    String varName,
    Iterator<?> iterator,
    boolean containsExplodeModifier,
    CompositeOutput compositeOutput) {
  if (!iterator.hasNext()) {
    return "";
  }
  StringBuilder retBuf = new StringBuilder();
  String joiner;
  if (containsExplodeModifier) {
    joiner = compositeOutput.getExplodeJoiner();
  } else {
    joiner = COMPOSITE_NON_EXPLODE_JOINER;
    if (compositeOutput.requiresVarAssignment()) {
      retBuf.append(CharEscapers.escapeUriPath(varName));
      retBuf.append("=");
    }
  }
  while (iterator.hasNext()) {
    if (containsExplodeModifier && compositeOutput.requiresVarAssignment()) {
      retBuf.append(CharEscapers.escapeUriPath(varName));
      retBuf.append("=");
    }
    retBuf.append(compositeOutput.getEncodedValue(iterator.next().toString()));
    if (iterator.hasNext()) {
      retBuf.append(joiner);
    }
  }
  return retBuf.toString();
}
 
Example #11
Source File: UriTemplate.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Expand the template of a composite map property. Eg: If d := [("semi", ";"),("dot",
 * "."),("comma", ",")] then {/d*} is expanded to "/semi=%3B/dot=./comma=%2C"
 *
 * @param varName the name of the variable the value corresponds to. Eg: "d"
 * @param map the map property value. Eg: [("semi", ";"),("dot", "."),("comma", ",")]
 * @param containsExplodeModifier Set to true if the template contains the explode modifier "*"
 * @param compositeOutput contains information on how the expansion should be done
 * @return the expanded map template
 * @throws IllegalArgumentException if the required list path parameter is map
 */
private static String getMapPropertyValue(
    String varName,
    Map<String, Object> map,
    boolean containsExplodeModifier,
    CompositeOutput compositeOutput) {
  if (map.isEmpty()) {
    return "";
  }
  StringBuilder retBuf = new StringBuilder();
  String joiner;
  String mapElementsJoiner;
  if (containsExplodeModifier) {
    joiner = compositeOutput.getExplodeJoiner();
    mapElementsJoiner = "=";
  } else {
    joiner = COMPOSITE_NON_EXPLODE_JOINER;
    mapElementsJoiner = COMPOSITE_NON_EXPLODE_JOINER;
    if (compositeOutput.requiresVarAssignment()) {
      retBuf.append(CharEscapers.escapeUriPath(varName));
      retBuf.append("=");
    }
  }
  for (Iterator<Map.Entry<String, Object>> mapIterator = map.entrySet().iterator();
      mapIterator.hasNext(); ) {
    Map.Entry<String, Object> entry = mapIterator.next();
    String encodedKey = compositeOutput.getEncodedValue(entry.getKey());
    String encodedValue = compositeOutput.getEncodedValue(entry.getValue().toString());
    retBuf.append(encodedKey);
    retBuf.append(mapElementsJoiner);
    retBuf.append(encodedValue);
    if (mapIterator.hasNext()) {
      retBuf.append(joiner);
    }
  }
  return retBuf.toString();
}
 
Example #12
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private GenericUrl(
    String scheme,
    String host,
    int port,
    String path,
    String fragment,
    String query,
    String userInfo,
    boolean verbatim) {
  this.scheme = scheme.toLowerCase(Locale.US);
  this.host = host;
  this.port = port;
  this.pathParts = toPathParts(path, verbatim);
  this.verbatim = verbatim;
  if (verbatim) {
    this.fragment = fragment;
    if (query != null) {
      UrlEncodedParser.parse(query, this, false);
    }
    this.userInfo = userInfo;
  } else {
    this.fragment = fragment != null ? CharEscapers.decodeUri(fragment) : null;
    if (query != null) {
      UrlEncodedParser.parse(query, this);
    }
    this.userInfo = userInfo != null ? CharEscapers.decodeUri(userInfo) : null;
  }
}
 
Example #13
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private void appendRawPathFromParts(StringBuilder buf) {
  int size = pathParts.size();
  for (int i = 0; i < size; i++) {
    String pathPart = pathParts.get(i);
    if (i != 0) {
      buf.append('/');
    }
    if (pathPart.length() != 0) {
      buf.append(verbatim ? pathPart : CharEscapers.escapeUriPath(pathPart));
    }
  }
}
 
Example #14
Source File: ImplicitResponseUrl.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
private ImplicitResponseUrl(String scheme, String host, int port, String path, String fragment,
        String query, String userInfo) {
    setScheme(scheme);
    setHost(host);
    setPort(port);
    setPathParts(toPathParts(path));
    setFragment(fragment != null ? CharEscapers.decodeUri(fragment) : null);
    if (fragment != null) {
        UrlEncodedParser.parse(fragment, this);
    }
    // no need for query parameters
    setUserInfo(userInfo != null ? CharEscapers.decodeUri(userInfo) : null);
}