|
| 1 | +package org.rest.integration; |
| 2 | + |
| 3 | +import static com.jayway.restassured.RestAssured.given; |
| 4 | +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | + |
| 8 | +import org.apache.http.HttpHeaders; |
| 9 | +import org.apache.http.HttpResponse; |
| 10 | +import org.apache.http.client.ClientProtocolException; |
| 11 | +import org.apache.http.client.methods.HttpPost; |
| 12 | +import org.apache.http.impl.client.DefaultHttpClient; |
| 13 | +import org.rest.constants.HttpConstants; |
| 14 | +import org.rest.model.Foo; |
| 15 | +import org.rest.util.common.ExtractUtil; |
| 16 | +import org.rest.util.json.ConvertUtil; |
| 17 | +import org.rest.util.json.DecorateUtil; |
| 18 | +import org.springframework.beans.factory.annotation.Autowired; |
| 19 | +import org.springframework.stereotype.Component; |
| 20 | + |
| 21 | +import com.google.common.base.Preconditions; |
| 22 | + |
| 23 | +/** |
| 24 | + * Template for the consumption of the REST API <br> |
| 25 | + */ |
| 26 | +@Component |
| 27 | +public final class FooRESTTemplateNew{ |
| 28 | + |
| 29 | + @Autowired |
| 30 | + ExamplePaths paths; |
| 31 | + |
| 32 | + public FooRESTTemplateNew(){ |
| 33 | + super(); |
| 34 | + } |
| 35 | + |
| 36 | + // |
| 37 | + public final long createResource() throws ClientProtocolException, IOException{ |
| 38 | + return this.createResource( new Foo( randomAlphabetic( 6 ) ) ); |
| 39 | + } |
| 40 | + public final long createResource( final Foo resource ) throws ClientProtocolException, IOException{ |
| 41 | + Preconditions.checkNotNull( resource ); |
| 42 | + |
| 43 | + final HttpPost request = new HttpPost( this.paths.getFooURL() ); |
| 44 | + DecorateUtil.setResourceOnRequestAsJson( request, resource ); |
| 45 | + |
| 46 | + final HttpResponse response = new DefaultHttpClient().execute( request ); |
| 47 | + |
| 48 | + final long idOfNewResource = ExtractUtil.extractIdFromCreateResponse( response ); |
| 49 | + return idOfNewResource; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * - note: usually, the |
| 54 | + */ |
| 55 | + public final String getResourceAsJson( final long id ){ |
| 56 | + return given().header( HttpHeaders.ACCEPT, HttpConstants.MIME_JSON ).get( this.paths.getFooURL() + "/" + id ).asString(); |
| 57 | + } |
| 58 | + public final < T >T getResourceViaJson( final long id, final Class< T > clazz ) throws ClientProtocolException, IOException{ |
| 59 | + final String resourceAsJson = this.getResourceAsJson( id ); |
| 60 | + return ConvertUtil.convertJsonToResource( resourceAsJson, clazz ); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments