retrofit.converter.ConversionException Java Examples

The following examples show how to use retrofit.converter.ConversionException. 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
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 #2
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 #3
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 #4
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 #5
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 #6
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 #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: 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 #9
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 #10
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 #11
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 #12
Source File: DelegatingConverterTest.java    From wear-notify-for-reddit with Apache License 2.0 5 votes vote down vote up
private void convertResponse(String filename, Type type) throws IOException,
        ConversionException {
    when(mTypedInput.in()).thenReturn(TestUtils.loadFileFromStream(filename));

    new DelegatingConverter(mConverter,
            mTokenConverter,
            mPostConverter,
            mMarkAsReadConverter,
            mSubscriptionConverter,
            mCommentsConverter).fromBody(mTypedInput, type);
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: InfluxDbResponseConverter.java    From kayenta with Apache License 2.0 5 votes vote down vote up
private Map getResultObject(String json)
    throws IOException, JsonParseException, JsonMappingException, ConversionException {
  Map responseMap = kayentaObjectMapper.readValue(json, Map.class);
  List<Map> results = (List<Map>) responseMap.get("results");
  if (CollectionUtils.isEmpty(results)) {
    throw new ConversionException("Unexpected response from influxDb");
  }
  Map result = (Map) results.get(0);
  return result;
}
 
Example #18
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 #19
Source File: RetrofitError.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
public static RetrofitError conversionError(String url, Response response, Converter converter, Type successType, ConversionException exception) {
    return new RetrofitError(url, response, converter, successType, false, exception);
}
 
Example #20
Source File: ApiExceptionTests.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private APIException getConversionExceptionFromRetrofit() {
    return APIException.fromRetrofitError(
            RetrofitError.conversionError("test_message", response, converter,
                    type, new ConversionException("test_message")));
}
 
Example #21
Source File: SubscriptionConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    return new GsonConverter(new GsonBuilder().registerTypeAdapter(SubscriptionResponse.class,
            new SubscriptionResponse.SubscriptionResponseJsonDeserializer()).create()).fromBody(
            body,
            type);
}
 
Example #22
Source File: InfluxDbResponseConverterTest.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Test(expected = ConversionException.class)
public void deserializeWrongValue() throws Exception {
  TypedInput input = new TypedByteArray(MIME_TYPE, "{\"foo\":\"bar\"}".getBytes());
  influxDbResponseConverter.fromBody(input, List.class);
}
 
Example #23
Source File: PostConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    ListingResponse listingResponse = (ListingResponse) mOriginalConverter.fromBody(body,
            ListingResponse.class);
    return new ListingResponseConverter(mUserStorage, mResources, mHtmlDecoder).convert(
            listingResponse);
}
 
Example #24
Source File: InfluxDbResponseConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {

  try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
    String json = reader.readLine();
    log.debug("Converting response from influxDb: {}", json);

    Map result = getResultObject(json);
    List<Map> seriesList = (List<Map>) result.get("series");

    if (CollectionUtils.isEmpty(seriesList)) {
      log.warn("Received no data from Influxdb.");
      return null;
    }

    Map series = seriesList.get(0);
    List<String> seriesColumns = (List<String>) series.get("columns");
    List<List> seriesValues = (List<List>) series.get("values");
    List<InfluxDbResult> influxDbResultsList = new ArrayList<InfluxDbResult>(seriesValues.size());

    // TODO(joerajeev): if returning tags (other than the field names) we will need to skip tags
    // from this loop,
    // and to extract and set the tag values to the influxDb result.
    for (int i = 1;
        i < seriesColumns.size();
        i++) { // Starting from index 1 to skip 'time' column

      String id = seriesColumns.get(i);
      long firstTimeMillis = extractTimeInMillis(seriesValues, 0);
      long stepMillis = calculateStep(seriesValues, firstTimeMillis);
      List<Double> values = new ArrayList<>(seriesValues.size());
      for (List<Object> valueRow : seriesValues) {
        if (valueRow.get(i) != null) {
          values.add(Double.valueOf((Integer) valueRow.get(i)));
        }
      }
      influxDbResultsList.add(new InfluxDbResult(id, firstTimeMillis, stepMillis, null, values));
    }

    log.debug("Converted response: {} ", influxDbResultsList);
    return influxDbResultsList;
  } catch (IOException e) {
    e.printStackTrace();
  }

  return null;
}
 
Example #25
Source File: PrometheusResponseConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
  if (type == PrometheusMetricDescriptorsResponse.class) {
    return new JacksonConverter(kayentaObjectMapper).fromBody(body, type);
  } else {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
      String json = reader.readLine();
      Map responseMap = kayentaObjectMapper.readValue(json, Map.class);
      Map data = (Map) responseMap.get("data");
      List<Map> resultList = (List<Map>) data.get("result");
      List<PrometheusResults> prometheusResultsList =
          new ArrayList<PrometheusResults>(resultList.size());

      if (CollectionUtils.isEmpty(resultList)) {
        log.warn("Received no data from Prometheus.");
        return null;
      }

      for (Map elem : resultList) {
        Map<String, String> tags = (Map<String, String>) elem.get("metric");
        String id = tags.remove("__name__");
        List<List> values = (List<List>) elem.get("values");
        List<Double> dataValues = new ArrayList<Double>(values.size());

        for (List tuple : values) {
          String val = (String) tuple.get(1);
          if (val != null) {
            switch (val) {
              case "+Inf":
                dataValues.add(Double.POSITIVE_INFINITY);
                break;
              case "-Inf":
                dataValues.add(Double.NEGATIVE_INFINITY);
                break;
              case "NaN":
                dataValues.add(Double.NaN);
                break;
              default:
                dataValues.add(Double.valueOf(val));
            }
          }
        }

        long startTimeMillis =
            doubleTimestampSecsToLongTimestampMillis(values.get(0).get(0) + "");
        // If there aren't at least two data points, consider the step size to be zero.
        long stepSecs =
            values.size() > 1
                ? TimeUnit.MILLISECONDS.toSeconds(
                    doubleTimestampSecsToLongTimestampMillis(values.get(1).get(0) + "")
                        - startTimeMillis)
                : 0;
        long endTimeMillis = startTimeMillis + values.size() * stepSecs * 1000;

        prometheusResultsList.add(
            new PrometheusResults(
                id, startTimeMillis, stepSecs, endTimeMillis, tags, dataValues));
      }

      return prometheusResultsList;
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
}