Search in sources :

Example 1 with PreConditionFailedException

use of datawave.webservice.common.exception.PreConditionFailedException in project datawave by NationalSecurityAgency.

the class CachedResultsBean method loadAndCreateAsync.

// Do not use the @Asynchronous annotation here. This method runs, setting status and
// then executes loadAndCreate asynchronously. It does not itself get run asynchronously.
@Interceptors({ RequiredInterceptor.class, ResponseInterceptor.class })
public Future<CachedResultsResponse> loadAndCreateAsync(MultivaluedMap<String, String> queryParameters) {
    String newQueryId = queryParameters.getFirst("newQueryId");
    Preconditions.checkNotNull(newQueryId, "newQueryId cannot be null");
    String queryId = queryParameters.getFirst(CachedResultsParameters.QUERY_ID);
    Preconditions.checkNotNull(queryId, "queryId cannot be null");
    String alias = queryParameters.getFirst("alias");
    if (alias == null) {
        alias = newQueryId;
    }
    // Find out who/what called this method
    Principal p = ctx.getCallerPrincipal();
    String owner = getOwnerFromPrincipal(p);
    CachedRunningQuery crq = null;
    try {
        persistByQueryId(newQueryId, alias, owner, CachedRunningQuery.Status.LOADING, "", true);
        crq = retrieve(newQueryId, owner);
    } catch (IOException e1) {
        log.error("Error trying to persist/retrieve cached results", e1);
        try {
            persistByQueryId(newQueryId, alias, owner, CachedRunningQuery.Status.ERROR, e1.getMessage(), false);
        } catch (IOException e2) {
            log.error(e2.getMessage(), e2);
        }
        PreConditionFailedQueryException e = new PreConditionFailedQueryException(DatawaveErrorCode.CACHED_RESULTS_PERSIST_ERROR, e1);
        throw new PreConditionFailedException(e, null);
    }
    RunningQuery rq = null;
    try {
        rq = getQueryById(queryId);
        if (rq != null) {
            String nameBase = UUID.randomUUID().toString().replaceAll("-", "");
            Query q = rq.getSettings();
            crq.setOriginalQueryId(q.getId().toString());
            crq.setView(nameBase);
            crq.setAlias(alias);
            crq.setQuery(rq.getSettings());
            persist(crq, owner);
        }
    } catch (Exception e) {
        String statusMessage = e.getMessage();
        if (null == statusMessage) {
            statusMessage = e.getClass().getName();
        }
        try {
            persistByQueryId(newQueryId, alias, owner, CachedRunningQuery.Status.ERROR, statusMessage, true);
        } catch (IOException e1) {
            log.error("Error persisting status to CachedResult store", e1);
        }
        log.error(e.getMessage(), e);
    }
    // pagesize validated in loadAndCreate
    return new AsyncResult<>(loadAndCreate(queryId, queryParameters));
}
Also used : RunningQuery(datawave.webservice.query.runner.RunningQuery) PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) Query(datawave.webservice.query.Query) RunningQuery(datawave.webservice.query.runner.RunningQuery) PreConditionFailedQueryException(datawave.webservice.query.exception.PreConditionFailedQueryException) IOException(java.io.IOException) AsyncResult(javax.ejb.AsyncResult) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) DatawaveWebApplicationException(datawave.webservice.common.exception.DatawaveWebApplicationException) PreConditionFailedQueryException(datawave.webservice.query.exception.PreConditionFailedQueryException) EJBException(javax.ejb.EJBException) NotFoundQueryException(datawave.webservice.query.exception.NotFoundQueryException) NoResultsQueryException(datawave.webservice.query.exception.NoResultsQueryException) BatchUpdateException(java.sql.BatchUpdateException) SQLException(java.sql.SQLException) IOException(java.io.IOException) QueryCanceledQueryException(datawave.webservice.query.exception.QueryCanceledQueryException) QueryException(datawave.webservice.query.exception.QueryException) QueryCanceledException(datawave.webservice.common.exception.QueryCanceledException) PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) NotFoundException(datawave.webservice.common.exception.NotFoundException) UnauthorizedQueryException(datawave.webservice.query.exception.UnauthorizedQueryException) UnauthorizedException(datawave.webservice.common.exception.UnauthorizedException) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) NoResultsException(datawave.webservice.common.exception.NoResultsException) BadRequestQueryException(datawave.webservice.query.exception.BadRequestQueryException) MalformedURLException(java.net.MalformedURLException) Interceptors(javax.interceptor.Interceptors)

Example 2 with PreConditionFailedException

use of datawave.webservice.common.exception.PreConditionFailedException in project datawave by NationalSecurityAgency.

the class CachedResultsBean method status.

/**
 * Returns status of the requested cached result
 *
 * @param queryId
 * @return List of attribute names that can be used in subsequent queries
 *
 * @return {@code datawave.webservice.result.GenericResponse<String>}
 * @RequestHeader X-ProxiedEntitiesChain use when proxying request for user by specifying a chain of DNs of the identities to proxy
 * @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
 * @ResponseHeader X-OperationTimeInMS time spent on the server performing the operation, does not account for network or result serialization
 *
 * @HTTP 200 success
 * @HTTP 404 not found
 * @HTTP 412 not yet loaded
 * @HTTP 500 internal server error
 */
@GET
@Produces({ "application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf" })
@javax.ws.rs.Path("/{queryId}/status")
@GZIP
@Interceptors({ RequiredInterceptor.class, ResponseInterceptor.class })
@Timed(name = "dw.cachedr.status", absolute = true)
public GenericResponse<String> status(@PathParam("queryId") @Required("queryId") String queryId) {
    GenericResponse<String> response = new GenericResponse<>();
    // Find out who/what called this method
    Principal p = ctx.getCallerPrincipal();
    String owner = getOwnerFromPrincipal(p);
    CachedRunningQuery crq;
    try {
        crq = retrieve(queryId, owner);
    } catch (IOException e1) {
        PreConditionFailedQueryException e = new PreConditionFailedQueryException(DatawaveErrorCode.CACHED_RESULTS_IMPORT_ERROR, e1);
        response.addException(e);
        response.setResult("CachedResult not found");
        throw new PreConditionFailedException(e, response);
    }
    if (null == crq) {
        NotFoundQueryException e = new NotFoundQueryException(DatawaveErrorCode.CACHED_RESULT_NOT_FOUND);
        response.addException(e);
        response.setResult("CachedResult not found");
        throw new NotFoundException(e, response);
    }
    if (!crq.getUser().equals(owner)) {
        UnauthorizedQueryException e = new UnauthorizedQueryException(DatawaveErrorCode.QUERY_OWNER_MISMATCH, MessageFormat.format("{0} != {1}", crq.getUser(), owner));
        response.addException(e);
        response.setResult("Current user does not match user that defined query.");
        throw new UnauthorizedException(e, response);
    }
    CachedRunningQuery.Status status = crq.getStatus();
    if (status == null) {
        response.setResult(CachedRunningQuery.Status.NONE.toString());
    } else {
        response.setResult(status.toString());
    }
    if (crq.getStatusMessage() != null && crq.getStatusMessage().isEmpty() == false) {
        response.addMessage(crq.getStatusMessage());
    }
    return response;
}
Also used : GenericResponse(datawave.webservice.result.GenericResponse) PreConditionFailedQueryException(datawave.webservice.query.exception.PreConditionFailedQueryException) NotFoundException(datawave.webservice.common.exception.NotFoundException) IOException(java.io.IOException) NotFoundQueryException(datawave.webservice.query.exception.NotFoundQueryException) UnauthorizedQueryException(datawave.webservice.query.exception.UnauthorizedQueryException) PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) UnauthorizedException(datawave.webservice.common.exception.UnauthorizedException) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Interceptors(javax.interceptor.Interceptors) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) GZIP(org.jboss.resteasy.annotations.GZIP)

Example 3 with PreConditionFailedException

use of datawave.webservice.common.exception.PreConditionFailedException in project datawave by NationalSecurityAgency.

the class CachedResultsBean method close.

/**
 * Releases resources associated with this query.
 *
 * @param queryId
 *            use defined id for this query
 *
 * @return datawave.webservice.result.VoidResponse
 * @RequestHeader X-ProxiedEntitiesChain use when proxying request for user by specifying a chain of DNs of the identities to proxy
 * @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
 * @RequestHeader query-session-id session id value used for load balancing purposes. query-session-id can be placed in the request in a Cookie header or as
 *                a query parameter
 * @ResponseHeader X-OperationTimeInMS time spent on the server performing the operation, does not account for network or result serialization
 *
 * @HTTP 200 success
 * @HTTP 500 internal server error
 */
@DELETE
@Produces({ "application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml" })
@javax.ws.rs.Path("/{queryId}/close")
@Interceptors({ RequiredInterceptor.class, ResponseInterceptor.class })
@ClearQuerySessionId
@Timed(name = "dw.cachedr.close", absolute = true)
public VoidResponse close(@PathParam("queryId") @Required("queryId") String queryId) {
    // Find out who/what called this method
    Principal p = ctx.getCallerPrincipal();
    String owner = getOwnerFromPrincipal(p);
    VoidResponse response = new VoidResponse();
    CachedRunningQuery crq;
    try {
        crq = retrieve(queryId, owner);
    } catch (IOException e) {
        PreConditionFailedQueryException qe = new PreConditionFailedQueryException(DatawaveErrorCode.CACHED_RUNNING_QUERY_ERROR, e);
        log.error(qe);
        response.addException(qe.getBottomQueryException());
        throw new PreConditionFailedException(qe, response);
    }
    if (null != crq) {
        // CachedRunningQueries may be stored under multiple keys
        if (crq.getQueryId() != null) {
            cachedRunningQueryCache.remove(owner + "-" + crq.getQueryId());
        }
        if (crq.getAlias() != null) {
            cachedRunningQueryCache.remove(owner + "-" + crq.getAlias());
        }
        if (crq.getView() != null) {
            cachedRunningQueryCache.remove(owner + "-" + crq.getView());
        }
        if (crq.isActivated()) {
            synchronized (crq) {
                crq.closeConnection(log);
            }
            crq.getMetric().setLifecycle(QueryMetric.Lifecycle.CLOSED);
            if (crq.getQueryLogic().getCollectQueryMetrics() == true) {
                try {
                    metrics.updateMetric(crq.getMetric());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
    return response;
}
Also used : PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) PreConditionFailedQueryException(datawave.webservice.query.exception.PreConditionFailedQueryException) VoidResponse(datawave.webservice.result.VoidResponse) IOException(java.io.IOException) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) DatawaveWebApplicationException(datawave.webservice.common.exception.DatawaveWebApplicationException) PreConditionFailedQueryException(datawave.webservice.query.exception.PreConditionFailedQueryException) EJBException(javax.ejb.EJBException) NotFoundQueryException(datawave.webservice.query.exception.NotFoundQueryException) NoResultsQueryException(datawave.webservice.query.exception.NoResultsQueryException) BatchUpdateException(java.sql.BatchUpdateException) SQLException(java.sql.SQLException) IOException(java.io.IOException) QueryCanceledQueryException(datawave.webservice.query.exception.QueryCanceledQueryException) QueryException(datawave.webservice.query.exception.QueryException) QueryCanceledException(datawave.webservice.common.exception.QueryCanceledException) PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) NotFoundException(datawave.webservice.common.exception.NotFoundException) UnauthorizedQueryException(datawave.webservice.query.exception.UnauthorizedQueryException) UnauthorizedException(datawave.webservice.common.exception.UnauthorizedException) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) NoResultsException(datawave.webservice.common.exception.NoResultsException) BadRequestQueryException(datawave.webservice.query.exception.BadRequestQueryException) MalformedURLException(java.net.MalformedURLException) DELETE(javax.ws.rs.DELETE) Interceptors(javax.interceptor.Interceptors) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ClearQuerySessionId(datawave.annotation.ClearQuerySessionId)

Example 4 with PreConditionFailedException

use of datawave.webservice.common.exception.PreConditionFailedException in project datawave by NationalSecurityAgency.

the class LookupUUIDUtil method validatePagedResponse.

private EventQueryResponseBase validatePagedResponse(final BaseQueryResponse response) {
    final EventQueryResponseBase pagedResponse;
    if (response instanceof EventQueryResponseBase) {
        pagedResponse = (EventQueryResponseBase) response;
    } else {
        final EventQueryResponseBase er = responseObjectFactory.getEventQueryResponse();
        er.addMessage("Unhandled response type from Query/createQueryAndNext");
        throw new PreConditionFailedException(null, er);
    }
    return pagedResponse;
}
Also used : PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) EventQueryResponseBase(datawave.webservice.result.EventQueryResponseBase)

Example 5 with PreConditionFailedException

use of datawave.webservice.common.exception.PreConditionFailedException in project datawave by NationalSecurityAgency.

the class LookupUUIDUtil method lookupPagedContent.

private EventQueryResponseBase lookupPagedContent(final String queryName, final AbstractUUIDLookupCriteria validatedCriteria, final List<StringBuilder> batchedContentQueryStrings, final Date endDate, final Date expireDate, final String userAuths, boolean allEventMockResponse) {
    // Initialize the return value
    EventQueryResponseBase mergedContentQueryResponse = null;
    // Call the ContentQuery for one or more events
    DatawaveWebApplicationException noResultsException = null;
    for (final StringBuilder contentQuery : batchedContentQueryStrings) {
        // Submitted query should look like this:
        // 
        // DOCUMENT:shardId/datatype/uid [DOCUMENT:shardId/datatype/uid]*
        // 
        MultivaluedMap<String, String> queryParameters = new MultivaluedMapImpl<>();
        queryParameters.putAll(this.defaultOptionalParams);
        queryParameters.putSingle(QueryParameters.QUERY_NAME, queryName);
        queryParameters.putSingle(QueryParameters.QUERY_STRING, contentQuery.toString());
        try {
            queryParameters.putSingle(QueryParameters.QUERY_BEGIN, QueryParametersImpl.formatDate(this.beginAsDate));
        } catch (ParseException e1) {
            throw new RuntimeException("Error formatting begin date: " + this.beginAsDate);
        }
        try {
            queryParameters.putSingle(QueryParameters.QUERY_END, QueryParametersImpl.formatDate(endDate));
        } catch (ParseException e1) {
            throw new RuntimeException("Error formatting end date: " + endDate);
        }
        queryParameters.putSingle(QueryParameters.QUERY_AUTHORIZATIONS, userAuths);
        try {
            queryParameters.putSingle(QueryParameters.QUERY_EXPIRATION, QueryParametersImpl.formatDate(expireDate));
        } catch (ParseException e1) {
            throw new RuntimeException("Error formatting expr date: " + expireDate);
        }
        queryParameters.putSingle(QueryParameters.QUERY_PERSISTENCE, QueryPersistence.TRANSIENT.name());
        queryParameters.putSingle(QueryParameters.QUERY_TRACE, "false");
        for (String key : validatedCriteria.getQueryParameters().keySet()) {
            if (!queryParameters.containsKey(key)) {
                queryParameters.put(key, validatedCriteria.getQueryParameters().get(key));
            }
        }
        final GenericResponse<String> createResponse = this.queryExecutor.createQuery(CONTENT_QUERY, queryParameters);
        final String contentQueryId = createResponse.getResult();
        boolean preventCloseOfMergedQueryId = ((null == mergedContentQueryResponse) && allEventMockResponse);
        try {
            BaseQueryResponse contentQueryResponse = null;
            do {
                try {
                    // Get the first/next results
                    contentQueryResponse = this.queryExecutor.next(contentQueryId);
                    // Validate the response, which also checks for null
                    if (!(contentQueryResponse instanceof EventQueryResponseBase)) {
                        EventQueryResponseBase er = responseObjectFactory.getEventQueryResponse();
                        er.addMessage("Unhandled response type " + contentQueryResponse + " from ContentQuery");
                        throw new PreConditionFailedException(null, er);
                    }
                    // Prevent NPE due to attempted merge when total events is null
                    final EventQueryResponseBase eventQueryResponse = (EventQueryResponseBase) contentQueryResponse;
                    if (null == eventQueryResponse.getTotalEvents()) {
                        final Long returnedEvents = eventQueryResponse.getReturnedEvents();
                        eventQueryResponse.setTotalEvents((null != returnedEvents) ? returnedEvents : 0L);
                    }
                    // Assign the merged response if it hasn't been done yet
                    if (null == mergedContentQueryResponse) {
                        mergedContentQueryResponse = (EventQueryResponseBase) contentQueryResponse;
                    } else // If the merged content has already been assigned, merge into it, but keep the original
                    // query Id
                    {
                        final String queryId = mergedContentQueryResponse.getQueryId();
                        mergedContentQueryResponse.merge((EventQueryResponseBase) contentQueryResponse);
                        mergedContentQueryResponse.setQueryId(queryId);
                    }
                } catch (final NoResultsException e) {
                    contentQueryResponse = null;
                    noResultsException = e;
                }// in case.
                 catch (final EJBException e) {
                    final Throwable cause = e.getCause();
                    if (cause instanceof DatawaveWebApplicationException) {
                        DatawaveWebApplicationException nwae = (DatawaveWebApplicationException) cause;
                        if (nwae instanceof NoResultsException) {
                            contentQueryResponse = null;
                            noResultsException = nwae;
                        } else {
                            throw nwae;
                        }
                    }
                }
            } while (// Loop if more results are available
            null != contentQueryResponse);
        } finally {
            if (!preventCloseOfMergedQueryId) {
                this.queryExecutor.close(contentQueryId);
            }
        }
    }
    // Conditionally throw a NoResultsException
    if ((null == mergedContentQueryResponse) && (null != noResultsException)) {
        throw noResultsException;
    }
    return mergedContentQueryResponse;
}
Also used : NoResultsException(datawave.webservice.common.exception.NoResultsException) MultivaluedMapImpl(org.jboss.resteasy.specimpl.MultivaluedMapImpl) EventQueryResponseBase(datawave.webservice.result.EventQueryResponseBase) PreConditionFailedException(datawave.webservice.common.exception.PreConditionFailedException) BaseQueryResponse(datawave.webservice.result.BaseQueryResponse) DatawaveWebApplicationException(datawave.webservice.common.exception.DatawaveWebApplicationException) ParseException(java.text.ParseException) DateTimeParseException(java.time.format.DateTimeParseException) EJBException(javax.ejb.EJBException)

Aggregations

PreConditionFailedException (datawave.webservice.common.exception.PreConditionFailedException)7 DatawavePrincipal (datawave.security.authorization.DatawavePrincipal)4 DatawaveWebApplicationException (datawave.webservice.common.exception.DatawaveWebApplicationException)4 NoResultsException (datawave.webservice.common.exception.NoResultsException)4 NotFoundException (datawave.webservice.common.exception.NotFoundException)4 UnauthorizedException (datawave.webservice.common.exception.UnauthorizedException)4 NotFoundQueryException (datawave.webservice.query.exception.NotFoundQueryException)4 PreConditionFailedQueryException (datawave.webservice.query.exception.PreConditionFailedQueryException)4 UnauthorizedQueryException (datawave.webservice.query.exception.UnauthorizedQueryException)4 IOException (java.io.IOException)4 Principal (java.security.Principal)4 QueryCanceledException (datawave.webservice.common.exception.QueryCanceledException)3 BadRequestQueryException (datawave.webservice.query.exception.BadRequestQueryException)3 NoResultsQueryException (datawave.webservice.query.exception.NoResultsQueryException)3 QueryCanceledQueryException (datawave.webservice.query.exception.QueryCanceledQueryException)3 QueryException (datawave.webservice.query.exception.QueryException)3 MalformedURLException (java.net.MalformedURLException)3 BatchUpdateException (java.sql.BatchUpdateException)3 SQLException (java.sql.SQLException)3 SQLSyntaxErrorException (java.sql.SQLSyntaxErrorException)3