Java Code Examples for retrofit.mime.TypedString

The following examples show how to use retrofit.mime.TypedString. These examples are extracted from open source projects. 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 Project: apiman-cli   Source File: ApiDefinitionCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void performFinalAction(JCommander parser) throws CommandException {
    if (!definitionStdIn && null == definitionFile) {
        throw new ExitWithCodeException(1, "API definition must be provided", true);
    }

    // read definition from STDIN or file
    String definition;
    try (InputStream is = (definitionStdIn ? System.in : Files.newInputStream(definitionFile))) {
        definition = CharStreams.toString(new InputStreamReader(is));

    } catch (IOException e) {
        throw new CommandException(e);
    }

    LOGGER.debug("Adding definition to API '{}' with contents: {}", this::getModelName, () -> definition);

    ManagementApiUtil.invokeAndCheckResponse(() ->
            getManagerConfig().buildServerApiClient(VersionAgnosticApi.class, serverVersion).setDefinition(orgName, name, version, definitionType, new TypedString(definition)));
}
 
Example 2
Source Project: apiman-cli   Source File: ManagementApiUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeAndCheckResponse_StatusMismatch() throws Exception {
    // test data
    response = new Response(URL, HttpURLConnection.HTTP_NOT_FOUND, "Not Found",
            newArrayList(), new TypedString(""));

    // mock behaviour
    when(request.get()).thenReturn(response);

    // test
    try {
        ManagementApiUtil.invokeAndCheckResponse(HttpURLConnection.HTTP_OK, request);
        fail(CommandException.class + " expected");

    } catch (CommandException ignored) {
        // verify behaviour
        verify(request).get();
    }
}
 
Example 3
Source Project: apiman-cli   Source File: ManagementApiUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeAndCheckResponse_RetrofitError() throws Exception {
    // test data
    response = new Response(URL, HttpURLConnection.HTTP_NOT_FOUND, "Not Found",
            newArrayList(), new TypedString(""));

    // mock behaviour
    when(request.get()).thenThrow(RetrofitError.httpError(URL, response, null, null));

    // test
    try {
        ManagementApiUtil.invokeAndCheckResponse(HttpURLConnection.HTTP_OK, request);
        fail(CommandException.class + " expected");

    } catch (CommandException ignored) {
        // verify behaviour
        verify(request).get();
    }
}
 
Example 4
Source Project: retrofit1-okhttp3-client   Source File: Ok3ClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void post() throws IOException {
  TypedString body = new TypedString("hi");
  Request request = new Request("POST", HOST + "/foo/bar/", null, body);
  okhttp3.Request okRequest = Ok3Client.createRequest(request);

  assertThat(okRequest.method()).isEqualTo("POST");
  assertThat(okRequest.url().toString()).isEqualTo(HOST + "/foo/bar/");
  assertThat(okRequest.headers().size()).isEqualTo(0);

  RequestBody okBody = okRequest.body();
  assertThat(okBody).isNotNull();

  Buffer buffer = new Buffer();
  okBody.writeTo(buffer);
  assertThat(buffer.readUtf8()).isEqualTo("hi");
}
 
Example 5
@Test public void post() throws IOException, InterruptedException {
  server.enqueue(new MockResponse()
      .addHeader("Hello", "World")
      .setBody("Hello!"));

  Response response = service.post(new TypedString("Hello?"));
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getUrl()).isEqualTo(server.url("/").toString());
  assertThat(response.getHeaders()).contains(new Header("Hello", "World"));
  assertThat(buffer(source(response.getBody().in())).readUtf8()).isEqualTo("Hello!");

  RecordedRequest request = server.takeRequest();
  assertThat(request.getMethod()).isEqualTo("POST");
  assertThat(request.getPath()).isEqualTo("/");
  assertThat(request.getBody().readUtf8()).isEqualTo("Hello?");
}
 
Example 6
public void putInterpretationComment(InterpretationComment comment) throws APIException {
    Interpretation interpretation = comment.getInterpretation();

    if (interpretation != null && interpretation.getState() != null) {
        boolean isInterpretationSynced = (interpretation.getState().equals(State.SYNCED) ||
                interpretation.getState().equals(State.TO_UPDATE));

        if (!isInterpretationSynced) {
            return;
        }

        try {
            mDhisApi.putInterpretationComment(interpretation.getUId(),
                    comment.getUId(), new TypedString(comment.getText()));

            comment.setState(State.SYNCED);
            comment.save();

            updateInterpretationTimeStamp(comment.getInterpretation());
        } catch (APIException apiException) {
            handleApiException(apiException);
        }
    }
}
 
Example 7
Source Project: retrofit1-okhttp3-client   Source File: Ok3ClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void post() throws IOException {
  TypedString body = new TypedString("hi");
  Request request = new Request("POST", HOST + "/foo/bar/", null, body);
  okhttp3.Request okRequest = Ok3Client.createRequest(request);

  assertThat(okRequest.method()).isEqualTo("POST");
  assertThat(okRequest.url().toString()).isEqualTo(HOST + "/foo/bar/");
  assertThat(okRequest.headers().size()).isEqualTo(0);

  RequestBody okBody = okRequest.body();
  assertThat(okBody).isNotNull();

  Buffer buffer = new Buffer();
  okBody.writeTo(buffer);
  assertThat(buffer.readUtf8()).isEqualTo("hi");
}
 
Example 8
@Test public void post() throws IOException, InterruptedException {
  server.enqueue(new MockResponse()
      .addHeader("Hello", "World")
      .setBody("Hello!"));

  Response response = service.post(new TypedString("Hello?"));
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getUrl()).isEqualTo(server.url("/").toString());
  assertThat(response.getHeaders()).contains(new Header("Hello", "World"));
  assertThat(buffer(source(response.getBody().in())).readUtf8()).isEqualTo("Hello!");

  RecordedRequest request = server.takeRequest();
  assertThat(request.getMethod()).isEqualTo("POST");
  assertThat(request.getPath()).isEqualTo("/");
  assertThat(request.getBody().readUtf8()).isEqualTo("Hello?");
}
 
Example 9
Source Project: hacker-news-android   Source File: LoganSquareConvertor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
    try {
        // Check if the type contains a parametrized list
        if (List.class.isAssignableFrom(object.getClass())) {
            // Convert the input to a list first, access the first element and serialize the list
            List<Object> list = (List<Object>) object;
            if (list.isEmpty()) {
                return new TypedString("[]");
            }
            else {
                Object firstElement = list.get(0);
                return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass()));
            }
        }
        else {
            // Serialize single elements immediately
            return new TypedString(LoganSquare.serialize(object));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source Project: apiman-cli   Source File: DeclarativeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds a definition to the API.
 *
 * @param apiClient
 * @param declarativeApi
 * @param orgName
 * @param apiName
 * @param apiVersion
 */
private void applyDefinition(VersionAgnosticApi apiClient, DeclarativeApi declarativeApi, String orgName,
                             String apiName, String apiVersion) {

    ofNullable(declarativeApi.getDefinition()).ifPresent(declarativeApiDefinition -> {
        if (StringUtils.isNotEmpty(declarativeApiDefinition.getFile())
                || StringUtils.isNotEmpty(declarativeApiDefinition.getBody())) {

            LOGGER.debug("Applying definition to API: {}", apiName);
            final String definition;
            if (StringUtils.isNotEmpty(declarativeApiDefinition.getFile())) {
                try (InputStream is = Files.newInputStream(Paths.get(declarativeApiDefinition.getFile()), StandardOpenOption.READ)) {
                    definition = CharStreams.toString(new InputStreamReader(is));
                } catch (IOException e) {
                    LOGGER.error("Failed to apply API definition, invalid file: {}", declarativeApiDefinition.getFile(), e);
                    return;
                }
            } else {
                definition = declarativeApiDefinition.getBody();
            }

            apiClient.setDefinition(orgName, apiName, apiVersion, declarativeApiDefinition.getType(), new TypedString(definition));

            LOGGER.info("Setting definition for API: {}", apiName);
        }
    });
}
 
Example 11
Source Project: apiman-cli   Source File: ManagementApiUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeAndCheckResponse_StatusMatch() throws Exception {
    // test data
    response = new Response(URL, HttpURLConnection.HTTP_OK, "OK",
            newArrayList(), new TypedString("test body"));

    // mock behaviour
    when(request.get()).thenReturn(response);

    // test
    ManagementApiUtil.invokeAndCheckResponse(request);

    // assertions
    verify(request).get();
}
 
Example 12
Source Project: droidddle   Source File: CreateShotFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void createShot() {
    if (mImageFile == null || !mImageFile.exists()) {
        UiUtils.showToast(getActivity(), R.string.shot_image_file_missing);
        return;
    }
    if (mMimeType == null) {
        mMimeType = FileUtils.getMimeType(mImageFile);
    }
    if (!Utils.hasInternet(getActivity())) {
        Toast.makeText(getActivity(), R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    mDialog = UiUtils.showProgressDialog(getActivity(), getString(R.string.creating));
    String text = mNameView.getText().toString();
    String des = mDescriptionView.getText().toString();
    String tag = mTagsView.getText().toString().trim();
    //TODO set image/png GIF, JPG by file ext name
    TypedFile image = new TypedFile(mMimeType, mImageFile);
    TypedString title = new TypedString(text);
    TypedString description = new TypedString(des);
    TypedString tags = new TypedString(tag);
    Observable<Response> observable = ApiFactory.getService(getActivity()).createShot(image, title, description, tags);
    observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe((response) -> {
        bucketCreated(response);
    }, new ErrorCallback(getActivity()));

}
 
Example 13
Source Project: Android-REST-API-Explorer   Source File: PagesService.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new page in a section specified by section title
 *
 * @param version
 * @param name
 * @param content
 * @param callback
 */
@POST("/{version}/me/notes/pages")
void postPagesInSection(
        @Header("Content-type") String contentTypeHeader,
        @Path("version") String version,
        @Query("sectionName") String name,
        @Body TypedString content,
        Callback<Envelope<Page>> callback
);
 
Example 14
public void postInterpretation(Interpretation interpretation) throws APIException {
    try {
        Response response;

        switch (interpretation.getType()) {
            case Interpretation.TYPE_CHART: {
                response = mDhisApi.postChartInterpretation(interpretation.getChart().getUId(),
                        new TypedString(interpretation.getText()));
                break;
            }
            case Interpretation.TYPE_MAP: {
                response = mDhisApi.postMapInterpretation(interpretation.getMap().getUId(),
                        new TypedString(interpretation.getText()));
                break;
            }
            case Interpretation.TYPE_REPORT_TABLE: {
                response = mDhisApi.postReportTableInterpretation(interpretation
                        .getReportTable().getUId(), new TypedString(interpretation.getText()));
                break;
            }
            default:
                throw new IllegalArgumentException("Unsupported interpretation type");
        }

        Header header = findLocationHeader(response.getHeaders());
        String interpretationUid = Uri.parse(header.getValue()).getLastPathSegment();
        interpretation.setUId(interpretationUid);
        interpretation.setState(State.SYNCED);
        interpretation.save();

        updateInterpretationTimeStamp(interpretation);

    } catch (APIException apiException) {
        handleApiException(apiException, interpretation);
    }
}
 
Example 15
public void putInterpretation(Interpretation interpretation) throws APIException {
    try {
        mDhisApi.putInterpretationText(interpretation.getUId(),
                new TypedString(interpretation.getText()));
        interpretation.setState(State.SYNCED);
        interpretation.save();

        updateInterpretationTimeStamp(interpretation);
    } catch (APIException apiException) {
        handleApiException(apiException, interpretation);
    }
}
 
Example 16
public void postInterpretationComment(InterpretationComment comment) throws APIException {
    Interpretation interpretation = comment.getInterpretation();

    if (interpretation != null && interpretation.getState() != null) {
        boolean isInterpretationSynced = (interpretation.getState().equals(State.SYNCED) ||
                interpretation.getState().equals(State.TO_UPDATE));

        if (!isInterpretationSynced) {
            return;
        }

        try {
            Response response = mDhisApi.postInterpretationComment(
                    interpretation.getUId(), new TypedString(comment.getText()));

            Header locationHeader = findLocationHeader(response.getHeaders());
            String commentUid = Uri.parse(locationHeader
                    .getValue()).getLastPathSegment();
            comment.setUId(commentUid);
            comment.setState(State.SYNCED);
            comment.save();

            updateInterpretationCommentTimeStamp(comment);
        } catch (APIException apiException) {
            handleApiException(apiException, comment);
        }
    }
}
 
Example 17
Source Project: kayenta   Source File: SignalFxConverter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
  String string = (String) object;
  return new TypedString(string);
}
 
Example 18
Source Project: apiman-cli   Source File: Version12xServerApi.java    License: Apache License 2.0 4 votes vote down vote up
@PUT("/organizations/{orgName}/apis/{serviceName}/versions/{version}/definition")
Response setDefinition(@Path("orgName") String orgName, @Path("serviceName") String serviceName,
                   @Path("version") String version, @Header("Content-Type") String type, @Body TypedString content);
 
Example 19
Source Project: apiman-cli   Source File: Version11xServerApi.java    License: Apache License 2.0 4 votes vote down vote up
@PUT("/organizations/{orgName}/services/{serviceName}/versions/{version}/definition")
Response setDefinition(@Path("orgName") String orgName, @Path("serviceName") String serviceName,
                       @Path("version") String version, @Header("Content-Type") String type, @Body TypedString content);
 
Example 20
Source Project: apiman-cli   Source File: VersionAgnosticApi.java    License: Apache License 2.0 4 votes vote down vote up
Response setDefinition(String orgName, String apiName,
String version, String definitionType,  TypedString definition);
 
Example 21
Source Project: droidddle   Source File: ApiService.java    License: Apache License 2.0 4 votes vote down vote up
@Multipart
@POST("/shots")
Observable<Response> createShot(@Part("image") TypedFile image, @Part("title") TypedString title, @Part("description") TypedString description);
 
Example 22
Source Project: droidddle   Source File: ApiService.java    License: Apache License 2.0 4 votes vote down vote up
@Multipart
@POST("/shots")
Observable<Response> createShot(@Part("image") TypedFile image, @Part("title") TypedString title, @Part("description") TypedString description, @Part("tags") TypedString tags);
 
Example 23
Source Project: foam   Source File: GoogleAnalytics.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public TypedOutput toBody(Object output) {
    return new TypedString(output.toString());
}
 
Example 24
@Headers("Content-Type: text/plain")
@POST("/interpretations/chart/{uid}")
Response postChartInterpretation(@Path("uid") String elementUid,
                                 @Body TypedString interpretationText);
 
Example 25
@Headers("Content-Type: text/plain")
@POST("/interpretations/map/{uid}")
Response postMapInterpretation(@Path("uid") String elementUid,
                               @Body TypedString interpretationText);
 
Example 26
@Headers("Content-Type: text/plain")
@POST("/interpretations/reportTable/{uid}")
Response postReportTableInterpretation(@Path("uid") String elementUid,
                                       @Body TypedString interpretationText);
 
Example 27
@Headers("Content-Type: text/plain")
@PUT("/interpretations/{uid}")
Response putInterpretationText(@Path("uid") String interpretationUid,
                               @Body TypedString interpretationText);
 
Example 28
@Headers("Content-Type: text/plain")
@POST("/interpretations/{interpretationUid}/comments")
Response postInterpretationComment(@Path("interpretationUid") String interpretationUid,
                                   @Body TypedString commentText);
 
Example 29
@Headers("Content-Type: text/plain")
@PUT("/interpretations/{interpretationUid}/comments/{commentUid}")
Response putInterpretationComment(@Path("interpretationUid") String interpretationUid,
                                  @Path("commentUid") String commentUid,
                                  @Body TypedString commentText);
 
Example 30
Source Project: android-discourse   Source File: RequestBuilder.java    License: Apache License 2.0 4 votes vote down vote up
void setArguments(Object[] args) {
    if (args == null) {
        return;
    }
    int count = args.length;
    if (!isSynchronous) {
        count -= 1;
    }
    for (int i = 0; i < count; i++) {
        String name = paramNames[i];
        Object value = args[i];
        RestMethodInfo.ParamUsage paramUsage = paramUsages[i];
        switch (paramUsage) {
            case PATH:
                if (value == null) {
                    throw new IllegalArgumentException("Path parameter \"" + name + "\" value must not be null.");
                }
                addPathParam(name, value.toString());
                break;
            case ENCODED_PATH:
                if (value == null) {
                    throw new IllegalArgumentException("Path parameter \"" + name + "\" value must not be null.");
                }
                addEncodedPathParam(name, value.toString());
                break;
            case QUERY:
                if (value != null) { // Skip null values.
                    addQueryParam(name, value.toString());
                }
                break;
            case ENCODED_QUERY:
                if (value != null) { // Skip null values.
                    addEncodedQueryParam(name, value.toString());
                }
                break;
            case HEADER:
                if (value != null) { // Skip null values.
                    addHeader(name, value.toString());
                }
                break;
            case FIELD:
                if (value != null) { // Skip null values.
                    formBody.addField(name, value.toString());
                }
                break;
            case PART:
                if (value != null) { // Skip null values.
                    if (value instanceof TypedOutput) {
                        multipartBody.addPart(name, (TypedOutput) value);
                    } else if (value instanceof String) {
                        multipartBody.addPart(name, new TypedString((String) value));
                    } else {
                        multipartBody.addPart(name, converter.toBody(value));
                    }
                }
                break;
            case BODY:
                if (value == null) {
                    throw new IllegalArgumentException("Body parameter value must not be null.");
                }
                if (value instanceof TypedOutput) {
                    body = (TypedOutput) value;
                } else {
                    body = converter.toBody(value);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown parameter usage: " + paramUsage);
        }
    }
}