use of datawave.webservice.query.QueryParameters in project datawave by NationalSecurityAgency.
the class CompositeIndexTest method getQueryRangesIterator.
private Iterator getQueryRangesIterator(String queryString, ShardQueryLogic logic) throws Exception {
MultivaluedMap<String, String> params = new MultivaluedMapImpl<>();
params.putSingle(QUERY_STRING, queryString);
params.putSingle(QUERY_NAME, "geoQuery");
params.putSingle(QUERY_LOGIC_NAME, "EventQueryLogic");
params.putSingle(QUERY_PERSISTENCE, "PERSISTENT");
params.putSingle(QUERY_AUTHORIZATIONS, AUTHS);
params.putSingle(QUERY_EXPIRATION, "20200101 000000.000");
params.putSingle(QUERY_BEGIN, BEGIN_DATE);
params.putSingle(QUERY_END, END_DATE);
QueryParameters queryParams = new QueryParametersImpl();
queryParams.validate(params);
Set<Authorizations> auths = new HashSet<>();
auths.add(new Authorizations(AUTHS));
Query query = new QueryImpl();
query.initialize(USER, Arrays.asList(USER_DN), null, queryParams, null);
ShardQueryConfiguration config = ShardQueryConfiguration.create(logic, query);
logic.initialize(config, instance.getConnector("root", PASSWORD), query, auths);
logic.setupQuery(config);
return config.getQueries();
}
use of datawave.webservice.query.QueryParameters in project datawave by NationalSecurityAgency.
the class MultiValueCompositeIndexTest method getResultsIterator.
private Iterator getResultsIterator(String queryString, ShardQueryLogic logic) throws Exception {
MultivaluedMap<String, String> params = new MultivaluedMapImpl<>();
params.putSingle(QUERY_STRING, queryString);
params.putSingle(QUERY_NAME, "geoQuery");
params.putSingle(QUERY_LOGIC_NAME, "EventQueryLogic");
params.putSingle(QUERY_PERSISTENCE, "PERSISTENT");
params.putSingle(QUERY_AUTHORIZATIONS, AUTHS);
params.putSingle(QUERY_EXPIRATION, "20200101 000000.000");
params.putSingle(QUERY_BEGIN, BEGIN_DATE);
params.putSingle(QUERY_END, END_DATE);
QueryParameters queryParams = new QueryParametersImpl();
queryParams.validate(params);
Set<Authorizations> auths = new HashSet<>();
auths.add(new Authorizations(AUTHS));
Query query = new QueryImpl();
query.initialize(USER, Arrays.asList(USER_DN), null, queryParams, null);
ShardQueryConfiguration config = ShardQueryConfiguration.create(logic, query);
logic.initialize(config, instance.getConnector("root", PASSWORD), query, auths);
logic.setupQuery(config);
return logic.getTransformIterator(query);
}
use of datawave.webservice.query.QueryParameters in project datawave by NationalSecurityAgency.
the class QueryExecutorBeanTest method testCreateWithNoSelectedAuths.
@SuppressWarnings("unchecked")
@Test(expected = DatawaveWebApplicationException.class)
public void testCreateWithNoSelectedAuths() throws Exception {
String queryLogicName = "EventQueryLogic";
String queryName = "Something";
String query = "FOO == BAR";
Date beginDate = new Date();
Date expirationDate = DateUtils.addDays(new Date(), 1);
int pagesize = 10;
QueryPersistence persist = QueryPersistence.TRANSIENT;
Set<QueryImpl.Parameter> parameters = new HashSet<>();
// need to call the getQueryByName() method. Maybe a partial mock of QueryExecutorBean would be better
// setup principal mock
String userDN = "CN=Guy Some Other soguy, OU=MY_SUBDIVISION, OU=MY_DIVISION, O=ORG, C=US";
String[] auths = new String[2];
auths[0] = "PRIVATE";
auths[1] = "PUBLIC";
QueryImpl q = new QueryImpl();
q.setBeginDate(beginDate);
q.setEndDate(beginDate);
q.setExpirationDate(expirationDate);
q.setPagesize(pagesize);
q.setParameters(parameters);
q.setQuery(query);
q.setQueryAuthorizations(StringUtils.join(auths, ","));
q.setQueryLogicName(queryLogicName);
q.setUserDN(userDN);
q.setId(UUID.randomUUID());
@SuppressWarnings("rawtypes") QueryLogic logic = createMock(BaseQueryLogic.class);
MultivaluedMap<String, String> p = new MultivaluedMapImpl<>();
p.putSingle(QueryParameters.QUERY_AUTHORIZATIONS, "");
p.putSingle(QueryParameters.QUERY_BEGIN, QueryParametersImpl.formatDate(beginDate));
p.putSingle(QueryParameters.QUERY_END, QueryParametersImpl.formatDate(beginDate));
p.putSingle(QueryParameters.QUERY_EXPIRATION, QueryParametersImpl.formatDate(expirationDate));
p.putSingle(QueryParameters.QUERY_NAME, queryName);
p.putSingle(QueryParameters.QUERY_PAGESIZE, Integer.toString(pagesize));
p.putSingle(QueryParameters.QUERY_STRING, query);
p.putSingle(QueryParameters.QUERY_PERSISTENCE, persist.name());
p.putSingle(ColumnVisibilitySecurityMarking.VISIBILITY_MARKING, "PRIVATE|PUBLIC");
InMemoryInstance instance = new InMemoryInstance();
Connector c = instance.getConnector("root", new PasswordToken(""));
QueryParameters qp = new QueryParametersImpl();
MultivaluedMap<String, String> optionalParameters = new MultivaluedMapImpl<>();
optionalParameters.putAll(qp.getUnknownParameters(p));
DatawaveUser user = new DatawaveUser(SubjectIssuerDNPair.of(userDN, "<CN=MY_CA, OU=MY_SUBDIVISION, OU=MY_DIVISION, O=ORG, C=US>"), UserType.USER, Arrays.asList(auths), null, null, 0L);
DatawavePrincipal principal = new DatawavePrincipal(Collections.singletonList(user));
String[] dns = principal.getDNs();
Arrays.sort(dns);
List<String> dnList = Arrays.asList(dns);
PowerMock.resetAll();
EasyMock.expect(ctx.getCallerPrincipal()).andReturn(principal).anyTimes();
suppress(constructor(QueryParametersImpl.class));
EasyMock.expect(persister.create(userDN, dnList, (SecurityMarking) Whitebox.getField(bean.getClass(), "marking").get(bean), queryLogicName, (QueryParameters) Whitebox.getField(bean.getClass(), "qp").get(bean), optionalParameters)).andReturn(q);
EasyMock.expect(queryLogicFactory.getQueryLogic(queryLogicName, principal)).andReturn(logic);
EasyMock.expect(logic.getRequiredQueryParameters()).andReturn(Collections.EMPTY_SET);
EasyMock.expect(logic.containsDNWithAccess(dnList)).andReturn(true);
EasyMock.expect(logic.getMaxPageSize()).andReturn(0);
EasyMock.expect(logic.getAuditType(EasyMock.<Query>anyObject())).andReturn(AuditType.ACTIVE).anyTimes();
EasyMock.expect(logic.getSelectors(anyObject())).andReturn(null);
Map<String, String> auditParams = new HashMap<>();
auditParams.put(QueryParameters.QUERY_STRING, p.getFirst(QueryParameters.QUERY_STRING));
auditParams.put(AuditParameters.USER_DN, userDN);
auditParams.put(AuditParameters.QUERY_SECURITY_MARKING_COLVIZ, "PRIVATE|PUBLIC");
auditParams.put(AuditParameters.QUERY_AUDIT_TYPE, AuditType.ACTIVE.name());
auditParams.put(AuditParameters.QUERY_LOGIC_CLASS, "EventQueryLogic");
EasyMock.expect(auditService.audit(eq(auditParams))).andReturn(null);
logic.close();
EasyMock.expectLastCall();
persister.remove(anyObject(Query.class));
PowerMock.replayAll();
bean.createQuery(queryLogicName, p);
PowerMock.verifyAll();
}
use of datawave.webservice.query.QueryParameters in project datawave by NationalSecurityAgency.
the class QueryExecutorBeanTest method testCloseActuallyCloses.
@SuppressWarnings("unchecked")
@Test(timeout = 5000)
public void testCloseActuallyCloses() throws Exception {
QueryImpl q = createNewQuery();
final MultivaluedMap<String, String> queryParameters = createNewQueryParameterMap();
queryParameters.putSingle(QueryParameters.QUERY_LOGIC_NAME, "EventQueryLogic");
final Thread createQuery = new Thread(() -> {
try {
bean.createQuery("EventQueryLogic", queryParameters);
} catch (Exception e) {
// ok if we fail the call
log.debug("createQuery terminated with " + e);
}
});
final Throwable[] createQueryException = { null };
createQuery.setUncaughtExceptionHandler((t, e) -> createQueryException[0] = e);
@SuppressWarnings("rawtypes") QueryLogic logic = createMock(BaseQueryLogic.class);
DatawaveUser user = new DatawaveUser(SubjectIssuerDNPair.of(userDN, "<CN=MY_CA, OU=MY_SUBDIVISION, OU=MY_DIVISION, O=ORG, C=US>"), UserType.USER, Arrays.asList(auths), null, null, 0L);
DatawavePrincipal principal = new DatawavePrincipal(Collections.singletonList(user));
principal.getShortName();
String[] dns = principal.getDNs();
Arrays.sort(dns);
List<String> dnList = Arrays.asList(dns);
InMemoryInstance instance = new InMemoryInstance();
Connector c = instance.getConnector("root", new PasswordToken(""));
MultivaluedMap<String, String> optionalParameters = createNewQueryParameters(q, queryParameters);
PowerMock.resetAll();
EasyMock.expect(ctx.getCallerPrincipal()).andReturn(principal).anyTimes();
EasyMock.expect(logic.getAuditType(null)).andReturn(AuditType.NONE);
EasyMock.expect(persister.create(principal.getUserDN().subjectDN(), dnList, Whitebox.getInternalState(bean, SecurityMarking.class), queryLogicName, Whitebox.getInternalState(bean, QueryParameters.class), optionalParameters)).andReturn(q);
EasyMock.expect(persister.findById(EasyMock.anyString())).andReturn(null).anyTimes();
EasyMock.expect(connectionFactory.getTrackingMap(anyObject())).andReturn(Maps.newHashMap()).anyTimes();
BaseQueryMetric metric = new QueryMetricFactoryImpl().createMetric();
metric.populate(q);
EasyMock.expectLastCall();
metric.setQueryType(RunningQuery.class.getSimpleName());
metric.setLifecycle(Lifecycle.DEFINED);
System.out.println(metric);
Set<Prediction> predictions = new HashSet<>();
predictions.add(new Prediction("source", 1));
EasyMock.expect(predictor.predict(metric)).andReturn(predictions);
connectionRequestBean.requestBegin(q.getId().toString());
EasyMock.expectLastCall();
EasyMock.expect(connectionFactory.getConnection(eq("connPool1"), anyObject(), anyObject())).andReturn(c).anyTimes();
connectionRequestBean.requestEnd(q.getId().toString());
EasyMock.expectLastCall();
connectionFactory.returnConnection(c);
EasyMock.expectLastCall();
EasyMock.expect(queryLogicFactory.getQueryLogic(queryLogicName, principal)).andReturn(logic);
EasyMock.expect(logic.getRequiredQueryParameters()).andReturn(Collections.emptySet());
EasyMock.expect(logic.getConnectionPriority()).andReturn(AccumuloConnectionFactory.Priority.NORMAL).atLeastOnce();
EasyMock.expect(logic.containsDNWithAccess(dnList)).andReturn(true);
EasyMock.expect(logic.getMaxPageSize()).andReturn(0);
EasyMock.expect(logic.getAuditType(q)).andReturn(AuditType.NONE);
EasyMock.expect(logic.getConnPoolName()).andReturn("connPool1");
EasyMock.expect(logic.getResultLimit(eq(q.getDnList()))).andReturn(-1L).anyTimes();
EasyMock.expect(logic.getMaxResults()).andReturn(-1L).anyTimes();
EasyMock.expect(connectionRequestBean.cancelConnectionRequest(q.getId().toString(), principal)).andReturn(false).anyTimes();
connectionFactory.returnConnection(EasyMock.isA(Connector.class));
final AtomicBoolean initializeLooping = new AtomicBoolean(false);
// During initialize, mark that we get here, and then sleep
final IAnswer<GenericQueryConfiguration> initializeAnswer = () -> {
initializeLooping.set(true);
try {
while (true) {
Thread.sleep(1000);
log.debug("Initialize: woke up");
}
} catch (InterruptedException e) {
throw new QueryException("EXPECTED EXCEPTION: initialize interrupted");
}
};
EasyMock.expect(logic.initialize(anyObject(Connector.class), anyObject(Query.class), anyObject(Set.class))).andAnswer(initializeAnswer);
EasyMock.expect(logic.getCollectQueryMetrics()).andReturn(Boolean.FALSE);
// On close, interrupt the thread to simulate the ScannerFactory cleaning up
final IAnswer<Object> closeAnswer = () -> {
if (null != createQuery) {
log.debug("createQuery thread is not null. interrupting");
createQuery.interrupt();
} else {
log.debug("createQuery thread is null. not interrupting");
}
return null;
};
logic.close();
EasyMock.expectLastCall().andAnswer(closeAnswer).anyTimes();
// Make the QueryLogic mock not threadsafe, otherwise it will be blocked infinitely
// trying to get the lock on the infinite loop
EasyMock.makeThreadSafe(logic, false);
metrics.updateMetric(EasyMock.isA(QueryMetric.class));
PowerMock.replayAll();
try {
createQuery.start();
// Wait for the create call to get to initialize
while (!initializeLooping.get()) {
if (!createQuery.isAlive() && !initializeLooping.get()) {
Assert.fail("createQuery thread died before reaching initialize: " + createQueryException[0]);
}
Thread.sleep(50);
}
// initialize has not completed yet so it will not appear in the cache
Object cachedRunningQuery = cache.get(q.getId().toString());
Assert.assertNull(cachedRunningQuery);
Pair<QueryLogic<?>, Connector> pair = qlCache.poll(q.getId().toString());
Assert.assertNotNull(pair);
Assert.assertEquals(logic, pair.getFirst());
Assert.assertEquals(c, pair.getSecond());
// Have to add these back because poll was destructive
qlCache.add(q.getId().toString(), principal.getShortName(), pair.getFirst(), pair.getSecond());
// Call close
bean.close(q.getId().toString());
// Make sure that it's gone from the qlCache
pair = qlCache.poll(q.getId().toString());
Assert.assertNull("Still found an entry in the qlCache: " + pair, pair);
// Should have already joined by now, but just to be sure
createQuery.join();
} finally {
if (null != createQuery && createQuery.isAlive()) {
createQuery.interrupt();
}
}
}
use of datawave.webservice.query.QueryParameters in project datawave by NationalSecurityAgency.
the class ExtendedQueryExecutorBeanTest method testDefineQuery_UncheckedException.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(expected = IllegalArgumentException.class)
public void testDefineQuery_UncheckedException() throws Exception {
// Set local test input
String queryLogicName = "queryLogicName";
String query = "query";
String queryName = "queryName";
String queryVisibility = "A&B";
long currentTime = System.currentTimeMillis();
Date beginDate = new Date(currentTime - 5000);
Date endDate = new Date(currentTime - 1000);
String queryAuthorizations = "AUTH_1";
Date expirationDate = new Date(currentTime + 10000);
int pagesize = 10;
int pageTimeout = -1;
Long maxResultsOverride = null;
QueryPersistence persistenceMode = QueryPersistence.PERSISTENT;
String userName = "userName";
String userSid = "userSid";
String userDN = "userdn";
SubjectIssuerDNPair userDNpair = SubjectIssuerDNPair.of(userDN);
boolean trace = false;
List<String> dnList = Collections.singletonList(userDN);
UUID queryId = UUID.randomUUID();
MultivaluedMap<String, String> queryParameters = new MultivaluedMapImpl<>();
queryParameters.putAll(QueryParametersImpl.paramsToMap(null, query, queryName, queryVisibility, beginDate, endDate, queryAuthorizations, expirationDate, pagesize, pageTimeout, maxResultsOverride, persistenceMode, null, trace));
queryParameters.putSingle("valid", "param");
ColumnVisibilitySecurityMarking marking = new ColumnVisibilitySecurityMarking();
marking.validate(queryParameters);
QueryParameters qp = new QueryParametersImpl();
qp.validate(queryParameters);
MultivaluedMap<String, String> op = new MultivaluedMapImpl<>();
op.putAll(qp.getUnknownParameters(queryParameters));
op.putSingle(PrivateAuditConstants.LOGIC_CLASS, queryLogicName);
op.putSingle(PrivateAuditConstants.COLUMN_VISIBILITY, queryVisibility);
op.putSingle(PrivateAuditConstants.USER_DN, userDNpair.subjectDN());
// Set expectations
queryLogic1.validate(queryParameters);
expect(this.context.getCallerPrincipal()).andReturn(this.principal).anyTimes();
expect(this.principal.getName()).andReturn(userName);
expect(this.principal.getShortName()).andReturn(userSid);
expect(this.principal.getDNs()).andReturn(new String[] { userDN });
expect(this.principal.getProxyServers()).andReturn(new ArrayList<>(0));
expect(this.principal.getAuthorizations()).andReturn((Collection) Arrays.asList(Arrays.asList(queryAuthorizations)));
expect(this.principal.getUserDN()).andReturn(userDNpair);
expect(persister.create(eq(userDNpair.subjectDN()), eq(dnList), eq(marking), eq(queryLogicName), eq(qp), eq(op))).andReturn(this.query);
expect(this.query.getId()).andReturn(queryId).times(3);
expect(this.queryLogicFactory.getQueryLogic(queryLogicName, principal)).andReturn((QueryLogic) this.queryLogic1);
expect(this.queryLogic1.getMaxPageSize()).andReturn(100).times(2);
expect(this.traceInfos.get(userSid)).andReturn(new ArrayList<>(0));
expect(this.traceInfos.get(null)).andReturn(Arrays.asList(PatternWrapper.wrap(query)));
PowerMock.mockStaticPartial(Trace.class, "start");
expect(Trace.start("query:define")).andReturn(this.span);
expect(this.queryLogic1.getConnectionPriority()).andThrow(ILLEGAL_STATE_EXCEPTION);
// TODO: 1.8.1: no longer done
// expect(this.span.parent()).andReturn(this.span);
// expect(this.span.parent()).andReturn(this.span);
this.span.stop();
// Run the test
PowerMock.replayAll();
try {
QueryExecutorBean subject = new QueryExecutorBean();
setInternalState(subject, EJBContext.class, context);
setInternalState(subject, Persister.class, persister);
setInternalState(subject, QueryLogicFactory.class, queryLogicFactory);
setInternalState(subject, QueryExpirationConfiguration.class, queryExpirationConf);
setInternalState(subject, Multimap.class, traceInfos);
setInternalState(subject, SecurityMarking.class, new ColumnVisibilitySecurityMarking());
setInternalState(subject, QueryParameters.class, new QueryParametersImpl());
setInternalState(subject, QueryMetricFactory.class, new QueryMetricFactoryImpl());
subject.defineQuery(queryLogicName, queryParameters);
} finally {
PowerMock.verifyAll();
}
}
Aggregations