Search in sources :

Example 36 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContextResourceClient method onProcessingError.

public <T> ContextResourceClient onProcessingError(String relation, final ResultHandler<T> handler) {
    final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.map(((ParameterizedType) handler.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0]);
    processingErrorHandlers.put(relation, new ResponseHandler() {

        @Override
        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
            T result = contextResourceFactory.readResponse(response, resultType);
            return handler.handleResult(result, client);
        }
    });
    return this;
}
Also used : ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) NullResponseHandler(org.qi4j.library.rest.client.spi.NullResponseHandler) ResponseHandler(org.qi4j.library.rest.client.spi.ResponseHandler)

Example 37 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContextResourceClient method invokeQuery.

private HandlerCommand invokeQuery(Reference ref, Object queryRequest, ResponseHandler resourceHandler, ResponseHandler processingErrorHandler) {
    Request request = new Request(Method.GET, ref);
    if (queryRequest != null) {
        contextResourceFactory.writeRequest(request, queryRequest);
    }
    contextResourceFactory.updateQueryRequest(request);
    User user = request.getClientInfo().getUser();
    if (user != null)
        request.setChallengeResponse(new ChallengeResponse(ChallengeScheme.HTTP_BASIC, user.getName(), user.getSecret()));
    Response response = new Response(request);
    contextResourceFactory.getClient().handle(request, response);
    if (response.getStatus().isSuccess()) {
        contextResourceFactory.updateCache(response);
        return resourceHandler.handleResponse(response, this);
    } else if (response.getStatus().isRedirection()) {
        Reference redirectedTo = response.getLocationRef();
        return invokeQuery(redirectedTo, queryRequest, resourceHandler, processingErrorHandler);
    } else {
        if (response.getStatus().equals(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY) && processingErrorHandler != null) {
            return processingErrorHandler.handleResponse(response, this);
        } else {
            // TODO This needs to be expanded to allow custom handling of all the various cases
            return errorHandler.handleResponse(response, this);
        }
    }
}
Also used : ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) User(org.restlet.security.User) Reference(org.restlet.data.Reference) Request(org.restlet.Request) ChallengeResponse(org.restlet.data.ChallengeResponse)

Example 38 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContinuousIntegrationTest method testRunBuildProgressive.

@Test
public void testRunBuildProgressive() {
    // START SNIPPET: query-list-and-command-progressive
    crc.onResource(new ResultHandler<Resource>() {

        @Override
        public HandlerCommand handleResult(Resource result, ContextResourceClient client) {
            return query("runbuild").onSuccess(new ResultHandler<Links>() {

                @Override
                public HandlerCommand handleResult(Links result, ContextResourceClient client) {
                    Link link = LinksUtil.withId("any", result);
                    return command(link).onSuccess(new ResponseHandler() {

                        @Override
                        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
                            System.out.println("Done");
                            return null;
                        }
                    });
                }
            });
        }
    });
    crc.start();
// END SNIPPET: query-list-and-command-progressive
}
Also used : HandlerCommand(org.qi4j.library.rest.client.api.HandlerCommand) Response(org.restlet.Response) ResponseHandler(org.qi4j.library.rest.client.spi.ResponseHandler) ContextResource(org.qi4j.library.rest.server.api.ContextResource) Resource(org.qi4j.library.rest.common.Resource) Links(org.qi4j.library.rest.common.link.Links) ResultHandler(org.qi4j.library.rest.client.spi.ResultHandler) ContextResourceClient(org.qi4j.library.rest.client.api.ContextResourceClient) Link(org.qi4j.library.rest.common.link.Link) AbstractQi4jTest(org.qi4j.test.AbstractQi4jTest) Test(org.junit.Test)

Example 39 with Response

use of org.restlet.Response in project qi4j-sdk by Qi4j.

the class ContinuousIntegrationTest method startWebServer.

@Before
public void startWebServer() throws Exception {
    server = new Server(Protocol.HTTP, 8888);
    ContextRestlet restlet = module.newObject(ContextRestlet.class, new org.restlet.Context());
    ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "testRealm");
    MapVerifier mapVerifier = new MapVerifier();
    mapVerifier.getLocalSecrets().put("rickard", "secret".toCharArray());
    guard.setVerifier(mapVerifier);
    guard.setNext(restlet);
    server.setNext(guard);
    server.start();
    // START SNIPPET: client-create1
    Client client = new Client(Protocol.HTTP);
    ContextResourceClientFactory contextResourceClientFactory = module.newObject(ContextResourceClientFactory.class, client);
    contextResourceClientFactory.setAcceptedMediaTypes(MediaType.APPLICATION_JSON);
    // END SNIPPET: client-create1
    // START SNIPPET: client-create2
    contextResourceClientFactory.setErrorHandler(new ErrorHandler().onError(ErrorHandler.AUTHENTICATION_REQUIRED, new ResponseHandler() {

        boolean tried = false;

        @Override
        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
            if (tried) {
                throw new ResourceException(response.getStatus());
            }
            tried = true;
            client.getContextResourceClientFactory().getInfo().setUser(new User("rickard", "secret"));
            // Try again
            return refresh();
        }
    }).onError(ErrorHandler.RECOVERABLE_ERROR, new ResponseHandler() {

        @Override
        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
            // Try to restart
            return refresh();
        }
    }));
    // END SNIPPET: client-create2
    // START SNIPPET: client-create3
    Reference ref = new Reference("http://localhost:8888/");
    crc = contextResourceClientFactory.newClient(ref);
// END SNIPPET: client-create3
}
Also used : ErrorHandler(org.qi4j.library.rest.client.api.ErrorHandler) ContextResourceClientFactory(org.qi4j.library.rest.client.api.ContextResourceClientFactory) User(org.restlet.security.User) Server(org.restlet.Server) ResponseHandler(org.qi4j.library.rest.client.spi.ResponseHandler) Reference(org.restlet.data.Reference) Response(org.restlet.Response) HandlerCommand(org.qi4j.library.rest.client.api.HandlerCommand) ContextRestlet(org.qi4j.library.rest.server.api.ContextRestlet) ChallengeAuthenticator(org.restlet.security.ChallengeAuthenticator) MapVerifier(org.restlet.security.MapVerifier) ResourceException(org.restlet.resource.ResourceException) ContextResourceClient(org.qi4j.library.rest.client.api.ContextResourceClient) Client(org.restlet.Client) ContextResourceClient(org.qi4j.library.rest.client.api.ContextResourceClient) Before(org.junit.Before)

Example 40 with Response

use of org.restlet.Response in project vcell by virtualcell.

the class VCellApiApplication method createInboundRoot.

@Override
public Restlet createInboundRoot() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    /**
     * curl --insecure
     * "https://nrcamdev5.cam.uchc.edu:8080/access_token?user_id=schaff&user_password=056F4508E0DE1ED22D4D6F541E91460694A00E16&client_id=85133f8d-26f7-4247-8356-d175399fc2e6"
     *
     * {"token":"9002b7ba-004f-40aa-a639-9136364850a6","creationDateSeconds"
     * :1376586968,"expireDateSeconds":1376673368,"userId":"schaff",
     * "userKey":"17"}
     *
     * curl --verbose --insecure -H
     * "Authorization: CUSTOM access_token=9002b7ba-004f-40aa-a639-9136364850a6"
     * https://nrcamdev5.cam.uchc.edu:8080/simtask?running=on
     *
     * [{"simKey":"83642386","simName":"Simulation5","userName":"schaff",
     * "userKey"
     * :"17","htcJobId":"SGE:283488","status":"running","startdate":
     * 1375408007000
     * ,"jobIndex":0,"taskId":0,"message":"0.7202440000182919","site"
     * :"REL","computeHost"
     * :"compute-2-0.local","schedulerStatus":"running","hasData"
     * :true,"scanCount"
     * :1,"bioModelLink":{"bioModelKey":"83642503","bioModelBranchId"
     * :"83640470"
     * ,"bioModelName":"CSHL 2011 Exercise 6_Jim_2013","simContextKey"
     * :"83642357","simContextBranchId":"83642358","simContextName":
     * "smoldyn_repressor_activator_oscillations"
     * }},{"simKey":"38442198","simName"
     * :"Simulation0","userName":"schaff","userKey"
     * :"17","status":"running","startdate"
     * :1264828384000,"jobIndex":0,"taskId"
     * :0,"message":"processing geometry..."
     * ,"site":"SCHAFF_WSAD","computeHost"
     * :"\u003c\u003clocal\u003e\u003e","schedulerStatus"
     * :"running","hasData"
     * :false,"scanCount":1,"mathModelLink":{"mathModelKey"
     * :"38442201","mathModelBranchId"
     * :"38442202","mathModelName":"tempMath77"}}]
     */
    // Attach a guard to secure access to user parts of the api
    boolean bCookieOptional = true;
    final VCellCookieAuthenticator cookieAuthenticator = new VCellCookieAuthenticator(this, bCookieOptional, "My cookie realm", "MyExtraSecretKey".getBytes());
    cookieAuthenticator.setLoginPath("/" + LOGIN);
    cookieAuthenticator.setLogoutPath("/" + LOGOUT);
    cookieAuthenticator.setCookieName("org.vcell.auth");
    cookieAuthenticator.setLoginFormPath("/" + LOGINFORM);
    cookieAuthenticator.setIdentifierFormName(IDENTIFIER_FORMNAME);
    cookieAuthenticator.setSecretFormName(SECRET_FORMNAME);
    cookieAuthenticator.setRedirectQueryName(REDIRECTURL_FORMNAME);
    cookieAuthenticator.setVerifier(userVerifier);
    // 15 minutes (in units of seconds).
    cookieAuthenticator.setMaxCookieAge(15 * 60);
    String ROOT_URI = javascriptDir.toURI().toString();
    String WEBAPP_URI = new File(javascriptDir.getParentFile(), "webapp").toURI().toString();
    System.out.println("using uri=" + ROOT_URI + " for scripts directory");
    String SCRIPTS = "scripts";
    Router rootRouter = new Router(getContext());
    rootRouter.attach("/" + SCRIPTS, new Directory(getContext(), ROOT_URI));
    rootRouter.attach("/" + ACCESSTOKENRESOURCE, new AuthenticationTokenRestlet(getContext()));
    rootRouter.attach("/" + WEBAPP, new Directory(getContext(), WEBAPP_URI));
    rootRouter.attach("/" + OPTIMIZATION, OptimizationRunServerResource.class);
    rootRouter.attach("/" + OPTIMIZATION + "/{" + OPTIMIZATIONID + "}", OptimizationRunServerResource.class);
    rootRouter.attach("/" + PUBLICATION, PublicationsServerResource.class);
    rootRouter.attach("/" + PUBLICATION + "/{" + PUBLICATIONID + "}", PublicationServerResource.class);
    rootRouter.attach("/" + BIOMODEL, BiomodelsServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}", BiomodelServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + VCML_DOWNLOAD, BiomodelVCMLServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + SBML_DOWNLOAD, BiomodelSBMLServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + BNGL_DOWNLOAD, BiomodelBNGLServerResource.class);
    // Expects queryparameters
    rootRouter.attach("/" + MODELBRICK, BiomodelVCMLModelInfoResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + DIAGRAM_DOWNLOAD, BiomodelDiagramServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + SIMULATION + "/{" + SIMULATIONID + "}", BiomodelSimulationServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + SIMULATION + "/{" + SIMULATIONID + "}/" + SAVESIMULATION, BiomodelSimulationSaveServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + SIMULATION + "/{" + SIMULATIONID + "}/" + STARTSIMULATION, BiomodelSimulationStartServerResource.class);
    rootRouter.attach("/" + BIOMODEL + "/{" + BIOMODELID + "}/" + SIMULATION + "/{" + SIMULATIONID + "}/" + STOPSIMULATION, BiomodelSimulationStopServerResource.class);
    rootRouter.attach("/" + SIMSTATUS, SimulationStatusServerResource.class);
    rootRouter.attach("/" + SIMTASK, SimulationTasksServerResource.class);
    rootRouter.attach("/" + SIMTASK + "/{" + SIMTASKID + "}", SimulationTaskServerResource.class);
    rootRouter.attach("/" + SIMDATA + "/{" + SIMDATAID + "}", SimDataServerResource.class);
    rootRouter.attach("/" + SIMDATA + "/{" + SIMDATAID + "}/jobindex/{" + JOBINDEX + "}", SimDataValuesServerResource.class);
    rootRouter.attach("/" + LOGIN, new LoginRestlet(getContext()));
    rootRouter.attach("/" + LOGINFORM, new LoginFormRestlet(getContext()));
    rootRouter.attach("/" + REGISTRATIONFORM, new RegistrationFormRestlet(getContext()));
    rootRouter.attach("/" + NEWUSER, new NewUserRestlet(getContext()));
    rootRouter.attach("/" + NEWUSER_VERIFY, new EmailTokenVerifyRestlet(getContext()));
    rootRouter.attach("/" + LOSTPASSWORD, new LostPasswordRestlet(getContext()));
    rootRouter.attach("/" + SWVERSION, new SWVersionRestlet(getContext()));
    rootRouter.attach("/" + RPC, new RpcRestlet(getContext(), restDatabaseService));
    rootRouter.attach("/" + EVENTS, new EventsRestlet(getContext()));
    rootRouter.attach("/" + HEALTH, new HealthRestlet(getContext()));
    rootRouter.attach("/" + ADMIN + "/" + ADMIN_JOBS, new AdminJobsRestlet(getContext()));
    rootRouter.attach("/auth/user", new Restlet(getContext()) {

        @Override
        public void handle(Request request, Response response) {
            if (request.getMethod().equals(Method.GET)) {
                VCellApiApplication application = ((VCellApiApplication) getApplication());
                User vcellUser = application.getVCellUser(request.getChallengeResponse(), AuthenticationPolicy.ignoreInvalidCredentials);
                String jsonString = "{}";
                if (vcellUser != null) {
                    jsonString = "{user: \"" + vcellUser.getName() + "\"}";
                }
                response.setEntity(new StringRepresentation(jsonString));
            }
        }
    });
    cookieAuthenticator.setNext(rootRouter);
    return cookieAuthenticator;
}
Also used : User(org.vcell.util.document.User) SWVersionRestlet(org.vcell.rest.users.SWVersionRestlet) RpcRestlet(org.vcell.rest.rpc.RpcRestlet) SWVersionRestlet(org.vcell.rest.users.SWVersionRestlet) RegistrationFormRestlet(org.vcell.rest.users.RegistrationFormRestlet) LoginRestlet(org.vcell.rest.users.LoginRestlet) HealthRestlet(org.vcell.rest.health.HealthRestlet) EventsRestlet(org.vcell.rest.events.EventsRestlet) AuthenticationTokenRestlet(org.vcell.rest.auth.AuthenticationTokenRestlet) NewUserRestlet(org.vcell.rest.users.NewUserRestlet) EmailTokenVerifyRestlet(org.vcell.rest.users.EmailTokenVerifyRestlet) LostPasswordRestlet(org.vcell.rest.users.LostPasswordRestlet) Restlet(org.restlet.Restlet) AdminJobsRestlet(org.vcell.rest.admin.AdminJobsRestlet) LoginFormRestlet(org.vcell.rest.users.LoginFormRestlet) EventsRestlet(org.vcell.rest.events.EventsRestlet) LoginFormRestlet(org.vcell.rest.users.LoginFormRestlet) RegistrationFormRestlet(org.vcell.rest.users.RegistrationFormRestlet) AdminJobsRestlet(org.vcell.rest.admin.AdminJobsRestlet) StringRepresentation(org.restlet.representation.StringRepresentation) LoginRestlet(org.vcell.rest.users.LoginRestlet) HealthRestlet(org.vcell.rest.health.HealthRestlet) Directory(org.restlet.resource.Directory) Request(org.restlet.Request) Router(org.restlet.routing.Router) RpcRestlet(org.vcell.rest.rpc.RpcRestlet) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) LostPasswordRestlet(org.vcell.rest.users.LostPasswordRestlet) NewUserRestlet(org.vcell.rest.users.NewUserRestlet) AuthenticationTokenRestlet(org.vcell.rest.auth.AuthenticationTokenRestlet) EmailTokenVerifyRestlet(org.vcell.rest.users.EmailTokenVerifyRestlet) File(java.io.File)

Aggregations

Response (org.restlet.Response)82 Request (org.restlet.Request)64 Test (org.testng.annotations.Test)28 Reference (org.restlet.data.Reference)26 Representation (org.restlet.representation.Representation)24 Status (org.restlet.data.Status)17 StringWriter (java.io.StringWriter)16 ChallengeResponse (org.restlet.data.ChallengeResponse)15 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)12 ResponseHandler (org.qi4j.library.rest.client.spi.ResponseHandler)12 HashMap (java.util.HashMap)11 ZNRecord (org.apache.helix.ZNRecord)11 StringReader (java.io.StringReader)10 Map (java.util.Map)10 TypeReference (org.codehaus.jackson.type.TypeReference)10 Test (org.junit.Test)10 Client (org.restlet.Client)10 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)9 ContextResourceClient (org.qi4j.library.rest.client.api.ContextResourceClient)7 HandlerCommand (org.qi4j.library.rest.client.api.HandlerCommand)7