use of datawave.webservice.result.VoidResponse in project datawave by NationalSecurityAgency.
the class MutableMetadataUUIDHandler method process.
@Override
public void process(Connector con, ModificationRequestBase request, Map<String, Set<String>> mutableFieldList, Set<Authorizations> userAuths, String user) throws BadRequestException, AccumuloException, AccumuloSecurityException, TableNotFoundException, ExecutionException {
VoidResponse response = new VoidResponse();
ArrayList<Exception> exceptions = new ArrayList<>();
MetadataHelper mHelper = getMetadataHelper(con);
// Receive DefaultUUIDModificationRequest
DefaultUUIDModificationRequest uuidModReq = DefaultUUIDModificationRequest.class.cast(request);
List<ModificationEvent> events = uuidModReq.getEvents();
for (ModificationEvent event : events) {
List<ModificationOperationImpl> operations = event.getOperations();
for (ModificationOperationImpl operation : operations) {
ResetValues();
OPERATIONMODE mode = operation.getOperationMode();
String columnVisibility = operation.getColumnVisibility();
String oldColumnVisibility = operation.getOldColumnVisibility();
String eventUser = event.getUser();
// check whether this is a security-marking exempt field. Meaning we can pull the marking if not specified
boolean securityMarkingExempt = false;
fieldName = operation.getFieldName();
for (String s : this.getSecurityMarkingExemptFields()) {
if (fieldName.toUpperCase().equals(s)) {
securityMarkingExempt = true;
}
}
// if they are updating, assume the old values should be the same as current
if (OPERATIONMODE.UPDATE.equals(mode) && oldColumnVisibility == null) {
oldColumnVisibility = columnVisibility;
}
try {
if (mHelper.getIndexOnlyFields(mutableFieldList.keySet()).contains(event.getIdType().toUpperCase())) {
throw new IllegalStateException("Cannot perform modification because " + event.getIdType() + " is index only. Please search " + "with a different uuidType to identify the event you wish to modify.");
}
// perform the lookupUUID
EventBase<?, ? extends FieldBase<?>> idEvent = findMatchingEventUuid(event.getId(), event.getIdType(), userAuths, operation);
// extract contents from lookupUUID necessary for modification
List<? extends FieldBase<?>> fields = idEvent.getFields();
if (operation.getOldFieldValue() != null)
oldFieldValue = operation.getOldFieldValue();
if (fields != null) {
// there may be multiple values for a single field
for (FieldBase<?> f : fields) {
if (f.getName().equals(fieldName)) {
fieldCount++;
// if they are doing a replace, we need all the current values, store them
if (operation.getOperationMode().equals(OPERATIONMODE.REPLACE)) {
if (log != null)
log.trace("Adding " + f.getValueString() + ",delete to replaceMap");
replaceMap.put(f.getValueString(), OPERATIONMODE.DELETE);
}
// user sent an oldValue and we found that value or no oldValue
if ((oldFieldValue != null && f.getValueString().equals(oldFieldValue)) || oldFieldValue == null) {
fieldValue = f.getValueString();
if (columnVisibility == null && securityMarkingExempt) {
fieldColumnVisibility = f.getColumnVisibility();
}
}
} else // only if the input didn't supply a security marking AND it is an exempt field
if (f.getName().equalsIgnoreCase(event.getIdType()) && fieldCount < 1 && columnVisibility == null && securityMarkingExempt) {
if (log != null)
log.trace("Using visibility of " + f.getName() + " and setting to " + f.getColumnVisibility());
fieldColumnVisibility = f.getColumnVisibility();
}
}
List<DefaultModificationRequest> modificationRequests = new ArrayList<>();
if (OPERATIONMODE.INSERT.equals(mode) || OPERATIONMODE.UPDATE.equals(mode) || OPERATIONMODE.DELETE.equals(mode)) {
modificationRequests.add(createModificationRequest(idEvent, operation, columnVisibility, oldColumnVisibility, securityMarkingExempt));
} else if (OPERATIONMODE.REPLACE.equals(mode)) {
if (log != null)
log.trace("Adding " + operation.getFieldValue() + ",insert to replaceMap");
replaceMap.put(operation.getFieldValue(), OPERATIONMODE.INSERT);
// create a modification request of delete for each current value and an insert for the new value
for (String s : replaceMap.keySet()) {
ModificationOperation replaceOperation = operation.clone();
replaceOperation.setOperationMode(replaceMap.get(s));
replaceOperation.setFieldValue(s);
oldFieldValue = s;
modificationRequests.add(createModificationRequest(idEvent, replaceOperation, columnVisibility, oldColumnVisibility, securityMarkingExempt));
}
}
if (log != null)
log.trace("modificationRequests= " + modificationRequests);
for (DefaultModificationRequest modReq : modificationRequests) {
try {
if (fieldCount > 1 && (oldFieldValue == null && modReq.getMode() != MODE.INSERT) && !mode.equals(OPERATIONMODE.REPLACE)) {
throw new IllegalStateException("Unable to perform modification. More than one value exists for " + modReq.getFieldName() + ". Please specify the current value you wish to modify in the oldFieldValue field.");
} else if (fieldCount < 1 && modReq.getMode() != MODE.INSERT) {
throw new IllegalStateException("Unable to perform modification. No values exist for " + modReq.getFieldName() + ".");
} else if (columnVisibility == null && !securityMarkingExempt) {
throw new IllegalStateException("Must provide columnVisibility");
} else // submit DefaultModificationRequest
{
log.info("eventUser = " + eventUser + ", event.getUser() = " + event.getUser());
if (log != null)
log.trace("Submitting request to MutableMetadataHandler from MutableMetadataUUIDHandler: " + modReq);
// make sure user isn't null or empty
if (eventUser == null || eventUser.equals("")) {
if (log != null)
log.trace("No user provided for event. Using caller: " + user);
super.process(con, modReq, mutableFieldList, userAuths, user);
} else {
super.process(con, modReq, mutableFieldList, userAuths, event.getUser());
}
}
}// log exceptions that occur for each modification request. Let as many requests work as possible before returning
catch (Exception e) {
if (log != null)
log.error("Modification error", e);
exceptions.add(new Exception(event.getId() + ": " + e.getMessage() + "\n" + modReq));
}
}
modificationRequests.clear();
} else {
throw new IllegalStateException("No event matched " + event.getId());
}
} catch (Exception e) {
if (log != null)
log.error("Modification error", e);
exceptions.add(new Exception(event.getId() + ": " + e.getMessage() + "\n"));
}
}
}
// If any errors occurred, return them in the response to the user
if (!exceptions.isEmpty()) {
for (Exception e : exceptions) {
QueryException qe = new QueryException(DatawaveErrorCode.MODIFICATION_ERROR, e);
response.addException(qe.getBottomQueryException());
}
QueryException e = new QueryException(DatawaveErrorCode.MODIFICATION_ERROR);
throw new BadRequestException(e, response);
}
}
use of datawave.webservice.result.VoidResponse 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;
}
use of datawave.webservice.result.VoidResponse in project datawave by NationalSecurityAgency.
the class CachedResultsBean method cancelLoad.
/**
* Cancel the load process.
*
* @param originalQueryId
*
* @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 401 caller is not authorized to cancel the query
*/
@PUT
@Produces({ "application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf", "application/x-protostuff" })
@javax.ws.rs.Path("/{queryId}/cancel")
@GZIP
@ClearQuerySessionId
@Interceptors({ RequiredInterceptor.class, ResponseInterceptor.class })
@Timed(name = "dw.cachedr.cancel", absolute = true)
public VoidResponse cancelLoad(@PathParam("queryId") @Required("queryId") String originalQueryId) {
// Find out who/what called this method
Principal p = ctx.getCallerPrincipal();
String owner = getOwnerFromPrincipal(p);
VoidResponse response = new VoidResponse();
try {
// check if query is even loading
RunningQuery query = CachedResultsBean.loadingQueryMap.get(originalQueryId);
if (query == null) {
NotFoundQueryException e = new NotFoundQueryException(DatawaveErrorCode.NO_QUERY_OBJECT_MATCH);
throw new NotFoundException(e, response);
} else {
if (query.getSettings().getOwner().equals(owner)) {
accumuloConnectionRequestBean.cancelConnectionRequest(originalQueryId);
query.cancel();
response.addMessage("CachedResults load canceled.");
} else {
UnauthorizedQueryException e = new UnauthorizedQueryException(DatawaveErrorCode.QUERY_OWNER_MISMATCH, MessageFormat.format("{0} != {1}", query.getSettings().getOwner(), owner));
throw new UnauthorizedException(e, response);
}
}
return response;
} catch (DatawaveWebApplicationException e) {
throw e;
} catch (Exception e) {
QueryException qe = new QueryException(DatawaveErrorCode.CANCELLATION_ERROR, e, MessageFormat.format("query_id: {0}", originalQueryId));
log.error(qe);
response.addException(qe.getBottomQueryException());
int statusCode = qe.getBottomQueryException().getStatusCode();
throw new DatawaveWebApplicationException(qe, response, statusCode);
}
}
use of datawave.webservice.result.VoidResponse in project datawave by NationalSecurityAgency.
the class AtomServiceBean method getCategories.
/**
* @return Atom Categories document that lists category names
*/
@GET
@GZIP
@Produces("application/atomcat+xml")
@Path("/categories")
public Categories getCategories() {
Principal p = ctx.getCallerPrincipal();
Set<Authorizations> auths = new HashSet<>();
if (p instanceof DatawavePrincipal) {
DatawavePrincipal dp = (DatawavePrincipal) p;
for (Collection<String> cbAuths : dp.getAuthorizations()) auths.add(new Authorizations(cbAuths.toArray(new String[cbAuths.size()])));
}
Categories result;
Connector connection = null;
try {
result = abdera.newCategories();
Map<String, String> trackingMap = connectionFactory.getTrackingMap(Thread.currentThread().getStackTrace());
connection = connectionFactory.getConnection(poolName, Priority.NORMAL, trackingMap);
try (Scanner scanner = ScannerHelper.createScanner(connection, tableName + "Categories", auths)) {
Map<String, String> props = new HashMap<>();
props.put(MatchingKeySkippingIterator.ROW_DELIMITER_OPTION, "\0");
props.put(MatchingKeySkippingIterator.NUM_SCANS_STRING_NAME, "5");
IteratorSetting setting = new IteratorSetting(30, MatchingKeySkippingIterator.class, props);
scanner.addScanIterator(setting);
for (Map.Entry<Key, Value> entry : scanner) {
String collectionName = entry.getKey().getRow().toString();
result.addCategory(collectionName);
}
}
if (result.getCategories().isEmpty())
throw new NoResultsException(null);
else
return result;
} catch (WebApplicationException web) {
throw web;
} catch (Exception e) {
VoidResponse response = new VoidResponse();
QueryException qe = new QueryException(DatawaveErrorCode.COLLECTION_ERROR, e);
log.error(qe);
response.addException(qe.getBottomQueryException());
throw new DatawaveWebApplicationException(qe, response);
} finally {
if (null != connection) {
try {
connectionFactory.returnConnection(connection);
} catch (Exception e) {
log.error("Error returning connection to factory", e);
}
}
}
}
use of datawave.webservice.result.VoidResponse in project datawave by NationalSecurityAgency.
the class ModelBean method cloneModel.
/**
* <strong>Administrator credentials required.</strong> Copy a model
*
* @param name
* model to copy
* @param newName
* name of copied model
* @param modelTableName
* name of the table that contains the model
* @return datawave.webservice.result.VoidResponse
* @RequestHeader X-ProxiedEntitiesChain use when proxying request for user
*
* @HTTP 200 success
* @HTTP 204 model not found
* @HTTP 500 internal server error
*/
@POST
@Produces({ "application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf", "application/x-protostuff" })
@Path("/clone")
@GZIP
@RolesAllowed({ "Administrator", "JBossAdministrator" })
@Interceptors({ RequiredInterceptor.class, ResponseInterceptor.class })
public VoidResponse cloneModel(@Required("name") @FormParam("name") String name, @Required("newName") @FormParam("newName") String newName, @FormParam("modelTableName") String modelTableName) {
VoidResponse response = new VoidResponse();
if (modelTableName == null) {
modelTableName = defaultModelTableName;
}
datawave.webservice.model.Model model = getModel(name, modelTableName);
// Set the new name
model.setName(newName);
importModel(model, modelTableName);
return response;
}
Aggregations