Search in sources :

Example 1 with Context

use of org.restlet.Context in project Xponents by OpenSextant.

the class XlayerRestlet method createInboundRoot.

@Override
public synchronized Restlet createInboundRoot() {
    Router router = new Router(getContext());
    info("Starting Xponents Xlayer Service");
    try {
        banner();
        configure();
        Context ctx = getContext();
        ctx.getAttributes().put("xgeo", tagger);
        info("%%%%   Xponents Geo Phase Configured");
    } catch (Exception err) {
        error("Unable to start", err);
        System.exit(-1);
    }
    router.attach("/process", XponentsGeotagger.class);
    return router;
}
Also used : Context(org.restlet.Context) Router(org.restlet.routing.Router) ConfigException(org.opensextant.ConfigException) IOException(java.io.IOException)

Example 2 with Context

use of org.restlet.Context in project AJSC by att.

the class RestletSpringServlet method isDefaultComponent.

/**
 * Indicates if the Component hosted by this Servlet is the default one or
 * one provided by the user.
 *
 * @return True if the Component is the default one, false otherwise.
 */
private boolean isDefaultComponent() {
    // The Component is provided via an XML configuration file.
    Client client = createWarClient(new Context(), getServletConfig());
    Response response = client.handle(new Request(Method.GET, "war:///WEB-INF/restlet.xml"));
    if (response.getStatus().isSuccess() && response.isEntityAvailable()) {
        return false;
    }
    // The Component is provided via a context parameter in the "web.xml"
    // file.
    String componentAttributeName = getInitParameter(COMPONENT_KEY, null);
    if (componentAttributeName != null) {
        return false;
    }
    return true;
}
Also used : Context(org.restlet.Context) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.restlet.Response) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.restlet.Request) Client(org.restlet.Client)

Example 3 with Context

use of org.restlet.Context in project pinot by linkedin.

the class ControllerStarter method start.

public void start() {
    LOGGER.info("Starting Pinot controller");
    Utils.logVersions();
    component.getServers().add(Protocol.HTTP, Integer.parseInt(config.getControllerPort()));
    component.getClients().add(Protocol.FILE);
    component.getClients().add(Protocol.JAR);
    final Context applicationContext = component.getContext().createChildContext();
    LOGGER.info("Controller download url base: {}", config.generateVipUrl());
    LOGGER.info("Injecting configuration and resource manager to the API context");
    applicationContext.getAttributes().put(ControllerConf.class.toString(), config);
    applicationContext.getAttributes().put(PinotHelixResourceManager.class.toString(), helixResourceManager);
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setConnectionTimeout(config.getServerAdminRequestTimeoutSeconds());
    applicationContext.getAttributes().put(HttpConnectionManager.class.toString(), connectionManager);
    applicationContext.getAttributes().put(Executor.class.toString(), executorService);
    controllerRestApp.setContext(applicationContext);
    component.getDefaultHost().attach(controllerRestApp);
    MetricsHelper.initializeMetrics(config.subset("pinot.controller.metrics"));
    MetricsHelper.registerMetricsRegistry(_metricsRegistry);
    final ControllerMetrics controllerMetrics = new ControllerMetrics(_metricsRegistry);
    try {
        LOGGER.info("Starting Pinot Helix resource manager and connecting to Zookeeper");
        helixResourceManager.start();
        // Helix resource manager must be started in order to create PinotLLCRealtimeSegmentManager
        PinotLLCRealtimeSegmentManager.create(helixResourceManager, config, controllerMetrics);
        ValidationMetrics validationMetrics = new ValidationMetrics(_metricsRegistry);
        validationManager = new ValidationManager(validationMetrics, helixResourceManager, config, PinotLLCRealtimeSegmentManager.getInstance());
        LOGGER.info("Starting Pinot REST API component");
        component.start();
        LOGGER.info("Starting retention manager");
        retentionManager.start();
        LOGGER.info("Starting validation manager");
        validationManager.start();
        LOGGER.info("Starting realtime segment manager");
        realtimeSegmentsManager.start(controllerMetrics);
        PinotLLCRealtimeSegmentManager.getInstance().start();
        LOGGER.info("Starting segment status manager");
        segmentStatusChecker.start(controllerMetrics);
        LOGGER.info("Pinot controller ready and listening on port {} for API requests", config.getControllerPort());
        LOGGER.info("Controller services available at http://{}:{}/", config.getControllerHost(), config.getControllerPort());
    } catch (final Exception e) {
        LOGGER.error("Caught exception while starting controller", e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    }
    controllerMetrics.addCallbackGauge("helix.connected", new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            return helixResourceManager.getHelixZkManager().isConnected() ? 1L : 0L;
        }
    });
    controllerMetrics.addCallbackGauge("helix.leader", new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            return helixResourceManager.getHelixZkManager().isLeader() ? 1L : 0L;
        }
    });
    controllerMetrics.addCallbackGauge("dataDir.exists", new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            return new File(config.getDataDir()).exists() ? 1L : 0L;
        }
    });
    controllerMetrics.addCallbackGauge("dataDir.fileOpLatencyMs", new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            File dataDir = new File(config.getDataDir());
            if (dataDir.exists()) {
                try {
                    long startTime = System.currentTimeMillis();
                    final File testFile = new File(dataDir, config.getControllerHost());
                    FileOutputStream outputStream = new FileOutputStream(testFile, false);
                    outputStream.write(Longs.toByteArray(System.currentTimeMillis()));
                    outputStream.flush();
                    outputStream.close();
                    FileUtils.deleteQuietly(testFile);
                    long endTime = System.currentTimeMillis();
                    return endTime - startTime;
                } catch (IOException e) {
                    LOGGER.warn("Caught exception while checking the data directory operation latency", e);
                    return DATA_DIRECTORY_EXCEPTION_VALUE;
                }
            } else {
                return DATA_DIRECTORY_MISSING_VALUE;
            }
        }
    });
    ServiceStatus.setServiceStatusCallback(new ServiceStatus.ServiceStatusCallback() {

        private boolean _isStarted = false;

        @Override
        public ServiceStatus.Status getServiceStatus() {
            if (_isStarted) {
                // If we've connected to Helix at some point, the instance status depends on being connected to ZK
                if (helixResourceManager.getHelixZkManager().isConnected()) {
                    return ServiceStatus.Status.GOOD;
                } else {
                    return ServiceStatus.Status.BAD;
                }
            }
            // Return starting until zk is connected
            if (!helixResourceManager.getHelixZkManager().isConnected()) {
                return ServiceStatus.Status.STARTING;
            } else {
                _isStarted = true;
                return ServiceStatus.Status.GOOD;
            }
        }
    });
    helixResourceManager.getHelixZkManager().addPreConnectCallback(new PreConnectCallback() {

        @Override
        public void onPreConnect() {
            controllerMetrics.addMeteredGlobalValue(ControllerMeter.HELIX_ZOOKEEPER_RECONNECTS, 1L);
        }
    });
    controllerMetrics.initializeGlobalMeters();
    ControllerRestApplication.setControllerMetrics(controllerMetrics);
}
Also used : Context(org.restlet.Context) ServiceStatus(com.linkedin.pinot.common.utils.ServiceStatus) PinotHelixResourceManager(com.linkedin.pinot.controller.helix.core.PinotHelixResourceManager) IOException(java.io.IOException) ControllerMetrics(com.linkedin.pinot.common.metrics.ControllerMetrics) IOException(java.io.IOException) ValidationMetrics(com.linkedin.pinot.common.metrics.ValidationMetrics) Executor(java.util.concurrent.Executor) ServiceStatus(com.linkedin.pinot.common.utils.ServiceStatus) FileOutputStream(java.io.FileOutputStream) PreConnectCallback(org.apache.helix.PreConnectCallback) MultiThreadedHttpConnectionManager(org.apache.commons.httpclient.MultiThreadedHttpConnectionManager) HttpConnectionManager(org.apache.commons.httpclient.HttpConnectionManager) MultiThreadedHttpConnectionManager(org.apache.commons.httpclient.MultiThreadedHttpConnectionManager) File(java.io.File) ValidationManager(com.linkedin.pinot.controller.validation.ValidationManager)

Example 4 with Context

use of org.restlet.Context in project OpenAM by OpenRock.

the class ExceptionHandler method handle.

/**
     * Handles a OAuth2RestletException that is thrown when processing a OAuth2 authorization request.
     * <br/>
     * If the OAuth2RestletException has a status of {@link Status#REDIRECTION_TEMPORARY} the user agent will be
     * redirected to the redirect uri set on the exception.
     * <br/>
     * If the OAuth2RestletException does not have a redirect status but still has a redirect uri set, the user
     * agent will be redrected to the redirect uri with the exception message in the redirect uri.
     * <br/>
     * In all other cases the OAuth2 error page will be presented.
     *
     * @param exception The OAuth2RestletException.
     * @param context The Restlet context.
     * @param request The Restlet request.
     * @param response The Restlet response.
     */
private void handle(OAuth2RestletException exception, Context context, Request request, Response response) {
    if (exception.getStatus().equals(Status.REDIRECTION_TEMPORARY)) {
        Redirector redirector = new Redirector(new Context(), exception.getRedirectUri(), Redirector.MODE_CLIENT_PERMANENT);
        redirector.handle(request, response);
        return;
    } else {
        response.setStatus(exception.getStatus());
    }
    if (!isEmpty(exception.getRedirectUri())) {
        Reference ref = new Reference(exception.getRedirectUri());
        if (UrlLocation.FRAGMENT.equals(exception.getParameterLocation())) {
            ref.setFragment(representation.toForm(exception.asMap()).getQueryString());
        } else {
            ref.addQueryParameters(representation.toForm(exception.asMap()));
        }
        final Redirector redirector = new Redirector(context, ref.toString(), Redirector.MODE_CLIENT_FOUND);
        redirector.handle(request, response);
        return;
    }
    final Map<String, String> data = new HashMap<>(exception.asMap());
    final String realm = requestFactory.create(request).getParameter("realm");
    data.put("realm", realm);
    data.put("baseUrl", baseURLProviderFactory.get(realm).getRootURL(ServletUtils.getRequest(request)));
    response.setEntity(representation.getRepresentation(context, "page", "error.ftl", data));
}
Also used : Context(org.restlet.Context) HashMap(java.util.HashMap) Reference(org.restlet.data.Reference) Redirector(org.restlet.routing.Redirector)

Example 5 with Context

use of org.restlet.Context in project OpenAM by OpenRock.

the class TokenEndpointResourceTest method testToken.

@Test
public void testToken() throws Exception {
    //Given
    Context context = new Context();
    Request request = new Request();
    Response response = new Response(request);
    tokenEndpointResource.init(context, request, response);
    doReturn(new AccessToken(null, OAUTH_ACCESS_TOKEN, null)).when(accessTokenService).requestAccessToken(any(OAuth2Request.class));
    //When
    tokenEndpointResource.token(new EmptyRepresentation());
    //Then
    verify(hook).afterTokenHandling(any(OAuth2Request.class), eq(request), eq(response));
}
Also used : Context(org.restlet.Context) Response(org.restlet.Response) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) AccessToken(org.forgerock.oauth2.core.AccessToken) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Test(org.testng.annotations.Test)

Aggregations

Context (org.restlet.Context)8 Request (org.restlet.Request)3 Response (org.restlet.Response)3 IOException (java.io.IOException)2 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)2 Test (org.testng.annotations.Test)2 ControllerMetrics (com.linkedin.pinot.common.metrics.ControllerMetrics)1 ValidationMetrics (com.linkedin.pinot.common.metrics.ValidationMetrics)1 ServiceStatus (com.linkedin.pinot.common.utils.ServiceStatus)1 PinotHelixResourceManager (com.linkedin.pinot.controller.helix.core.PinotHelixResourceManager)1 ValidationManager (com.linkedin.pinot.controller.validation.ValidationManager)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 HashMap (java.util.HashMap)1 Executor (java.util.concurrent.Executor)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpConnectionManager (org.apache.commons.httpclient.HttpConnectionManager)1 MultiThreadedHttpConnectionManager (org.apache.commons.httpclient.MultiThreadedHttpConnectionManager)1 PreConnectCallback (org.apache.helix.PreConnectCallback)1