com.google.api.client.http.HttpMediaType Java Examples

The following examples show how to use com.google.api.client.http.HttpMediaType. 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: Attachments.java    From java-asana with MIT License 6 votes vote down vote up
/**
 * Upload a file and attach it to a task
 *
 * @param task        Globally unique identifier for the task.
 * @param fileContent Content of the file to be uploaded
 * @param fileName    Name of the file to be uploaded
 * @param fileType    MIME type of the file to be uploaded
 * @return Request object
 */
public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {
    MultipartContent.Part part = new MultipartContent.Part()
            .setContent(new InputStreamContent(fileType, fileContent))
            .setHeaders(new HttpHeaders().set(
                    "Content-Disposition",
                    String.format("form-data; name=\"file\"; filename=\"%s\"", fileName) // TODO: escape fileName?
            ));
    MultipartContent content = new MultipartContent()
            .setMediaType(new HttpMediaType("multipart/form-data").setParameter("boundary", UUID.randomUUID().toString()))
            .addPart(part);

    String path = String.format("/tasks/%s/attachments", task);
    return new ItemRequest<Attachment>(this, Attachment.class, path, "POST")
            .data(content);
}
 
Example #2
Source File: MockLowLevelHttpRequest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns HTTP content as a string, taking care of any encodings of the content if necessary.
 *
 * <p>Returns an empty string if there is no HTTP content.
 *
 * @since 1.12
 */
public String getContentAsString() throws IOException {
  if (getStreamingContent() == null) {
    return "";
  }
  // write content to a byte[]
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  getStreamingContent().writeTo(out);
  // determine gzip encoding
  String contentEncoding = getContentEncoding();
  if (contentEncoding != null && contentEncoding.contains("gzip")) {
    InputStream contentInputStream =
        new GZIPInputStream(new ByteArrayInputStream(out.toByteArray()));
    out = new ByteArrayOutputStream();
    IOUtils.copy(contentInputStream, out);
  }
  // determine charset parameter from content type
  String contentType = getContentType();
  HttpMediaType mediaType = contentType != null ? new HttpMediaType(contentType) : null;
  Charset charset =
      mediaType == null || mediaType.getCharsetParameter() == null
          ? Charsets.ISO_8859_1
          : mediaType.getCharsetParameter();
  return out.toString(charset.name());
}
 
Example #3
Source File: DicomWebClientTest.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 6 votes vote down vote up
@Test
public void testDicomWebClient_Stow() throws Exception {
  fakeDicomWebServer.addResponseWithStatusCode(200);

  String data = "some data";
  client.stowRs(new ByteArrayInputStream(data.getBytes()));

  FakeWebServer.Request req = fakeDicomWebServer.getRequests().firstElement();

  ByteArrayOutputStream body = new ByteArrayOutputStream();
  req.request.getStreamingContent().writeTo(body);

  String contentType = req.request.getContentType();
  HttpMediaType mediaType = new HttpMediaType(contentType);
  String boundary = mediaType.getParameter("boundary");

  MultipartHandler handler = new MultipartHandler();
  MultiPartParser parser = new MultiPartParser(handler,boundary);
  parser.parse(ByteBuffer.wrap(body.toByteArray()), true);

  assertThat(StandardCharsets.UTF_8.decode(handler.lastItem).toString()).isEqualTo(data);
}
 
Example #4
Source File: Atom.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the given content type matches the Atom content type specified in {@link #MEDIA_TYPE}.
 *
 * @throws IllegalArgumentException if content type doesn't match
 */
public static void checkContentType(String contentType) {
  Preconditions.checkArgument(contentType != null); // for backwards compatibility
  Preconditions.checkArgument(
      HttpMediaType.equalsIgnoreParameters(MEDIA_TYPE, contentType),
      "Wrong content type: expected <" + MEDIA_TYPE + "> but got <%s>",
      contentType);
}
 
Example #5
Source File: LenientTokenResponseException.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link LenientTokenResponseException}.
 * <p>
 * If there is a JSON error response, it is parsed using
 * {@link TokenErrorResponse}, which can be inspected using
 * {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 * 
 * @param jsonFactory JSON factory
 * @param readResponse an HTTP response that has already been read
 * @param responseContent the content String of the HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static LenientTokenResponseException from(JsonFactory jsonFactory,
        HttpResponse readResponse, String responseContent) {
    HttpResponseException.Builder builder = new HttpResponseException.Builder(
            readResponse.getStatusCode(), readResponse.getStatusMessage(),
            readResponse.getHeaders());
    // details
    Preconditions.checkNotNull(jsonFactory);
    TokenErrorResponse details = null;
    String detailString = null;
    String contentType = readResponse.getContentType();
    try {
        if (/* !response.isSuccessStatusCode() && */true
                && contentType != null
                && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
            details = readResponse
                    .getRequest()
                    .getParser()
                    .parseAndClose(new StringReader(responseContent), TokenErrorResponse.class);
            detailString = details.toPrettyString();
        } else {
            detailString = responseContent;
        }
    } catch (IOException exception) {
        // it would be bad to throw an exception while throwing an exception
        exception.printStackTrace();
    }
    // message
    StringBuilder message = HttpResponseException.computeMessageBuffer(readResponse);
    if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    return new LenientTokenResponseException(builder, details);
}
 
Example #6
Source File: TokenResponseException.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link TokenResponseException}.
 *
 * <p>
 * If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be
 * inspected using {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 *
 * @param jsonFactory JSON factory
 * @param response HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) {
  HttpResponseException.Builder builder = new HttpResponseException.Builder(
      response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
  // details
  Preconditions.checkNotNull(jsonFactory);
  TokenErrorResponse details = null;
  String detailString = null;
  String contentType = response.getContentType();
  try {
    if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null
        && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
      details = new JsonObjectParser(jsonFactory).parseAndClose(
          response.getContent(), response.getContentCharset(), TokenErrorResponse.class);
      detailString = details.toPrettyString();
    } else {
      detailString = response.parseAsString();
    }
  } catch (IOException exception) {
    // it would be bad to throw an exception while throwing an exception
    exception.printStackTrace();
  }
  // message
  StringBuilder message = HttpResponseException.computeMessageBuffer(response);
  if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
    message.append(StringUtils.LINE_SEPARATOR).append(detailString);
    builder.setContent(detailString);
  }
  builder.setMessage(message.toString());
  return new TokenResponseException(builder, details);
}
 
Example #7
Source File: TypedNotificationCallback.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public final void onNotification(StoredChannel storedChannel, UnparsedNotification notification)
    throws IOException {
  TypedNotification<T> typedNotification = new TypedNotification<T>(notification);
  // TODO(yanivi): how to properly detect if there is no content?
  String contentType = notification.getContentType();
  if (contentType != null) {
    Charset charset = new HttpMediaType(contentType).getCharsetParameter();
    Class<T> dataClass = Preconditions.checkNotNull(getDataClass());
    typedNotification.setContent(
        getObjectParser().parseAndClose(notification.getContentStream(), charset, dataClass));
  }
  onNotification(storedChannel, typedNotification);
}
 
Example #8
Source File: AtomContent.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param namespaceDictionary XML namespace dictionary
 * @param entry key/value pair data for the Atom entry
 * @param isEntry {@code true} for an Atom entry or {@code false} for an Atom feed
 * @since 1.5
 */
protected AtomContent(XmlNamespaceDictionary namespaceDictionary, Object entry, boolean isEntry) {
  super(namespaceDictionary);
  setMediaType(new HttpMediaType(Atom.MEDIA_TYPE));
  this.entry = Preconditions.checkNotNull(entry);
  this.isEntry = isEntry;
}
 
Example #9
Source File: AtomContent.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public AtomContent setMediaType(HttpMediaType mediaType) {
  super.setMediaType(mediaType);
  return this;
}
 
Example #10
Source File: AbstractXmlHttpContent.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * @param namespaceDictionary XML namespace dictionary
 * @since 1.5
 */
protected AbstractXmlHttpContent(XmlNamespaceDictionary namespaceDictionary) {
  super(new HttpMediaType(Xml.MEDIA_TYPE));
  this.namespaceDictionary = Preconditions.checkNotNull(namespaceDictionary);
}
 
Example #11
Source File: AbstractXmlHttpContent.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public AbstractXmlHttpContent setMediaType(HttpMediaType mediaType) {
  super.setMediaType(mediaType);
  return this;
}
 
Example #12
Source File: JsonHttpContent.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public JsonHttpContent setMediaType(HttpMediaType mediaType) {
  super.setMediaType(mediaType);
  return this;
}
 
Example #13
Source File: XmlHttpContent.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public XmlHttpContent setMediaType(HttpMediaType mediaType) {
  super.setMediaType(mediaType);
  return this;
}
 
Example #14
Source File: AtomPatchRelativeToOriginalContent.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public AtomPatchRelativeToOriginalContent setMediaType(HttpMediaType mediaType) {
  super.setMediaType(mediaType);
  return this;
}
 
Example #15
Source File: AtomPatchContent.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public AtomPatchContent setMediaType(HttpMediaType mediaType) {
  super.setMediaType(mediaType);
  return this;
}
 
Example #16
Source File: ProtoHttpContent.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public ProtoHttpContent setMediaType(HttpMediaType mediaType) {
  return (ProtoHttpContent) super.setMediaType(mediaType);
}
 
Example #17
Source File: JdcloudHttpResponse.java    From jdcloud-sdk-java with Apache License 2.0 4 votes vote down vote up
public void setMediaType(HttpMediaType mediaType) {
    MediaType = mediaType;
}
 
Example #18
Source File: MultipartFormDataContent.java    From Broadsheet.ie-Android with MIT License 4 votes vote down vote up
public MultipartFormDataContent() {
    super(new HttpMediaType("multipart/form-data").setParameter("boundary", "__END_OF_PART__"));
}
 
Example #19
Source File: MultipartFormDataContent.java    From Broadsheet.ie-Android with MIT License 4 votes vote down vote up
@Override
public MultipartFormDataContent setMediaType(HttpMediaType mediaType) {
    super.setMediaType(mediaType);
    return this;
}
 
Example #20
Source File: JdcloudHttpResponse.java    From jdcloud-sdk-java with Apache License 2.0 4 votes vote down vote up
public HttpMediaType getMediaType() {
    return MediaType;
}
 
Example #21
Source File: AtomPatchContent.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * @param namespaceDictionary XML namespace dictionary
 * @param patchEntry key/value pair data for the Atom PATCH entry
 * @since 1.5
 */
public AtomPatchContent(XmlNamespaceDictionary namespaceDictionary, Object patchEntry) {
  super(namespaceDictionary, patchEntry, true);
  setMediaType(new HttpMediaType(Xml.MEDIA_TYPE));
}