use of org.opennms.core.criteria.Criteria in project opennms by OpenNMS.
the class CriteriaBuilderSearchVisitor method visit.
@Override
public void visit(SearchCondition<Q> sc) {
PrimitiveStatement statement = sc.getStatement();
if (statement != null) {
if (statement.getProperty() != null) {
String name = getRealPropertyName(statement.getProperty());
// TODO: Figure out how to use validators at some point
// validatePropertyValue(name, originalValue);
// Introspect the property type
ClassValue clsValue = getPrimitiveFieldClass(statement, name, statement.getValue().getClass(), statement.getValueType(), statement.getValue());
// If the property value is a String
boolean isWildcard = false;
if (String.class.equals(clsValue.getCls())) {
// And if it's a FIQL wildcard
if (SearchUtils.containsWildcard((String) clsValue.getValue())) {
// Then mark it as a wildcard and replace the * wildcards with % wildcards
isWildcard = true;
clsValue.setValue(SearchUtils.toSqlWildcardString((String) clsValue.getValue(), false));
}
}
final Object value;
// Check to see if we have any criteria behaviors for this search term
if (m_criteriaBehaviors != null && m_criteriaBehaviors.containsKey(name)) {
// TODO: Change CriteriaBehaviors so that they can remap prefixes
// so that we don't have to put every joined property into m_criteriaMapping
CriteriaBehavior<?> behavior = m_criteriaBehaviors.get(name);
// Convert the query bean property name to the Criteria property name
// if necessary
name = behavior.getPropertyName() == null ? name : behavior.getPropertyName();
// If we're using CriteriaBehaviors, assume that the value is a String
// and convert it to the value that will be used in the Criteria
value = NULL_VALUE.equals((String) clsValue.getValue()) ? null : behavior.convert((String) clsValue.getValue());
// Execute any beforeVisit() actions for this query term such as adding
// additional JOIN aliases
behavior.beforeVisit(m_criteriaBuilder, value, sc.getConditionType(), isWildcard);
// If the behavior indicates that we should skip this search term, then return
if (behavior.shouldSkipProperty(sc.getConditionType(), isWildcard)) {
return;
}
} else {
value = clsValue.getValue();
}
switch(sc.getConditionType()) {
case EQUALS:
if (isWildcard) {
m_criteriaBuilder.like(name, value);
} else {
if (value == null || NULL_VALUE.equals(value) || NULL_DATE_VALUE.equals(value)) {
m_criteriaBuilder.isNull(name);
} else {
m_criteriaBuilder.eq(name, value);
}
}
break;
case NOT_EQUALS:
if (isWildcard) {
m_criteriaBuilder.not().like(name, value);
} else {
if (value == null || NULL_VALUE.equals(value) || NULL_DATE_VALUE.equals(value)) {
m_criteriaBuilder.isNotNull(name);
} else {
// Match any rows that do not match the value or are null
m_criteriaBuilder.or(Restrictions.ne(name, value), Restrictions.isNull(name));
}
}
break;
case LESS_THAN:
// TODO: Check for null?
m_criteriaBuilder.lt(name, value);
break;
case GREATER_THAN:
// TODO: Check for null?
m_criteriaBuilder.gt(name, value);
break;
case LESS_OR_EQUALS:
// TODO: Check for null?
m_criteriaBuilder.le(name, value);
break;
case GREATER_OR_EQUALS:
// TODO: Check for null?
m_criteriaBuilder.ge(name, value);
break;
case OR:
case AND:
case CUSTOM:
default:
}
}
} else {
List<Restriction> subRestrictions = new ArrayList<>();
for (SearchCondition<Q> condition : sc.getSearchConditions()) {
// Create a new CriteriaBuilder
CriteriaBuilder builder = null;
try {
// Try to use the same class as the outside CriteriaBuilder
builder = m_criteriaBuilder.getClass().getConstructor(Class.class).newInstance(m_class);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
LOG.warn("Could not create " + m_criteriaBuilder.getClass().getSimpleName() + "; falling back to CriteriaBuilder: " + e.getClass().getSimpleName() + ": " + e.getMessage());
builder = new CriteriaBuilder(m_class);
}
// Create a new visitor for the SearchCondition
CriteriaBuilderSearchVisitor<T, Q> newVisitor = new CriteriaBuilderSearchVisitor<T, Q>(builder, m_class, m_criteriaBehaviors);
// Visit the children
condition.accept(newVisitor);
Criteria newCriteria = newVisitor.getQuery().toCriteria();
// Add any aliases from the subcriteria
Collection<Alias> aliases = newCriteria.getAliases();
if (aliases != null) {
for (Alias alias : aliases) {
m_criteriaBuilder.alias(alias);
}
}
// Fetch the rendered restrictions
Collection<Restriction> restrictions = newCriteria.getRestrictions();
// If there are restrictions...
if (restrictions != null && restrictions.size() > 0) {
final Restriction subRestriction;
// If there are multiple restrictions...
if (restrictions.size() > 1) {
// Wrap them in an AND restriction
subRestriction = Restrictions.all(restrictions);
} else {
subRestriction = restrictions.iterator().next();
}
LOG.info(subRestriction.toString());
subRestrictions.add(subRestriction);
}
}
switch(sc.getConditionType()) {
case OR:
LOG.info("OR criteria");
// .or() with current Criteria
m_criteriaBuilder.or(subRestrictions.toArray(new Restriction[0]));
break;
case AND:
LOG.info("AND criteria");
// .and() with current Criteria
m_criteriaBuilder.and(subRestrictions.toArray(new Restriction[0]));
break;
default:
}
}
}
use of org.opennms.core.criteria.Criteria in project opennms by OpenNMS.
the class IfServicesRestService method updateServices.
@PUT
public Response updateServices(@Context final UriInfo uriInfo, final MultivaluedMapImpl params) {
final String status = params.getFirst("status");
if (status == null || !status.matches("(A|R|S|F)")) {
throw getException(Status.BAD_REQUEST, "Parameter status must be specified. Possible values: A (Managed), F (Forced Unmanaged), R (Rescan to Resume), S (Rescan to Suspend)");
}
final String services_csv = params.getFirst("services");
final List<String> serviceList = new ArrayList<>();
if (services_csv != null) {
for (String s : services_csv.split(",")) {
serviceList.add(s);
}
}
final Criteria c = getCriteria(uriInfo.getQueryParameters());
c.setLimit(null);
c.setOffset(null);
final OnmsMonitoredServiceList services = new OnmsMonitoredServiceList(m_serviceDao.findMatching(c));
if (services.isEmpty()) {
throw getException(Status.BAD_REQUEST, "Can't find any service matching the provided criteria: {}.", uriInfo.getQueryParameters().toString());
}
boolean modified = false;
for (OnmsMonitoredService svc : services) {
boolean proceed = false;
if (serviceList.isEmpty()) {
proceed = true;
} else {
if (serviceList.contains(svc.getServiceName())) {
proceed = true;
}
}
if (proceed) {
modified = true;
final String currentStatus = svc.getStatus();
svc.setStatus(status);
m_serviceDao.update(svc);
if ("S".equals(status) || ("A".equals(currentStatus) && "F".equals(status))) {
LOG.debug("updateServices: suspending polling for service {} on node with IP {}", svc.getServiceName(), svc.getIpAddress().getHostAddress());
// TODO ManageNodeServlet is sending this.
sendEvent(EventConstants.SERVICE_UNMANAGED_EVENT_UEI, svc);
sendEvent(EventConstants.SUSPEND_POLLING_SERVICE_EVENT_UEI, svc);
}
if ("R".equals(status) || ("F".equals(currentStatus) && "A".equals(status))) {
LOG.debug("updateServices: resuming polling for service {} on node with IP {}", svc.getServiceName(), svc.getIpAddress().getHostAddress());
sendEvent(EventConstants.RESUME_POLLING_SERVICE_EVENT_UEI, svc);
}
}
}
return modified ? Response.noContent().build() : Response.notModified().build();
}
use of org.opennms.core.criteria.Criteria in project opennms by OpenNMS.
the class OnmsRestService method applyQueryFilters.
protected static void applyQueryFilters(final MultivaluedMap<String, String> p, final CriteriaBuilder builder, final Integer defaultLimit) {
final MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.putAll(p);
builder.distinct();
builder.limit(defaultLimit);
if (params.containsKey("limit")) {
builder.limit(Integer.valueOf(params.getFirst("limit")));
params.remove("limit");
}
if (params.containsKey("offset")) {
builder.offset(Integer.valueOf(params.getFirst("offset")));
params.remove("offset");
}
if (params.containsKey("orderBy")) {
builder.clearOrder();
builder.orderBy(params.getFirst("orderBy"));
params.remove("orderBy");
if (params.containsKey("order")) {
if ("desc".equalsIgnoreCase(params.getFirst("order"))) {
builder.desc();
} else {
builder.asc();
}
params.remove("order");
}
}
if (Boolean.getBoolean("org.opennms.web.rest.enableQuery")) {
final String query = removeParameter(params, "query");
if (query != null)
builder.sql(query);
}
final String matchType;
final String match = removeParameter(params, "match");
if (match == null) {
matchType = "all";
} else {
matchType = match;
}
builder.match(matchType);
final Class<?> criteriaClass = builder.toCriteria().getCriteriaClass();
final BeanWrapper wrapper = getBeanWrapperForClass(criteriaClass);
final String comparatorParam = removeParameter(params, "comparator", "eq").toLowerCase();
final Criteria currentCriteria = builder.toCriteria();
for (final String key : params.keySet()) {
for (final String paramValue : params.get(key)) {
// the actual implementation com.sun.jersey.core.util.MultivaluedMapImpl returns a String, so this is fine in some way ...
if ("null".equalsIgnoreCase(paramValue)) {
builder.isNull(key);
} else if ("notnull".equalsIgnoreCase(paramValue)) {
builder.isNotNull(key);
} else {
Object value;
Class<?> type = Object.class;
try {
type = currentCriteria.getType(key);
} catch (final IntrospectionException e) {
LOG.debug("Unable to determine type for key {}", key);
}
if (type == null) {
type = Object.class;
}
LOG.debug("comparator = {}, key = {}, propertyType = {}", comparatorParam, key, type);
if (comparatorParam.equals("contains") || comparatorParam.equals("iplike") || comparatorParam.equals("ilike") || comparatorParam.equals("like")) {
value = paramValue;
} else {
LOG.debug("convertIfNecessary({}, {})", key, paramValue);
try {
value = wrapper.convertIfNecessary(paramValue, type);
} catch (final Throwable t) {
LOG.debug("failed to introspect (key = {}, value = {})", key, paramValue, t);
value = paramValue;
}
}
try {
final Method m = builder.getClass().getMethod(comparatorParam, String.class, Object.class);
m.invoke(builder, new Object[] { key, value });
} catch (final Throwable t) {
LOG.warn("Unable to find method for comparator: {}, key: {}, value: {}", comparatorParam, key, value, t);
}
}
}
}
}
use of org.opennms.core.criteria.Criteria in project opennms by OpenNMS.
the class JtiTelemetryIT method sendnewSuspectEvent.
public static OnmsNode sendnewSuspectEvent(Executor executor, InetSocketAddress opennmsHttp, TestEnvironment m_testEnvironment, boolean isMinion, Date startOfTest) throws ClientProtocolException, IOException {
Event minionEvent = new Event();
minionEvent.setUei("uei.opennms.org/internal/discovery/newSuspect");
minionEvent.setHost(SENDER_IP);
minionEvent.setInterface(SENDER_IP);
minionEvent.setInterfaceAddress(Inet4Address.getByName(SENDER_IP));
minionEvent.setSource("system-test");
minionEvent.setSeverity("4");
if (isMinion) {
Parm parm = new Parm();
parm.setParmName("location");
Value minion = new Value("MINION");
parm.setValue(minion);
List<Parm> parms = new ArrayList<>();
parms.add(parm);
minionEvent.setParmCollection(parms);
}
String xmlString = JaxbUtils.marshal(minionEvent);
executor.execute(Request.Post(String.format("http://%s:%d/opennms/rest/events", opennmsHttp.getAddress().getHostAddress(), opennmsHttp.getPort())).bodyString(xmlString, ContentType.APPLICATION_XML)).returnContent();
InetSocketAddress pgsql = m_testEnvironment.getServiceAddress(ContainerAlias.POSTGRES, 5432);
HibernateDaoFactory daoFactory = new HibernateDaoFactory(pgsql);
EventDao eventDao = daoFactory.getDao(EventDaoHibernate.class);
NodeDao nodeDao = daoFactory.getDao(NodeDaoHibernate.class);
Criteria criteria = new CriteriaBuilder(OnmsEvent.class).eq("eventUei", EventConstants.NEW_SUSPECT_INTERFACE_EVENT_UEI).ge("eventTime", startOfTest).eq("ipAddr", Inet4Address.getByName(SENDER_IP)).toCriteria();
await().atMost(1, MINUTES).pollInterval(10, SECONDS).until(DaoUtils.countMatchingCallable(eventDao, criteria), greaterThan(0));
final OnmsNode onmsNode = await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(DaoUtils.findMatchingCallable(nodeDao, new CriteriaBuilder(OnmsNode.class).eq("label", SENDER_IP).ge("createTime", startOfTest).toCriteria()), notNullValue());
assertNotNull(onmsNode);
if (isMinion) {
assertThat(onmsNode.getLocation().getLocationName(), is("MINION"));
}
LOG.info(" New suspect event has been sent and node has been created for IP : {}", SENDER_IP);
return onmsNode;
}
use of org.opennms.core.criteria.Criteria in project opennms by OpenNMS.
the class EnhancedLinkdServiceImpl method getSnmpNodeList.
@Override
public List<Node> getSnmpNodeList() {
final List<Node> nodes = new ArrayList<Node>();
final Criteria criteria = new Criteria(OnmsNode.class);
criteria.setAliases(Arrays.asList(new Alias[] { new Alias("ipInterfaces", "iface", JoinType.LEFT_JOIN) }));
criteria.addRestriction(new EqRestriction("type", NodeType.ACTIVE));
criteria.addRestriction(new EqRestriction("iface.isSnmpPrimary", PrimaryType.PRIMARY));
for (final OnmsNode node : m_nodeDao.findMatching(criteria)) {
nodes.add(new Node(node.getId(), node.getPrimaryInterface().getIpAddress(), node.getSysObjectId(), node.getSysName(), node.getLocation() == null ? null : node.getLocation().getLocationName()));
}
return nodes;
}
Aggregations