Search in sources :

Example 41 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project pinot by linkedin.

the class TableSizeResource method getTableSize.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/tables/{tableName}/size")
@ApiOperation(value = "Show table storage size", notes = "Lists size of all the segments of the table")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 404, message = "Table not found") })
public TableSizeInfo getTableSize(@ApiParam(value = "Table Name with type", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "Provide detailed information", required = false) @DefaultValue("true") @QueryParam("detailed") boolean detailed) throws WebApplicationException {
    InstanceDataManager dataManager = (InstanceDataManager) serverInstance.getInstanceDataManager();
    if (dataManager == null) {
        throw new WebApplicationException("Invalid server initialization", Response.Status.INTERNAL_SERVER_ERROR);
    }
    TableDataManager tableDataManager = dataManager.getTableDataManager(tableName);
    if (tableDataManager == null) {
        throw new WebApplicationException("Table: " + tableName + " is not found", Response.Status.NOT_FOUND);
    }
    TableSizeInfo tableSizeInfo = new TableSizeInfo();
    tableSizeInfo.tableName = tableDataManager.getTableName();
    tableSizeInfo.diskSizeInBytes = 0L;
    ImmutableList<SegmentDataManager> segmentDataManagers = tableDataManager.acquireAllSegments();
    try {
        for (SegmentDataManager segmentDataManager : segmentDataManagers) {
            IndexSegment segment = segmentDataManager.getSegment();
            long segmentSizeBytes = segment.getDiskSizeBytes();
            if (detailed) {
                SegmentSizeInfo segmentSizeInfo = new SegmentSizeInfo(segment.getSegmentName(), segmentSizeBytes);
                tableSizeInfo.segments.add(segmentSizeInfo);
            }
            tableSizeInfo.diskSizeInBytes += segmentSizeBytes;
        }
    } finally {
        // executes fast so duration of holding segments is not a concern
        for (SegmentDataManager segmentDataManager : segmentDataManagers) {
            tableDataManager.releaseSegment(segmentDataManager);
        }
    }
    //invalid to use the segmentDataManagers below
    return tableSizeInfo;
}
Also used : SegmentDataManager(com.linkedin.pinot.core.data.manager.offline.SegmentDataManager) WebApplicationException(javax.ws.rs.WebApplicationException) IndexSegment(com.linkedin.pinot.core.indexsegment.IndexSegment) TableDataManager(com.linkedin.pinot.core.data.manager.offline.TableDataManager) InstanceDataManager(com.linkedin.pinot.core.data.manager.offline.InstanceDataManager) SegmentSizeInfo(com.linkedin.pinot.common.restlet.resources.SegmentSizeInfo) TableSizeInfo(com.linkedin.pinot.common.restlet.resources.TableSizeInfo) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 42 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project pinot by linkedin.

the class TablesResource method checkGetTableDataManager.

private TableDataManager checkGetTableDataManager(String tableName) {
    InstanceDataManager dataManager = checkGetInstanceDataManager();
    TableDataManager tableDataManager = dataManager.getTableDataManager(tableName);
    if (tableDataManager == null) {
        throw new WebApplicationException("Table " + tableName + " does not exist", Response.Status.NOT_FOUND);
    }
    return tableDataManager;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) TableDataManager(com.linkedin.pinot.core.data.manager.offline.TableDataManager) InstanceDataManager(com.linkedin.pinot.core.data.manager.offline.InstanceDataManager)

Example 43 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project platformlayer by platformlayer.

the class RestLoginServlet method processRequest.

protected void processRequest(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final AuthenticateRequest request, boolean checkLimit) throws IOException {
    try {
        if (request.auth == null) {
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        String username = getUsername(request);
        if (Strings.isNullOrEmpty(username)) {
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        if (checkLimit && limits.isOverLimit(httpRequest, username)) {
            final AsyncContext asyncContext = httpRequest.startAsync(httpRequest, httpResponse);
            asyncExecutor.schedule(LoginService.OVER_LIMIT_DELAY, new Runnable() {

                @Override
                public void run() {
                    try {
                        processRequest(httpRequest, httpResponse, request, false);
                        asyncContext.complete();
                    } catch (Exception e) {
                        log.error("Unexpected error caught in async task", e);
                    }
                }
            });
            return;
        }
        AuthenticateResponse authenticateResponse = loginService.authenticate(httpRequest, request);
        if (authenticateResponse == null) {
            limits.recordFail(httpRequest, username);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        marshaller.write(httpRequest, httpResponse, authenticateResponse);
    } catch (WebApplicationException e) {
        log.info("Returning exception from servlet", e);
        httpResponse.sendError(e.getResponse().getStatus());
    } catch (Exception e) {
        log.warn("Unexpected error in servlet", e);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : AuthenticateResponse(org.platformlayer.auth.model.AuthenticateResponse) WebApplicationException(javax.ws.rs.WebApplicationException) AsyncContext(javax.servlet.AsyncContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 44 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project platformlayer by platformlayer.

the class OperationWorker method doOperation.

Object doOperation() throws OpsException {
    final Action action = activeJob.getAction();
    final PlatformLayerKey targetItemKey = activeJob.getTargetItemKey();
    RenameThread rename = new RenameThread(action.getClass().getSimpleName() + " " + targetItemKey);
    try {
        OpsContextBuilder opsContextBuilder = opsSystem.getInjector().getInstance(OpsContextBuilder.class);
        final ProjectAuthorization project = activeJob.getProjectAuthorization();
        final OpsContext opsContext = opsContextBuilder.buildOpsContext(activeJob);
        final ServiceType serviceType = activeJob.getServiceType();
        final ServiceProvider serviceProvider = opsSystem.getServiceProvider(serviceType);
        try {
            return OpsContext.runInContext(opsContext, new CheckedCallable<Object, Exception>() {

                @Override
                public Object call() throws Exception {
                    log.info("Starting job");
                    activeJob.setState(JobState.RUNNING);
                    ItemBase item;
                    ManagedItemRepository repository = opsSystem.getManagedItemRepository();
                    try {
                        boolean fetchTags = true;
                        item = repository.getManagedItem(targetItemKey, fetchTags, SecretProvider.from(project));
                    } catch (RepositoryException e) {
                        throw new OpsException("Error reading item from repository", e);
                    }
                    if (item == null) {
                        throw new WebApplicationException(404);
                    }
                    List<Object> scopeItems = Lists.newArrayList();
                    addActionScopeItems(action, item, scopeItems);
                    Object controller = serviceProvider.getController(item);
                    scopeItems.add(item);
                    scopeItems.add(action);
                    BindingScope scope = BindingScope.push(scopeItems);
                    opsContext.recurseOperation(scope, controller);
                    // TODO: Should we run a verify operation before -> ACTIVE??
                    // (we need to fix the states as well)
                    ManagedItemState newState = finishAction(action, scope);
                    if (newState != null) {
                        repository.changeState(targetItemKey, newState);
                        item.state = newState;
                    }
                    log.info("Job finished with SUCCESS");
                    activeJob.setState(JobState.SUCCESS);
                    return null;
                }

                private ManagedItemState finishAction(Action action, BindingScope scope) throws OpsException {
                    ManagedItemState newState = null;
                    if (action instanceof ConfigureAction) {
                        newState = ManagedItemState.ACTIVE;
                    }
                    if (action instanceof ValidateAction) {
                    // TODO: Change state to healthy??
                    }
                    if (action instanceof DeleteAction) {
                        newState = ManagedItemState.DELETED;
                    }
                    if (action instanceof BackupAction) {
                        BackupContext backupContext = scope.getInstance(BackupContext.class);
                        backupContext.writeDescriptor();
                    }
                    return newState;
                }

                private void addActionScopeItems(Action action, ItemBase item, List<Object> scopeItems) throws OpsException {
                    if (action instanceof BackupAction) {
                        // TODO: Don't hard-code this
                        BackupHelpers backupHelpers = opsSystem.getInjector().getInstance(BackupHelpers.class);
                        BackupContext backupContext = backupHelpers.createBackupContext(item);
                        scopeItems.add(backupContext);
                    }
                }
            });
        } catch (Throwable e) {
            log.warn("Error running operation", e);
            log.warn("Job finished with FAILED");
            // boolean isDone = false; // We will retry
            activeJob.setState(JobState.FAILED);
            TimeSpan retry = null;
            HasRetryInfo retryInfo = ExceptionHelpers.findRetryInfo(e);
            if (retryInfo != null) {
                retry = retryInfo.getRetry();
            }
            if (retry == null) {
                // TODO: Eventually give up??
                retry = ApplicationMode.isDevelopment() ? TimeSpan.ONE_MINUTE : TimeSpan.FIVE_MINUTES;
            }
            // TODO: State transition??
            // managedItem.setState(ManagedItemState.ACTIVE, true);
            log.warn("Scheduling retry in " + retry);
            activeJob.enqueueRetry(retry);
            return null;
        } finally {
            try {
                activeJob.recordJobEnd();
            } catch (OpsException e) {
                log.error("Error recording job in registry", e);
            }
        }
    } finally {
        IoUtils.safeClose(rename);
    }
}
Also used : ValidateAction(org.platformlayer.core.model.ValidateAction) ConfigureAction(org.platformlayer.core.model.ConfigureAction) DeleteAction(org.platformlayer.core.model.DeleteAction) BackupAction(org.platformlayer.core.model.BackupAction) Action(org.platformlayer.core.model.Action) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) BackupHelpers(org.platformlayer.ops.backups.BackupHelpers) ManagedItemRepository(org.platformlayer.xaas.repository.ManagedItemRepository) OpsContext(org.platformlayer.ops.OpsContext) TimeSpan(com.fathomdb.TimeSpan) BackupAction(org.platformlayer.core.model.BackupAction) ServiceType(org.platformlayer.ids.ServiceType) BackupContext(org.platformlayer.ops.backups.BackupContext) HasRetryInfo(org.platformlayer.exceptions.HasRetryInfo) List(java.util.List) BindingScope(org.platformlayer.ops.BindingScope) ConfigureAction(org.platformlayer.core.model.ConfigureAction) ItemBase(org.platformlayer.core.model.ItemBase) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) ProjectAuthorization(org.platformlayer.model.ProjectAuthorization) DeleteAction(org.platformlayer.core.model.DeleteAction) ValidateAction(org.platformlayer.core.model.ValidateAction) ManagedItemState(org.platformlayer.core.model.ManagedItemState)

Example 45 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project presto by prestodb.

the class StatementResource method createQuery.

@POST
@Produces(MediaType.APPLICATION_JSON)
public Response createQuery(String statement, @Context HttpServletRequest servletRequest, @Context UriInfo uriInfo) throws InterruptedException {
    if (isNullOrEmpty(statement)) {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("SQL statement is empty").build());
    }
    SessionSupplier sessionSupplier = new HttpRequestSessionFactory(servletRequest);
    ExchangeClient exchangeClient = exchangeClientSupplier.get(deltaMemoryInBytes -> {
    });
    Query query = new Query(sessionSupplier, statement, queryManager, sessionPropertyManager, exchangeClient, blockEncodingSerde);
    queries.put(query.getQueryId(), query);
    return getQueryResults(query, Optional.empty(), uriInfo, new Duration(1, MILLISECONDS));
}
Also used : ExchangeClient(com.facebook.presto.operator.ExchangeClient) WebApplicationException(javax.ws.rs.WebApplicationException) Duration(io.airlift.units.Duration) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)276 Produces (javax.ws.rs.Produces)77 GET (javax.ws.rs.GET)71 Path (javax.ws.rs.Path)69 IOException (java.io.IOException)47 POST (javax.ws.rs.POST)47 Consumes (javax.ws.rs.Consumes)44 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)43 Response (javax.ws.rs.core.Response)30 MediaType (javax.ws.rs.core.MediaType)26 URI (java.net.URI)25 HashMap (java.util.HashMap)20 JSONObject (org.codehaus.jettison.json.JSONObject)20 Test (org.junit.Test)19 JSONException (org.codehaus.jettison.json.JSONException)18 ApiOperation (io.swagger.annotations.ApiOperation)17 ArrayList (java.util.ArrayList)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)15 List (java.util.List)14