I would like to call my Webservice with this pattern :
/resource/1,2,3
And in my Class I want to bind my parameters to a List of Object
@Path("/resource")
public class AppWS {
@GET
@Path("/{params}")
public Response get(@PathParam("params") List<MyObject> params) {
return Response.status(200).entity("output").build();
}
}
With a simple Object:
public class MyObject {
Integer value;
public MyObject(Integer value) {
this.value = value;
}
}
nb: If it possible I don't want to create an MyObjectList which extends List (and have a constructor which split my string)
How may I proceed ?
I'm not sure the way of 1,2,3
.
If you insist,
private Response get(List<MyObject> params) {
}
@GET
@Path("/{params}")
public Response get(@PathParam("params") String params) {
return get(Stream.of(params.split(","))
.map(MyObject::new)
.collect(Collectors.toList()));
}
If you really insist,
annotation,
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface MyObjectsParam {
}
converter,
public class MyObjectsParamDateConverter
implements ParamConverter<List<MyObject>> {
@Override
public List<MyObject> fromString(final String value) {
return Stream.of(params.split(","))
.map(MyObject::new)
.collect(Collectors.toList())
}
@Override
public String toString(final List<MyObject> value) {
return value.stream()
.map(o -> o.getValue())
.map(Object::toString)
.collect(Collectors.joining(","));
}
}
provider,
@Provider
public class MyObjectsParamConverterProvider
implements ParamConverterProvider {
@Override
@SuppressWarnings("unchecked")
default ParamConverter getConverter(final Class<S> rawType,
final Type genericType,
final Annotation[] annotations) {
for (final Annotation annotation : annotations) {
if (MyObjectsParam.class.isInstance(annotation)) {
return new MyObjectsParamDateConverter();
}
}
return null;
}
}
Now you can use it like this.
@GET
@Path("/{params}") // still '1,2,3'
public Response get(
@PathParam("params")
@MyObjectsParam // IN ACTION!!!
List<MyObject> params) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With