...
Codeblock |
---|
language | java |
---|
title | Beispiel |
---|
|
package example.rest;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Providerws.rs.GET;
import javax.ws.rs.GETPath;
import javax.ws.rs.PathProduces;
import javaxorg.nuclos.wsapi.rsrule.ProducesCustomRestRule;
@Path("example")
public class CustomRestWithPathTestRule implements CustomRestRule {
@GET
@Path("customers")
@Produces("application/json")
public List<Customer> customers() {
return Arrays.asList(
new Customer(1, "Mustermann"),
new Customer(2, "Maier")
);
}
public static class Customer {
private int id;
private String name;
public Customer(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
} |
...
Codeblock |
---|
|
@Inject
protected Provider<CustomRestContext> context;
// Dazu müssen noch zweidrei weitere Klassen importiert werden:
import javax.inject.Inject;
import javax.inject.Provider;
import org.nuclos.api.context.CustomRestContext; |
Behandlung von Exception und Custom Responses, jegliche Exceptions die in der Methode nicht mit einem try/catch-Block behandelt wird, wird vom Container-Service (Tomcat/Glassfish) als 500-Fehler gemeldet.
Um dieses Verhalten anzupassen ist es notwendig die Exceptions mittels try/catch zu behandeln und korrekte eigene Responses zu liefern, als Beispiel:
Codeblock |
---|
language | java |
---|
title | Behandlung von BusinessException |
---|
|
package example.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.nuclos.api.rule.CustomRestRule;
import org.nuclos.api.context.CustomRestContext;.exception.BusinessException;
@Path("Test")
@Rule(name="HandleException", description="Demonstrates how to handle exception in CustomRest")
public class HandleException implements CustomRestRule {
@GET
@Path("response/{parameter}")
@Produces("application/json")
public Response parameterTest(@PathParam("parameter") String parameter) {
try {
if( this.functionToThrowException(parameter) ) {
return Response.status(Response.Status.FORBIDDEN).entity(new Message("Dieser User hat keine Berechtigung für das Ausführen der Regel.")).build();
}
} catch (BusinessException e) {
// may also log error
return Response.status(Response.Status.BAD_REQUEST).entity(new Message(e.getMessage())).build();
}
return Response.status(Response.Status.NO_CONTENT).build();
}
private boolean functionToThrowException(String parameter) throws BusinessException {
if (parameter == null) {
throw BusinessException("No parameter given");
}
return "failure".equals(parameter);
}
// Any DTO class for response, will be JSON converted
public static class Message {
String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
} |