diff options
| author | Mike McCune <mmccune@gibson.pdx.redhat.com> | 2009-06-26 11:35:52 -0700 |
|---|---|---|
| committer | Mike McCune <mmccune@gibson.pdx.redhat.com> | 2009-06-26 11:37:45 -0700 |
| commit | eddf24b91f96effed75f52e6e87ba564279481b4 (patch) | |
| tree | 94c06b840718bca1e88a448d23fc533d573a33ab /proxy/code/src | |
| parent | 2ab21a6332fa4c39fa543c970d90279d6b316be8 (diff) | |
first cut at an API layer and some auth
Diffstat (limited to 'proxy/code/src')
9 files changed, 847 insertions, 8 deletions
diff --git a/proxy/code/src/org/fedoraproject/candlepin/api/ApiHandler.java b/proxy/code/src/org/fedoraproject/candlepin/api/ApiHandler.java new file mode 100644 index 0000000..4f127b3 --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/api/ApiHandler.java @@ -0,0 +1,74 @@ +package org.fedoraproject.candlepin.api; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; + +import org.fedoraproject.candlepin.model.BaseModel; +import org.fedoraproject.candlepin.model.ObjectFactory; +import org.fedoraproject.candlepin.model.Organization; +import org.fedoraproject.candlepin.model.User; + +public class ApiHandler { + + private static ApiHandler instance = new ApiHandler(); + private Set authTokens; + + /** + * Logger for this class + */ + private static final Logger logger = Logger.getLogger(ApiHandler.class); + + private ApiHandler() { + authTokens = new HashSet(); + } + + public static ApiHandler get() { + return instance; + } + + /** + * Auth + */ + public String login(String login, String password) { + User u = (User) ObjectFactory.get(). + lookupByFieldName(User.class, "login", login); + if (u == null) { + return null; + } + if (u.getPassword().equals(password)) { + String newtoken = BaseModel.generateUUID(); + authTokens.add(newtoken); + return newtoken; + } + else { + return null; + } + } + + private void checkToken(String token) throws AuthenticationException { + if (!authTokens.contains(token)) { + throw new AuthenticationException("token not valid: " + token); + } + } + + /** Organizations */ + + /** Fetch an org + * + */ + public Organization getOrg(String authToken, String uuid) { + checkToken(authToken); + logger.debug("getOrg(String) - start: " + uuid); + Organization retval = (Organization) ObjectFactory.get() + .lookupByUUID(Organization.class, uuid); + if (logger.isDebugEnabled()) { + logger.debug("getOrg(String) - end. returning: " + retval); + } + return retval; + } + +} diff --git a/proxy/code/src/org/fedoraproject/candlepin/api/AuthenticationException.java b/proxy/code/src/org/fedoraproject/candlepin/api/AuthenticationException.java new file mode 100644 index 0000000..f7b318e --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/api/AuthenticationException.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2009 Red Hat, Inc. + * + * This software is licensed to you under the GNU General Public License, + * version 2 (GPLv2). There is NO WARRANTY for this software, express or + * implied, including the implied warranties of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 + * along with this software; if not, see + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * Red Hat trademarks are not licensed under GPLv2. No permission is + * granted to use or replicate Red Hat trademarks that are incorporated + * in this software or its documentation. + */ +package org.fedoraproject.candlepin.api; + +/** + * @author mmccune + * + */ +public class AuthenticationException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * @param message + */ + public AuthenticationException(String message) { + super(message); + } + +} diff --git a/proxy/code/src/org/fedoraproject/candlepin/api/test/ApiHandlerTest.java b/proxy/code/src/org/fedoraproject/candlepin/api/test/ApiHandlerTest.java new file mode 100644 index 0000000..5587a04 --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/api/test/ApiHandlerTest.java @@ -0,0 +1,60 @@ +/** + * + */ +package org.fedoraproject.candlepin.api.test; + +import org.fedoraproject.candlepin.api.ApiHandler; +import org.fedoraproject.candlepin.model.BaseModel; +import org.fedoraproject.candlepin.model.ObjectFactory; +import org.fedoraproject.candlepin.model.Organization; +import org.fedoraproject.candlepin.model.User; + +import junit.framework.TestCase; + +/** + * @author mmccune + * + */ +public class ApiHandlerTest extends TestCase { + + public void testAuthentication() throws Exception { + User u = new User(); + u.setLogin("admin"); + u.setPassword("password"); + + ObjectFactory.get().store(u); + + ApiHandler handler = ApiHandler.get(); + String token = handler.login(u.getLogin(), "bad-password"); + assertNull(token); + token = handler.login(u.getLogin(), u.getPassword()); + assertNotNull(token); + } + + public void testLookupOrg() throws Exception { + Organization o = new Organization(BaseModel.generateUUID()); + ObjectFactory.get().store(o); + + User u = new User(); + u.setLogin("admin"); + u.setPassword("password"); + ObjectFactory.get().store(u); + + String token = ApiHandler.get().login(u.getLogin(), u.getPassword()); + + Organization lookedup = ApiHandler.get().getOrg(token, "BAD-UUID-NOTFOUND"); + assertNull(lookedup); + lookedup = ApiHandler.get().getOrg(token, o.getUuid()); + assertNotNull(lookedup); + + // Check bad token + boolean failed = false; + try { + lookedup = ApiHandler.get().getOrg("BAD-TOKEN", o.getUuid()); + } catch (Exception e) { + failed = true; + } + assertTrue(failed); + + } +} diff --git a/proxy/code/src/org/fedoraproject/candlepin/model/ObjectFactory.java b/proxy/code/src/org/fedoraproject/candlepin/model/ObjectFactory.java index 3571ac3..38d028d 100644 --- a/proxy/code/src/org/fedoraproject/candlepin/model/ObjectFactory.java +++ b/proxy/code/src/org/fedoraproject/candlepin/model/ObjectFactory.java @@ -16,6 +16,12 @@ package org.fedoraproject.candlepin.model; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.fedoraproject.candlepin.util.MethodUtil; /** * @author mmccune @@ -24,8 +30,11 @@ import java.lang.reflect.InvocationTargetException; public class ObjectFactory { private static ObjectFactory instance = new ObjectFactory(); + private Map objects; + private ObjectFactory() { + objects = new HashMap(); } public static ObjectFactory get() { @@ -38,10 +47,34 @@ public class ObjectFactory { * @return Organization */ public BaseModel lookupByUUID(Class<?> clazz, String uuid) { - BaseModel retval = (BaseModel) callNewMethod(clazz.getName(), - (Object[]) null); - retval.setUuid(uuid); - return retval; + return (BaseModel) lookupByFieldName(clazz, "uuid", uuid); + } + + /** + * Lookup an object by a field name + * @param clazz + * @param fieldName + * @return BaseModel if found. + */ + public Object lookupByFieldName(Class<?> clazz, String fieldName, String value) { + String key = clazz.getName(); + if (!objects.containsKey(key)) { + return null; + } + List typelist = (List) objects.get(key); + for (int i = 0; i < typelist.size(); i++) { + Object o = typelist.get(i); + System.out.println("O: " + o); + String getter = "get" + fieldName.substring(0, 1).toUpperCase() + + fieldName.substring(1); + System.out.println("getter: " + getter); + Object v = MethodUtil.callMethod(o, getter, new Object[0]); + System.out.println("v: " + v); + if (v.equals(value)) { + return o; + } + } + return null; } /** @@ -107,6 +140,21 @@ public class ObjectFactory { } return true; } + + /** + * Store an object + * @param u + */ + public void store(Object u) { + String key = u.getClass().getName(); + if (!objects.containsKey(key)) { + List newtype = new LinkedList(); + newtype.add(u); + objects.put(u.getClass().getName(), newtype); + } + List typelist = (List) objects.get(key); + typelist.add(u); + } } diff --git a/proxy/code/src/org/fedoraproject/candlepin/model/test/OrganizationTest.java b/proxy/code/src/org/fedoraproject/candlepin/model/test/OrganizationTest.java index 90d681c..df15d18 100644 --- a/proxy/code/src/org/fedoraproject/candlepin/model/test/OrganizationTest.java +++ b/proxy/code/src/org/fedoraproject/candlepin/model/test/OrganizationTest.java @@ -1,8 +1,21 @@ /** - * + * Copyright (c) 2009 Red Hat, Inc. + * + * This software is licensed to you under the GNU General Public License, + * version 2 (GPLv2). There is NO WARRANTY for this software, express or + * implied, including the implied warranties of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 + * along with this software; if not, see + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * Red Hat trademarks are not licensed under GPLv2. No permission is + * granted to use or replicate Red Hat trademarks that are incorporated + * in this software or its documentation. */ package org.fedoraproject.candlepin.model.test; +import junit.framework.TestCase; + import org.fedoraproject.candlepin.model.BaseModel; import org.fedoraproject.candlepin.model.Consumer; import org.fedoraproject.candlepin.model.EntitlementPool; @@ -11,8 +24,6 @@ import org.fedoraproject.candlepin.model.Organization; import org.fedoraproject.candlepin.model.Product; import org.fedoraproject.candlepin.model.User; -import junit.framework.TestCase; - /** * * @@ -26,7 +37,11 @@ public class OrganizationTest extends TestCase { public void testLookup() throws Exception { String lookedUp = BaseModel.generateUUID(); - Organization o = (Organization) ObjectFactory.get(). + Organization o = new Organization(); + o.setUuid(lookedUp); + ObjectFactory.get().store(o); + + o = (Organization) ObjectFactory.get(). lookupByUUID(Organization.class, lookedUp); assertNotNull(o); } diff --git a/proxy/code/src/org/fedoraproject/candlepin/util/MethodUtil.java b/proxy/code/src/org/fedoraproject/candlepin/util/MethodUtil.java new file mode 100644 index 0000000..2884c70 --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/util/MethodUtil.java @@ -0,0 +1,220 @@ +/** + * Copyright (c) 2009 Red Hat, Inc. + * + * This software is licensed to you under the GNU General Public License, + * version 2 (GPLv2). There is NO WARRANTY for this software, express or + * implied, including the implied warranties of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 + * along with this software; if not, see + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * Red Hat trademarks are not licensed under GPLv2. No permission is + * granted to use or replicate Red Hat trademarks that are incorporated + * in this software or its documentation. + */ + +package org.fedoraproject.candlepin.util; + +import org.apache.log4j.Logger; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * A simple class that assists with method invocation. We should just use + * the jakarta-commons MethodUtils class, but that class can't deal with + * static methods, so it is useless to us. + * @version $Rev$ + */ +public class MethodUtil { + + private static Logger log = Logger.getLogger(MethodUtil.class); + + /** + * Private constructore + */ + private MethodUtil() { + } + + /* This is insanity itself, but the reflection APIs ignore inheritance. + * So, if you ask for a method that accepts (Integer, HashMap, HashMap), + * and the class only has (Integer, Map, Map), you won't find the method. + * This method uses Class.isAssignableFrom to solve this problem. + */ + private static boolean isCompatible(Class[] declaredParams, Object[] params) { + if (params.length != declaredParams.length) { + return false; + } + + for (int i = 0; i < params.length; i++) { + if (!declaredParams[i].isInstance(params[i])) { + return false; + } + } + return true; + } + + + /** + * Call the specified method with the specified arguments, converting + * the argument type if necessary. + * @param o The object from which to call the method + * @param methodCalled The method to call + * @param params a Collection of the parameters to methodCalled + * @return the results of the method of the subclass + */ + public static Object callMethod(Object o, String methodCalled, + Object... params) { + /* This whole method is currently an ugly mess that needs to be + * refactored. rbb + */ + if (log.isDebugEnabled()) { + log.debug("Trying to call: " + methodCalled + " in " + o.getClass()); + } + Class myClass = o.getClass(); + Method[] methods; + try { + methods = myClass.getMethods(); + } + catch (SecurityException e) { + // This should _never_ happen, because the Handler classes must + // have public classes if they're expected to work. + throw new IllegalArgumentException("no public methods in class " + myClass); + } + + Method foundMethod = null; + Object[] converted = new Object[params.length]; + boolean rightMethod = false; + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(methodCalled)) { + foundMethod = methods[i]; + + Class[] types = foundMethod.getParameterTypes(); + if (types.length != params.length) { + continue; + } + + // We have a method that might work, now we need to loop + // through the params and make sure that the types match + // with what was provided in the Collection. If they don't + // match, try to do a translation, if that fails try the next + boolean found = true; + for (int j = 0; j < types.length; j++) { + Object curr = params[j]; + if (log.isDebugEnabled()) { + log.debug("Trying to translate from: " + + ((curr == null) ? null : curr.getClass()) + + " to: " + types[j] + + " isInstance: " + types[j].isInstance(curr)); + } + if (curr != null && curr.getClass().isPrimitive() && + types[j].isPrimitive()) { + if (log.isDebugEnabled()) { + log.debug("2 primitives"); + } + converted[j] = curr; + } + if ((curr == null && !types[j].isPrimitive()) || + types[j].isInstance(curr)) { + if (log.isDebugEnabled()) { + log.debug("same type"); + } + converted[j] = curr; + continue; + } + try { + if (log.isDebugEnabled()) { + log.debug("calling converter: " + curr); + } + converted[j] = Translator.convert(curr, types[j]); + } + catch (RuntimeException e) { + log.debug("Couldn't translate between " + curr + + " and " + types[j]); + // move on to the next method. + found = false; + break; + } + } + if (found) { + rightMethod = found; + break; + } + } + } + + if (!rightMethod) { + String message = "Could not find method called: " + methodCalled + + " in class: " + o.getClass().getName() + " with params: ["; + for (int i = 0; i < params.length; i++) { + if (params[i] != null) { + message = message + ("type: " + params[i].getClass().getName() + + ", value: " + params[i]); + if (i < params.length - 1) { + message = message + ", "; + } + } + } + message = message + "]"; + throw new RuntimeException(message); + } + try { + return foundMethod.invoke(o, converted); + } + catch (IllegalAccessException e) { + throw new RuntimeException("Could not access " + methodCalled, e); + } + catch (InvocationTargetException e) { + throw new RuntimeException("Something bad happened when " + + "calling " + methodCalled, e); + } + } + + /** + * Create a new instance of the classname passed in. + * + * @param className + * @return instance of class passed in. + */ + private static Object callNewMethod(String className, Object... args) { + Object retval = null; + + try { + Class clazz = Thread.currentThread(). + getContextClassLoader().loadClass(className); + if (args == null || args.length == 0) { + retval = clazz.newInstance(); + } + else { + try { + Constructor[] ctors = clazz.getConstructors(); + for (Constructor ctor : ctors) { + if (isCompatible(ctor.getParameterTypes(), args)) { + return ctor.newInstance(args); + } + } + } + catch (IllegalArgumentException e) { + throw new RuntimeException(e); + } + catch (InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + } + catch (InstantiationException e) { + throw new RuntimeException(e); + } + catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + + return retval; + } +} diff --git a/proxy/code/src/org/fedoraproject/candlepin/util/TranslationException.java b/proxy/code/src/org/fedoraproject/candlepin/util/TranslationException.java new file mode 100644 index 0000000..89d3fe9 --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/util/TranslationException.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2009 Red Hat, Inc. + * + * This software is licensed to you under the GNU General Public License, + * version 2 (GPLv2). There is NO WARRANTY for this software, express or + * implied, including the implied warranties of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 + * along with this software; if not, see + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * Red Hat trademarks are not licensed under GPLv2. No permission is + * granted to use or replicate Red Hat trademarks that are incorporated + * in this software or its documentation. + */ + +/* + * AUTOMATICALLY GENERATED FILE, DO NOT EDIT. + */ +package org.fedoraproject.candlepin.util; + + +/** + * Translation method not found + * <p> + + * + * @version definition($Rev: 76724 $)/template($Rev: 67725 $) + */ +public class TranslationException extends RuntimeException { + + + ///////////////////////// + // Constructors + ///////////////////////// + /** + * Constructor + * @param message exception message + */ + public TranslationException(String message) { + super(message); + // begin member variable initialization + } + + /** + * Constructor + * @param message exception message + * @param cause the cause (which is saved for later retrieval + * by the Throwable.getCause() method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + */ + public TranslationException(String message , Throwable cause) { + super(message, cause); + // begin member variable initialization + } + + ///////////////////////// + // Getters/Setters + ///////////////////////// +} diff --git a/proxy/code/src/org/fedoraproject/candlepin/util/Translations.java b/proxy/code/src/org/fedoraproject/candlepin/util/Translations.java new file mode 100644 index 0000000..6511dcd --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/util/Translations.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) 2009 Red Hat, Inc. + * + * This software is licensed to you under the GNU General Public License, + * version 2 (GPLv2). There is NO WARRANTY for this software, express or + * implied, including the implied warranties of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 + * along with this software; if not, see + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * Red Hat trademarks are not licensed under GPLv2. No permission is + * granted to use or replicate Red Hat trademarks that are incorporated + * in this software or its documentation. + */ + +package org.fedoraproject.candlepin.util; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * TranslationFactory, simple factory class that uses ManifestFactory to + * return translation methods + * + * @version $Rev$ + */ + +public class Translations { + + protected Translations() { + } + + // This is a HACK! Basically, we can't get to the Class object from + // within a static method. So, we pass the Class object in from + // a sub-class. + protected static Object convert(Class thisClass, Object have, Class want) { + + // Don't worry about classes that are assignable; i.e., HashMap -> Map + if (want.isAssignableFrom(have.getClass())) { + return have; + } + + Method[] methods = thisClass.getDeclaredMethods(); + + // tries to find an exact match + Object rc = findMatch(methods, have, want, false); + + if (rc == null) { + // try to find the best match + rc = findMatch(methods, have, want, true); + + if (rc == null) { + throw new TranslationException("Could not find translator for " + + have.getClass() + " to " + want); + } + } + + return rc; + } + + private static Object findMatch(Method[] methods, Object have, + Class want, boolean bestMatch) + throws TranslationException { + + for (int i = 0; i < methods.length; i++) { + Class returnType = methods[i].getReturnType(); + Class[] params = methods[i].getParameterTypes(); + + // All conversions have a single parameter, the object to transform + if (!bestMatch && have != null && + (params.length != 1 || !params[0].equals(have.getClass()))) { + continue; + } + else if (bestMatch && have != null && + (params.length != 1 || !params[0].isAssignableFrom(have.getClass()))) { + continue; + } + + if (returnType.equals(want)) { + Object[] objs = {have}; + try { + return methods[i].invoke(null, objs); + } + catch (IllegalAccessException e) { + throw new TranslationException("Could not execute " + + "translator for " + have.getClass() + + " to " + want, e); + } + catch (InvocationTargetException e) { + throw new TranslationException("Error when executing " + + "translator for " + have.getClass() + + " to " + want, e.getCause()); + } + } + } + + return null; + } +} diff --git a/proxy/code/src/org/fedoraproject/candlepin/util/Translator.java b/proxy/code/src/org/fedoraproject/candlepin/util/Translator.java new file mode 100644 index 0000000..2e818d3 --- /dev/null +++ b/proxy/code/src/org/fedoraproject/candlepin/util/Translator.java @@ -0,0 +1,231 @@ +/** + * Copyright (c) 2009 Red Hat, Inc. + * + * This software is licensed to you under the GNU General Public License, + * version 2 (GPLv2). There is NO WARRANTY for this software, express or + * implied, including the implied warranties of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 + * along with this software; if not, see + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * Red Hat trademarks are not licensed under GPLv2. No permission is + * granted to use or replicate Red Hat trademarks that are incorporated + * in this software or its documentation. + */ + +package org.fedoraproject.candlepin.util; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * Translator The class that actually does the object translations for us. + * + * @version $Rev$ + */ + +public class Translator extends Translations { + + private Translator() { + } + + /** + * Translate from from one object type to another. + * @param have The object to convert + * @param want The Class to convert to. + * @return the converted object + */ + public static Object convert(Object have, Class want) { + return convert(Translator.class, have, want); + } + + /** + * Convert an Integer object into a String + * @param i the integer to convert + * @return Returns the string representation of i + */ + public static String int2String(Integer i) { + return (i == null) ? "" : i.toString(); + } + + /** + * Convert an Integer object into a list containing the integer + * @param i The integer to add to the list + * @return Returns a list containing i + */ + public static List int2List(Integer i) { + List list = new ArrayList(); + if (i != null) { + list.add(i); + } + return list; + } + + /** + * Convert an Integer object to a boolean + * @param i Integer to check. 1 = true, anything else = false + * @return Returns the boolean representation of i + */ + public static boolean int2Boolean(Integer i) { + return (i == null) ? false : i.equals(new Integer(1)); + } + + /** + * Convert an Long object to a boolean + * @param i Long to check. 1 = true, anything else = false + * @return Returns the boolean representation of i + */ + public static boolean long2Boolean(Long i) { + return (i == null) ? false : i == 1; + } + + /** Convert from Long to long + * @param l The Long to convert + * @return The resulting long + * @throws Exception if anything goes wrong while doing the conversion. + */ + public static long long2Objlong(Long l) + throws Exception { + return (l == null) ? 0 : l.longValue(); + } + + /** + * Converts a Long to an Integer if needed. + * @param l Long object to be + * @return Integer version of the Long. + */ + public static Integer long2Integer(Long l) { + return (l == null) ? null : new Integer(l.intValue()); + } + + /** + * Converts a Long to an int if needed. + * @param l Long object to be + * @return int version of the Long. + */ + public static int long2Int(Long l) { + return (l == null) ? 0 : l.intValue(); + } + + /** Convert from BigDecimal to int + * @param bd The BigDecimal to convert + * @return The resulting int + * @throws Exception if anything goes wrong while doing the conversion. + */ + public static int bigDecimal2Int(BigDecimal bd) + throws Exception { + return (bd == null) ? 0 : bd.intValue(); + } + + /** Convert from BigDecimal to Integer + * @param bd The BigDecimal to convert + * @return The resulting Integer + * @throws Exception if anything goes wrong while doing the conversion. + */ + public static Integer bigDecimal2IntObject(BigDecimal bd) + throws Exception { + return (bd == null) ? new Integer(0) : new Integer(bd.intValue()); + } + + /** Convert from BigDecimal to long + * @param bd The BigDecimal to convert + * @return The resulting long + * @throws Exception if anything goes wrong while doing the conversion. + */ + public static long bigDecimal2Long(BigDecimal bd) + throws Exception { + return (bd == null) ? 0 : bd.longValue(); + } + + /** + * Convert from BigDecimal to Long + * @param bd The BigDecimal to convert + * @return The resulting Long + * @throws Exception if anything goes wrong while doing the conversion. + */ + public static Long bigDecimal2LongObj(BigDecimal bd) + throws Exception { + return (bd == null) ? null : new Long(bd.longValue()); + } + + /** + * Convert from String to boolean. + * @param str The string to convert + * @return true if the string equals "Y", false otherwise. + * @throws Exception if anything goes wrong while doing the conversion. + */ + public static boolean string2boolean(String str) + throws Exception { + if (str == null) { + return false; + } + + // need to check the possible true values + // tried to use BooleanUtils, but that didn't + // get the job done for an integer as a String. + if (str.equals("1") || str.equalsIgnoreCase("y") || + str.equalsIgnoreCase("true")) { + return true; + } + + return false; + } + + /** + * Convert from Double to String. + * @param d The double to convert + * @return The resulting string. + */ + public static String double2String(Double d) { + return (d == null) ? "0" : d.toString(); + } + + /** + * Converts a List to a String + * @param l list to be converted + * @return List.toString() + */ + public static String list2String(List l) { + return (l == null) ? "" : l.toString(); + } + + /** + * Converts a Map to a String. + * @param m map to be converted + * @return map.toString() + */ + public static String map2String(Map m) { + return (m == null) ? "" : m.toString(); + } + + /** + * Convert from Boolean to String. + * @param b The Boolean to convert + * @return The resulting string. + */ + public static String boolean2String(Boolean b) { + return (b == null) ? Boolean.FALSE.toString() : b.toString(); + } + + /** + * Convert from Date to String. + * + * @param d Date to convert + * @return Resulting string + */ + public static String date2String(Date d) { + return (d == null) ? "" : d.toString(); + } + + /** + * Convert from a Boolean to a boolean + * @param b the Boolean to convert + * @return a boolean primitive + */ + public static boolean boolean2boolean(Boolean b) { + return (b == null) ? false : b.booleanValue(); + } +} |
