retrofit.mime.TypedInput Java Examples

The following examples show how to use retrofit.mime.TypedInput. 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: SignalFxConverter.java    From kayenta with Apache License 2.0 6 votes vote down vote up
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {

  if (!CONVERTIBLE_TYPES.contains(type)) {
    throw new ConversionException(
        String.format(
            "The SignalFxConverter Retrofit converter can only handle Types: [ %s ], received: %s",
            CONVERTIBLE_TYPES.stream().map(Type::getTypeName).collect(Collectors.joining(", ")),
            type.getTypeName()));
  }

  if (type.getTypeName().equals(SignalFlowExecutionResult.class.getTypeName())) {
    return getSignalFlowExecutionResultFromBody(body);
  } else {
    return getErrorResponseFromBody(body);
  }
}
 
Example #2
Source File: Response.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
public Response(int status, String reason, List<Header> headers, TypedInput body) {
    if (status < 200) {
        throw new IllegalArgumentException("Invalid status code: " + status);
    }
    if (reason == null) {
        throw new IllegalArgumentException("reason == null");
    }
    if (headers == null) {
        throw new IllegalArgumentException("headers == null");
    }

    this.status = status;
    this.reason = reason;
    this.headers = Collections.unmodifiableList(new ArrayList<Header>(headers));
    this.body = body;
}
 
Example #3
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void responseNoContentType() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200).message("OK")
      .body(new TestResponseBody("hello", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  TypedInput responseBody = response.getBody();
  assertThat(responseBody.mimeType()).isNull();
  assertThat(buffer(source(responseBody.in())).readUtf8()).isEqualTo("hello");
}
 
Example #4
Source File: Ok3Client.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
private static TypedInput createResponseBody(final ResponseBody body) {
  if (body.contentLength() == 0) {
    return null;
  }
  return new TypedInput() {
    @Override public String mimeType() {
      MediaType mediaType = body.contentType();
      return mediaType == null ? null : mediaType.toString();
    }

    @Override public long length() {
      return body.contentLength();
    }

    @Override public InputStream in() throws IOException {
      return body.byteStream();
    }
  };
}
 
Example #5
Source File: WebViewFragment.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static String readInputStream(TypedInput in) {
    StringBuilder builder = new StringBuilder();
    try {
        BufferedReader bufferedStream
                = new BufferedReader(new InputStreamReader(in.in()));
        try {
            String line;
            while ((line = bufferedStream.readLine()) != null) {
                builder.append(line);
                builder.append('\n');
            }
            return builder.toString();
        } finally {
            bufferedStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}
 
Example #6
Source File: UrlConnectionClient.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
Response readResponse(HttpURLConnection connection) throws IOException {
    int status = connection.getResponseCode();
    String reason = connection.getResponseMessage();

    List<Header> headers = new ArrayList<Header>();
    for (Map.Entry<String, List<String>> field : connection.getHeaderFields().entrySet()) {
        String name = field.getKey();
        for (String value : field.getValue()) {
            headers.add(new Header(name, value));
        }
    }

    String mimeType = connection.getContentType();
    int length = connection.getContentLength();
    InputStream stream;
    if (status >= 400) {
        stream = connection.getErrorStream();
    } else {
        stream = connection.getInputStream();
    }
    TypedInput responseBody = new TypedInputStream(mimeType, length, stream);
    return new Response(status, reason, headers, responseBody);
}
 
Example #7
Source File: GoogleAnalytics.java    From foam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
    String text = null;
    try {
        typedInput.in();
        BufferedReader reader = new BufferedReader(new InputStreamReader(typedInput.in()));
        StringBuilder out = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
            out.append(newLine);
        }
        text = out.toString();
    } catch (IOException ignored) {/*NOP*/ }
    return text;
}
 
Example #8
Source File: GoogleCloudBuildArtifactExtractor.java    From echo with Apache License 2.0 6 votes vote down vote up
@Override
public List<Artifact> getArtifacts(String messagePayload) {
  TypedInput build =
      new TypedByteArray("application/json", messagePayload.getBytes(StandardCharsets.UTF_8));
  try {
    return retrySupport.retry(
        () ->
            AuthenticatedRequest.allowAnonymous(
                () -> igorService.extractGoogleCloudBuildArtifacts(account, build)),
        5,
        2000,
        false);
  } catch (Exception e) {
    log.error("Failed to fetch artifacts for build: {}", e);
    return Collections.emptyList();
  }
}
 
Example #9
Source File: LoganSquareConvertor.java    From hacker-news-android with Apache License 2.0 6 votes vote down vote up
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
    try {
        // Check if the type contains a parametrized list
        if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
            // Grab the actual type parameter from the parametrized list and delegate to LoganSquare
            ParameterizedType parameterized = (ParameterizedType) type;
            return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]);

        } else {
            // Single elements get parsed immediately
            return LoganSquare.parse(body.in(), (Class) type);
        }
    } catch (Exception e) {
        throw new ConversionException(e);
    }
}
 
Example #10
Source File: JacksonConverter.java    From android-skeleton-project with MIT License 6 votes vote down vote up
@Override
public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
    JavaType javaType = objectMapper.getTypeFactory().constructType(type);

    try {
        InputStream in = typedInput.in();
        try {
            return objectMapper.readValue(in, javaType);
        } finally {
             if (in != null) {
                 in.close();
             }
        }


    } catch (IOException e) {
        throw new ConversionException(e);
    }
}
 
Example #11
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void responseNoContentType() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200).message("OK")
      .body(new TestResponseBody("hello", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  TypedInput responseBody = response.getBody();
  assertThat(responseBody.mimeType()).isNull();
  assertThat(buffer(source(responseBody.in())).readUtf8()).isEqualTo("hello");
}
 
Example #12
Source File: Ok3Client.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
private static TypedInput createResponseBody(final ResponseBody body) {
  if (body.contentLength() == 0) {
    return null;
  }
  return new TypedInput() {
    @Override public String mimeType() {
      MediaType mediaType = body.contentType();
      return mediaType == null ? null : mediaType.toString();
    }

    @Override public long length() {
      return body.contentLength();
    }

    @Override public InputStream in() throws IOException {
      return body.byteStream();
    }
  };
}
 
Example #13
Source File: GsonResponse.java    From divide with Apache License 2.0 6 votes vote down vote up
public Response build(){
    return new Response(url,status,reason,new ArrayList<Header>(),new TypedInput() {
        @Override
        public String mimeType() {
            return null;
        }

        @Override
        public long length() {
            return length;
        }

        @Override
        public InputStream in() throws IOException {
            return is;
        }
    });
}
 
Example #14
Source File: ConfigBinResponseConverter.java    From kayenta with Apache License 2.0 6 votes vote down vote up
@Override
public String fromBody(TypedInput body, Type type) throws ConversionException {
  try {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[1024];
    InputStream inputStream = body.in();
    while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, nRead);
    }
    buffer.flush();
    byte[] byteArray = buffer.toByteArray();
    return new String(byteArray, StandardCharsets.UTF_8);
  } catch (IOException e) {
    log.error("Unable to read response body or convert it to a UTF-8 string", e);
    return null;
  }
}
 
Example #15
Source File: TokenConverter.java    From wear-notify-for-reddit with Apache License 2.0 6 votes vote down vote up
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    if (type != Token.class) {
        return mOriginalConverter.fromBody(body, type);
    }

    // We don't check for null refresh token, it's optional - it's retrieved on initial auth but not on a token refresh
    TokenResponse response = (TokenResponse) mOriginalConverter.fromBody(body,
            TokenResponse.class);
    if (response == null || response.getAccessToken() == null) {
        throw new ConversionException("Empty/missing token response: " + response);
    }
    return new Token.Builder().accessToken(response.getAccessToken())
            .refreshToken(response.getRefreshToken())
            .expiryTimeMillis(DateTime.now(DateTimeZone.UTC)
                    .plusSeconds(response.getExpiresIn())
                    .getMillis())
            .build();
}
 
Example #16
Source File: MarkAsReadConverter.java    From wear-notify-for-reddit with Apache License 2.0 6 votes vote down vote up
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    try {
        Scanner s = new Scanner(body.in()).useDelimiter("\\A");
        String bodyText = s.hasNext() ? s.next() : "";

        boolean isSuccessResponse = bodyText.startsWith("202 Accepted");

        MarkAllRead markAllRead = new MarkAllRead();
        if (!isSuccessResponse) {
            markAllRead.setErrors(bodyText);
        }

        return markAllRead;
    } catch (IOException e) {
        throw new ConversionException(e);
    }
}
 
Example #17
Source File: CommentsConverterTest.java    From wear-notify-for-reddit with Apache License 2.0 6 votes vote down vote up
private List<Comment> convertComments(String filename) throws IOException, ConversionException {
    final TypedInput body = mock(TypedInput.class);
    when(body.in()).thenReturn(TestUtils.loadFileFromStream(filename));

    final CommentsConverter commentsConverter = new CommentsConverter(mGson,
            mGsonConverter,
            mResources,
            mUserStorage);
    final List<Comment> comments = (List<Comment>) commentsConverter.fromBody(body,
            new ParameterizedType() {
                @Override public Type[] getActualTypeArguments() {
                    return new Type[]{Comment.class};
                }

                @Override public Type getOwnerType() {
                    return null;
                }

                @Override public Type getRawType() {
                    return List.class;
                }
            });

    return comments;
}
 
Example #18
Source File: PostConverterTest.java    From wear-notify-for-reddit with Apache License 2.0 6 votes vote down vote up
private Post convertPostResponse(String filename) throws IOException, ConversionException {
    final TypedInput body = mock(TypedInput.class);
    when(body.in()).thenReturn(TestUtils.loadFileFromStream(filename));

    final PostConverter postConverter = new PostConverter(mGsonConverter,
            mResources,
            mUserStorage,
            mHtmlDecoder);
    final List<Post> posts = (List<Post>) postConverter.fromBody(body, new ParameterizedType() {
        @Override public Type[] getActualTypeArguments() {
            return new Type[]{Post.class};
        }

        @Override public Type getOwnerType() {
            return null;
        }

        @Override public Type getRawType() {
            return List.class;
        }
    });

    assertThat(posts.size(), equalTo(1));
    return posts.get(0);
}
 
Example #19
Source File: SignalFxConverter.java    From kayenta with Apache License 2.0 6 votes vote down vote up
private SignalFlowExecutionResult getSignalFlowExecutionResultFromBody(TypedInput body)
    throws ConversionException {
  List<ChannelMessage> messages = new LinkedList<>();
  try (ServerSentEventsTransport.TransportEventStreamParser parser =
      new ServerSentEventsTransport.TransportEventStreamParser(body.in())) {

    while (parser.hasNext()) {
      StreamMessage streamMessage = parser.next();
      ChannelMessage channelMessage = ChannelMessage.decodeStreamMessage(streamMessage);
      messages.add(channelMessage);
    }
  } catch (Exception e) {
    throw new ConversionException("There was an issue parsing the SignalFlow response", e);
  }
  return new SignalFlowExecutionResult(messages);
}
 
Example #20
Source File: CommentsConverter.java    From wear-notify-for-reddit with Apache License 2.0 5 votes vote down vote up
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    List<ListingResponse> responses = (List<ListingResponse>) mOriginalConverter.fromBody(body,
            new TypeToken<List<ListingResponse>>() {
            }.getType());

    // First child is always the post itself, second is all the comments
    final ListingResponse listingResponse = responses.get(1);
    return convert(listingResponse, 0);
}
 
Example #21
Source File: DelegatingConverter.java    From wear-notify-for-reddit with Apache License 2.0 5 votes vote down vote up
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    if (type == Token.class) {
        return mTokenConverter.fromBody(body, type);
    } else if (type == MarkAllRead.class) {
        return mMarkAsReadConverter.fromBody(body, type);
    } else if (type == SubscriptionResponse.class) {
        return mSubscriptionConverter.fromBody(body, type);
    } else if (isListOfDesiredType(type, Post.class)) {
        return mPostConverter.fromBody(body, type);
    } else if (isListOfDesiredType(type, Comment.class)) {
        return mCommentsConverter.fromBody(body, type);
    }

    return mOriginalConverter.fromBody(body, type);
}
 
Example #22
Source File: SignalFxConverter.java    From kayenta with Apache License 2.0 5 votes vote down vote up
private ErrorResponse getErrorResponseFromBody(TypedInput body) throws ConversionException {
  try {
    return objectMapper.readValue(body.in(), ErrorResponse.class);
  } catch (Exception e) {
    throw new ConversionException("Failed to parse error response", e);
  }
}
 
Example #23
Source File: RetrofitError.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * HTTP response body converted to specified {@code type}.
 */
public Object getBodyAs(Type type) {
    TypedInput body = response.getBody();
    if (body == null) {
        return null;
    }
    try {
        return converter.fromBody(body, type);
    } catch (ConversionException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: RetrofitError.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * HTTP response body converted to the type declared by either the interface method return type or
 * the generic type of the supplied {@link Callback} parameter.
 */
public Object getBody() {
    TypedInput body = response.getBody();
    if (body == null) {
        return null;
    }
    try {
        return converter.fromBody(body, successType);
    } catch (ConversionException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: TeamFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void checkFollowingRes(Response res) {
    stopMenuLoading();
    if (res.getStatus() == 204) {
        swapFollowStatus();
    }
    TypedInput body = res.getBody();
}
 
Example #26
Source File: SignalFxRemoteServiceTest.java    From kayenta with Apache License 2.0 5 votes vote down vote up
@Test
public void test_that_a_signalfx_signal_flow_response_can_be_parsed() throws Exception {
  InputStream response =
      getClass().getClassLoader().getResourceAsStream("signalfx-signalflow-response.text");
  SignalFxConverter converter = new SignalFxConverter();
  TypedInput typedInput = new TypedByteArray("text/plain", ByteStreams.toByteArray(response));
  SignalFlowExecutionResult signalFlowExecutionResult =
      (SignalFlowExecutionResult) converter.fromBody(typedInput, SignalFlowExecutionResult.class);

  assertNotNull(signalFlowExecutionResult);
  assertThat(
      "The signalFlowExecutionResult contains the channel messages",
      signalFlowExecutionResult.getChannelMessages().size(),
      greaterThan(1));
}
 
Example #27
Source File: InfluxDbResponseConverterTest.java    From kayenta with Apache License 2.0 5 votes vote down vote up
@Test
public void deserialize() throws Exception {
  TypedInput input = new TypedByteArray(MIME_TYPE, JSON.getBytes());
  List<InfluxDbResult> result =
      (List<InfluxDbResult>) influxDbResponseConverter.fromBody(input, List.class);
  assertThat(result, is(results));
}
 
Example #28
Source File: AtlasSSEConverter.java    From kayenta with Apache License 2.0 5 votes vote down vote up
@Override
public List<AtlasResults> fromBody(TypedInput body, Type type) throws ConversionException {
  try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
    return processInput(reader);
  } catch (IOException e) {
    log.error("Cannot process Atlas results", e);
  }
  return null;
}
 
Example #29
Source File: UserFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void checkFollowingRes(Response res) {
    stopMenuLoading();
    if (res.getStatus() == 204) {
        swapFollowStatus();
    }
    TypedInput body = res.getBody();
}
 
Example #30
Source File: RetrofitCurlClient.java    From libcurldroid with Artistic License 2.0 5 votes vote down vote up
private Response convertResult(Request request, Result result) throws IOException {
	Map<String, String> headerMap = result.getHeaders();
	TypedInput input = new TypedByteArray(headerMap.get("Content-Type"), result.getDecodedBody());
	List<Header> headers = new ArrayList<Header>(headerMap.size());
	for (Entry<String, String> entry : headerMap.entrySet()) {
		headers.add(new Header(entry.getKey(), entry.getValue()));
	}
	return new Response(request.getUrl(), result.getStatus(), result.getStatusLine(), headers, input);
}