/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2008-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.rest;
import java.beans.IntrospectionException;
import java.lang.reflect.Method;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.datatype.XMLGregorianCalendar;
import org.opennms.core.criteria.Criteria;
import org.opennms.core.criteria.CriteriaBuilder;
import org.opennms.core.utils.LogUtils;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.model.OnmsSeverity;
import org.opennms.netmgt.model.OnmsSeverityEditor;
import org.opennms.netmgt.model.PrimaryType;
import org.opennms.netmgt.model.PrimaryTypeEditor;
import org.opennms.netmgt.provision.persist.StringXmlCalendarPropertyEditor;
import org.opennms.web.rest.support.InetAddressTypeEditor;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyAccessorFactory;
import com.sun.jersey.core.util.MultivaluedMapImpl;
/**
* <p>OnmsRestService class.</p>
*
* @author ranger
* @version $Id: $
* @since 1.8.1
*/
public class OnmsRestService {
private final ReentrantReadWriteLock m_globalLock = new ReentrantReadWriteLock();
private final Lock m_readLock = m_globalLock.readLock();
private final Lock m_writeLock = m_globalLock.writeLock();
protected static final int DEFAULT_LIMIT = 10;
protected enum ComparisonOperation { EQ, NE, ILIKE, LIKE, IPLIKE, GT, LT, GE, LE, CONTAINS }
/**
* <p>Constructor for OnmsRestService.</p>
*/
public OnmsRestService() {
super();
}
protected void readLock() {
m_readLock.lock();
}
protected void readUnlock() {
if (m_globalLock.getReadHoldCount() > 0) {
m_readLock.unlock();
}
}
protected void writeLock() {
if (m_globalLock.getWriteHoldCount() == 0) {
while (m_globalLock.getReadHoldCount() > 0) {
m_readLock.unlock();
}
m_writeLock.lock();
}
}
protected void writeUnlock() {
if (m_globalLock.getWriteHoldCount() > 0) {
m_writeLock.unlock();
}
}
protected void applyQueryFilters(final MultivaluedMap<String,String> p, final CriteriaBuilder builder) {
final MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.putAll(p);
builder.distinct();
builder.limit(DEFAULT_LIMIT);
// not sure why we remove this, but that's what the old query filter code did, I presume there's a reason :)
params.remove("_dc");
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");
}
// Is this necessary anymore? setLimitOffset() comments implies it's for Ext-JS.
if (params.containsKey("start")) {
builder.offset(Integer.valueOf(params.getFirst("start")));
params.remove("start");
}
if(params.containsKey("orderBy")) {
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");
}
}
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)) {
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) {
LogUtils.debugf(this, "Unable to determine type for key %s", key);
}
if (type == null) {
type = Object.class;
}
LogUtils.warnf(this, "comparator = %s, key = %s, propertyType = %s", comparatorParam, key, type);
if (comparatorParam.equals("contains") || comparatorParam.equals("iplike") || comparatorParam.equals("ilike") || comparatorParam.equals("like")) {
value = paramValue;
} else {
LogUtils.debugf(this, "convertIfNecessary(%s, %s)", key, paramValue);
try {
value = wrapper.convertIfNecessary(paramValue, type);
} catch (final Throwable t) {
LogUtils.debugf(this, t, "failed to introspect (key = %s, value = %s)", key, paramValue);
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) {
LogUtils.warnf(this, t, "Unable to find method for comparator: %s, key: %s, value: %s", comparatorParam, key, value);
}
}
}
}
}
protected BeanWrapper getBeanWrapperForClass(final Class<?> criteriaClass) {
final BeanWrapper wrapper = new BeanWrapperImpl(criteriaClass);
wrapper.registerCustomEditor(XMLGregorianCalendar.class, new StringXmlCalendarPropertyEditor());
wrapper.registerCustomEditor(java.util.Date.class, new ISO8601DateEditor());
wrapper.registerCustomEditor(java.net.InetAddress.class, new InetAddressTypeEditor());
wrapper.registerCustomEditor(OnmsSeverity.class, new OnmsSeverityEditor());
wrapper.registerCustomEditor(PrimaryType.class, new PrimaryTypeEditor());
return wrapper;
}
protected String removeParameter(final MultivaluedMap<java.lang.String, java.lang.String> params, final String key) {
if (params.containsKey(key)) {
final String value = params.getFirst(key);
params.remove(key);
return value;
} else {
return null;
}
}
protected String removeParameter(final MultivaluedMap<java.lang.String, java.lang.String> params, final String key, final String defaultValue) {
final String value = removeParameter(params, key);
if (value == null) {
return defaultValue;
} else {
return value;
}
}
@SuppressWarnings("unchecked")
private Object convertIfNecessary(final BeanWrapper wrapper, final String key, final String stringValue) {
LogUtils.debugf(this, "convertIfNecessary(%s, %s)", key, stringValue);
return wrapper.convertIfNecessary(stringValue, wrapper.getPropertyType(key));
}
/**
* <p>throwException</p>
*
* @param status a {@link javax.ws.rs.core.Response.Status} object.
* @param msg a {@link java.lang.String} object.
* @param <T> a T object.
* @return a T object.
*/
protected <T> WebApplicationException getException(final Status status, final String msg) throws WebApplicationException {
log().error(msg);
return new WebApplicationException(Response.status(status).type(MediaType.TEXT_PLAIN).entity(msg).build());
}
protected <T> WebApplicationException getException(Status status, Throwable t) throws WebApplicationException {
log().error(t.getMessage(), t);
return new WebApplicationException(Response.status(status).type(MediaType.TEXT_PLAIN).entity(t.getMessage()).build());
}
/**
* <p>log</p>
*
* @return a {@link org.opennms.core.utils.ThreadCategory} object.
*/
protected ThreadCategory log() {
return ThreadCategory.getInstance(getClass());
}
/**
* Convert a column name with underscores to the corresponding property name using "camel case". A name
* like "customer_number" would match a "customerNumber" property name.
*
* @param name the column name to be converted
* @return the name using "camel case"
*/
public static String convertNameToPropertyName(String name) {
StringBuffer result = new StringBuffer();
boolean nextIsUpper = false;
if (name != null && name.length() > 0) {
if (name.length() > 1 && (name.substring(1, 2).equals("_") || (name.substring(1, 2).equals("-")))) {
result.append(name.substring(0, 1).toUpperCase());
} else {
result.append(name.substring(0, 1).toLowerCase());
}
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
if (s.equals("_") || s.equals("-")) {
nextIsUpper = true;
} else {
if (nextIsUpper) {
result.append(s.toUpperCase());
nextIsUpper = false;
} else {
result.append(s.toLowerCase());
}
}
}
}
return result.toString();
}
/**
* <p>setProperties</p>
*
* @param params a {@link org.opennms.web.rest.MultivaluedMapImpl} object.
* @param req a {@link java.lang.Object} object.
*/
protected void setProperties(final org.opennms.web.rest.MultivaluedMapImpl params, final Object req) {
final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(req);
wrapper.registerCustomEditor(XMLGregorianCalendar.class, new StringXmlCalendarPropertyEditor());
wrapper.registerCustomEditor(java.util.Date.class, new ISO8601DateEditor());
wrapper.registerCustomEditor(java.net.InetAddress.class, new InetAddressTypeEditor());
wrapper.registerCustomEditor(OnmsSeverity.class, new OnmsSeverityEditor());
wrapper.registerCustomEditor(PrimaryType.class, new PrimaryTypeEditor());
for(final String key : params.keySet()) {
final String propertyName = convertNameToPropertyName(key);
if (wrapper.isWritableProperty(propertyName)) {
Object value = null;
final String stringValue = params.getFirst(key);
value = convertIfNecessary(wrapper, propertyName, stringValue);
wrapper.setPropertyValue(propertyName, value);
}
}
}
}