use of org.springframework.beans.BeanWrapper 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.springframework.beans.BeanWrapper in project opennms by OpenNMS.
the class ReportDefinitionBuilder method buildReportDefinitions.
/**
* Builds and schedules all reports enabled in the statsd-configuration.
* This method has the capability to throw a ton of exceptions, just generically throwing <code>Exception</code>
*
* @return a <code>Collection</code> of enabled reports from the statsd-configuration.
* @throws java.lang.Exception if any.
*/
public Collection<ReportDefinition> buildReportDefinitions() throws Exception {
Set<ReportDefinition> reportDefinitions = new HashSet<>();
for (StatsdPackage pkg : m_statsdConfigDao.getPackages()) {
for (PackageReport packageReport : pkg.getReports()) {
Report report = packageReport.getReport();
if (!packageReport.isEnabled()) {
LOG.debug("skipping report '{}' in package '{}' because the report is not enabled", report.getName(), pkg.getName());
continue;
}
Class<? extends AttributeStatisticVisitorWithResults> clazz;
try {
clazz = createClassForReport(report);
} catch (ClassNotFoundException e) {
throw new DataAccessResourceFailureException("Could not find class '" + report.getClassName() + "'; nested exception: " + e, e);
}
Assert.isAssignable(AttributeStatisticVisitorWithResults.class, clazz, "the class specified by class-name in the '" + report.getName() + "' report does not implement the interface " + AttributeStatisticVisitorWithResults.class.getName() + "; ");
ReportDefinition reportDef = new ReportDefinition();
reportDef.setReport(packageReport);
reportDef.setReportClass(clazz);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(reportDef);
try {
bw.setPropertyValues(packageReport.getAggregateParameters());
} catch (BeansException e) {
LOG.error("Could not set properties on report definition: {}", e.getMessage(), e);
}
reportDef.afterPropertiesSet();
reportDefinitions.add(reportDef);
}
}
return reportDefinitions;
}
use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.
the class RestUtils method setBeanProperties.
/**
* <p>Use Spring's {@link PropertyAccessorFactory} to set values on the specified bean.
* This call registers several {@link PropertyEditor} classes to properly convert
* values.</p>
*
* <ul>
* <li>{@link StringXmlCalendarPropertyEditor}</li>
* <li>{@link ISO8601DateEditor}</li>
* <li>{@link InetAddressTypeEditor}</li>
* <li>{@link OnmsSeverityEditor}</li>
* <li>{@link PrimaryTypeEditor}</li>
* </ul>
*
* @param bean
* @param properties
*/
public static void setBeanProperties(final Object bean, final MultivaluedMap<String, String> properties) {
final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
wrapper.registerCustomEditor(XMLGregorianCalendar.class, new StringXmlCalendarPropertyEditor());
wrapper.registerCustomEditor(Date.class, new ISO8601DateEditor());
wrapper.registerCustomEditor(InetAddress.class, new InetAddressTypeEditor());
wrapper.registerCustomEditor(OnmsSeverity.class, new OnmsSeverityEditor());
wrapper.registerCustomEditor(PrimaryType.class, new PrimaryTypeEditor());
for (final String key : properties.keySet()) {
final String propertyName = convertNameToPropertyName(key);
if (wrapper.isWritableProperty(propertyName)) {
final String stringValue = properties.getFirst(key);
Object value = convertIfNecessary(wrapper, propertyName, stringValue);
wrapper.setPropertyValue(propertyName, value);
}
}
}
use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.
the class AbstractXmlCollectionHandler method parseString.
/**
* Parses the string.
*
* <p>Valid placeholders are:</p>
* <ul>
* <li><b>ipAddr|ipAddress</b>, The Node IP Address</li>
* <li><b>step</b>, The Collection Step in seconds</li>
* <li><b>nodeId</b>, The Node ID</li>
* <li><b>nodeLabel</b>, The Node Label</li>
* <li><b>foreignId</b>, The Node Foreign ID</li>
* <li><b>foreignSource</b>, The Node Foreign Source</li>
* <li>Any asset property defined on the node.</li>
* </ul>
*
* @param reference the reference
* @param unformattedString the unformatted string
* @param node the node
* @param ipAddress the IP address
* @param collectionStep the collection step
* @param parameters the service parameters
* @return the string
* @throws IllegalArgumentException the illegal argument exception
*/
protected static String parseString(final String reference, final String unformattedString, final OnmsNode node, final String ipAddress, final Integer collectionStep, final Map<String, String> parameters) throws IllegalArgumentException {
if (unformattedString == null || node == null)
return null;
String formattedString = unformattedString.replaceAll("[{](?i)(ipAddr|ipAddress)[}]", ipAddress);
formattedString = formattedString.replaceAll("[{](?i)step[}]", collectionStep.toString());
formattedString = formattedString.replaceAll("[{](?i)nodeId[}]", node.getNodeId());
if (node.getLabel() != null)
formattedString = formattedString.replaceAll("[{](?i)nodeLabel[}]", node.getLabel());
if (node.getForeignId() != null)
formattedString = formattedString.replaceAll("[{](?i)foreignId[}]", node.getForeignId());
if (node.getForeignSource() != null)
formattedString = formattedString.replaceAll("[{](?i)foreignSource[}]", node.getForeignSource());
for (Map.Entry<String, String> entry : parameters.entrySet()) {
formattedString = formattedString.replaceAll("[{]parameter:" + entry.getKey() + "[}]", entry.getValue());
}
if (node.getAssetRecord() != null) {
BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord());
for (PropertyDescriptor p : wrapper.getPropertyDescriptors()) {
Object obj = wrapper.getPropertyValue(p.getName());
if (obj != null) {
String objStr = obj.toString();
try {
// NMS-7381 - if pulling from asset info you'd expect to not have to encode reserved words yourself.
objStr = URLEncoder.encode(obj.toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
formattedString = formattedString.replaceAll("[{](?i)" + p.getName() + "[}]", objStr);
}
}
}
if (formattedString.matches(".*[{].+[}].*"))
throw new IllegalArgumentException("The " + reference + " " + formattedString + " contains unknown placeholders.");
return formattedString;
}
use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.
the class EventBuilder method setField.
/**
* <p>setField</p>
*
* @param name a {@link java.lang.String} object.
* @param val a {@link java.lang.String} object.
*/
public void setField(final String name, final String val) {
if (name.equals("eventparms")) {
String[] parts = val.split(";");
for (String part : parts) {
String[] pair = part.split("=");
addParam(pair[0], pair[1].replaceFirst("[(]\\w+,\\w+[)]", ""));
}
} else {
final BeanWrapper w = PropertyAccessorFactory.forBeanPropertyAccess(m_event);
try {
w.setPropertyValue(name, val);
} catch (final BeansException e) {
LOG.warn("Could not set field on event: {}", name, e);
}
}
}
Aggregations