Example usage for java.lang Class toString

List of usage examples for java.lang Class toString

Introduction

In this page you can find the example usage for java.lang Class toString.

Prototype

public String toString() 

Source Link

Document

Converts the object to a string.

Usage

From source file:org.linagora.linshare.core.rac.impl.StatisticResourceAccessControlImpl.java

protected boolean isAuthorized(Account actor, Account targetedAccount, PermissionType permission,
        Statistic entry, Class<?> clazz, Object... opt) {
    Validate.notNull(actor);/*from   w  w w . j  a  v a2  s  .  co m*/
    Validate.notNull(permission);
    if (actor.hasAllRights())
        return true;
    if (permission.equals(PermissionType.GET)) {
        if (hasReadPermission(actor, targetedAccount, entry, opt)) {
            return true;
        }
    } else if (permission.equals(PermissionType.LIST)) {
        if (hasListPermission(actor, targetedAccount, entry, opt))
            return true;
    } else if (permission.equals(PermissionType.CREATE)) {
        if (hasCreatePermission(actor, targetedAccount, entry, opt)) {
            return true;
        }
    } else if (permission.equals(PermissionType.UPDATE)) {
        if (hasUpdatePermission(actor, targetedAccount, entry, opt)) {
            return true;
        }
    } else if (permission.equals(PermissionType.DELETE)) {
        if (hasDeletePermission(actor, targetedAccount, entry, opt)) {
            return true;
        }
    }
    if (clazz != null) {
        StringBuilder sb = getActorStringBuilder(actor);
        sb.append(" is trying to access to unauthorized resource named ");
        sb.append(clazz.toString());
        appendOwner(sb, entry, opt);
        logger.error(sb.toString());
    }
    return false;
}

From source file:de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java

/**
 * A generic parsing method for parsing JSON to SportsEquipment, Muscle or Locale.
 *///from  w ww .ja va 2  s. co  m
private static <T> SparseArray<T> parse(String jsonString, Class<T> c) throws JSONException {
    JSONObject mainObject = new JSONObject(jsonString);
    Log.d(TAG, "jsonString: " + mainObject.toString());
    JSONArray mainArray = mainObject.getJSONArray("objects");

    SparseArray<T> sparseArray = new SparseArray<T>();

    // parse each exercise of the JSON Array
    for (int i = 0; i < mainArray.length(); i++) {
        JSONObject singleObject = mainArray.getJSONObject(i);

        Integer id = singleObject.getInt("id");
        Object parsedObject;
        if (c.equals(Muscle.class)) {
            // handle Muscles
            String name = singleObject.getString("name");
            parsedObject = mDataProvider.getMuscleByName(name);

            if (parsedObject == null)
                Log.e(TAG, "Could not find Muscle: " + name);

        } else if (c.equals(SportsEquipment.class)) {
            // handle SportsEquipment
            String name = singleObject.getString("name");
            parsedObject = mDataProvider.getEquipmentByName(name);

            if (parsedObject == null)
                Log.e(TAG, "Could not find SportsEquipment: " + name);

        } else if (c.equals(Locale.class)) {
            // handle Locales
            String short_name = singleObject.getString("short_name");
            parsedObject = new Locale(short_name);

            if (short_name == null || short_name.equals(""))
                Log.e(TAG, "Error, no short_name=" + short_name);

        } else if (c.equals(LicenseType.class)) {
            // handle licenses
            String short_name = singleObject.getString("short_name");

            parsedObject = mDataProvider.getLicenseTypeByName(short_name);

            if (short_name == null || short_name.equals(""))
                Log.e(TAG, "Error, no short_name=" + short_name);

        } else {
            throw new IllegalStateException(
                    "parse(String, Class<T>) cannot be applied for class: " + c.toString());
        }

        sparseArray.put(id, (T) parsedObject);

    }

    return sparseArray;
}

From source file:org.apache.hadoop.hbase.master.HMaster.java

/**
 * Utility for constructing an instance of the passed HMaster class.
 * @param masterClass/*ww  w.j  ava  2 s  .  c o  m*/
 * @param conf
 * @return HMaster instance.
 */
public static HMaster constructMaster(Class<? extends HMaster> masterClass, final Configuration conf,
        final CoordinatedStateManager cp) {
    try {
        Constructor<? extends HMaster> c = masterClass.getConstructor(Configuration.class,
                CoordinatedStateManager.class);
        return c.newInstance(conf, cp);
    } catch (InvocationTargetException ite) {
        Throwable target = ite.getTargetException() != null ? ite.getTargetException() : ite;
        if (target.getCause() != null)
            target = target.getCause();
        throw new RuntimeException("Failed construction of Master: " + masterClass.toString(), target);
    } catch (Exception e) {
        throw new RuntimeException("Failed construction of Master: " + masterClass.toString()
                + ((e.getCause() != null) ? e.getCause().getMessage() : ""), e);
    }
}

From source file:org.voltdb.CLIConfig.java

private void assignValueToField(Field field, String value) throws Exception {
    if ((value == null) || (value.length() == 0)) {
        return;/*w w  w  .j av a  2s.c  om*/
    }

    field.setAccessible(true);
    Class<?> cls = field.getType();

    if ((cls == boolean.class) || (cls == Boolean.class))
        field.set(this, Boolean.parseBoolean(value));
    else if ((cls == byte.class) || (cls == Byte.class))
        field.set(this, Byte.parseByte(value));
    else if ((cls == short.class) || (cls == Short.class))
        field.set(this, Short.parseShort(value));
    else if ((cls == int.class) || (cls == Integer.class))
        field.set(this, Integer.parseInt(value));
    else if ((cls == long.class) || (cls == Long.class))
        field.set(this, Long.parseLong(value));
    else if ((cls == float.class) || (cls == Float.class))
        field.set(this, Float.parseFloat(value));
    else if ((cls == double.class) || (cls == Double.class))
        field.set(this, Double.parseDouble(value));
    else if ((cls == String.class))
        field.set(this, value);
    else if (value.length() == 1 && ((cls == char.class) || (cls == Character.class)))
        field.set(this, value.charAt(0));
    else {
        System.err.println(
                "Parsing failed. Reason: can not assign " + value + " to " + cls.toString() + " class");
        printUsage();
        System.exit(-1);
    }

}

From source file:ddf.catalog.data.impl.MetacardImpl.java

/**
 * The brains of the operation -- does the interaction with the map or the wrapped metacard.
 *
 * @param <T>           the type of the Attribute value expected
 * @param attributeName the name of the {@link Attribute} to retrieve
 * @param returnType    the class that the value of the {@link ddf.catalog.data.AttributeType} is expected to be bound to
 * @return the value of the requested {@link Attribute} name
 *///ww w. j  a v  a  2 s .c  o  m
protected <T> T requestData(String attributeName, Class<T> returnType) {

    Attribute attribute = getAttribute(attributeName);

    if (attribute == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Attribute " + attributeName + " was not found, returning null");
        }
        return null;
    }

    Serializable data = attribute.getValue();

    if (returnType.isAssignableFrom(data.getClass())) {
        return returnType.cast(data);
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(data.getClass().toString() + " can not be assigned to " + returnType.toString());
        }
    }

    return null;
}

From source file:org.linagora.linshare.core.rac.impl.AbstractResourceAccessControlImpl.java

protected boolean isAuthorized(Account actor, A targetedAccount, PermissionType permission, E entry,
        Class<?> clazz, Object... opt) {
    Validate.notNull(actor);/*w w  w . j  av a2s  .com*/
    Validate.notNull(targetedAccount);
    Validate.notNull(permission);
    if (actor.hasAllRights())
        return true;
    if (permission.equals(PermissionType.GET)) {
        if (hasReadPermission(actor, targetedAccount, entry, opt))
            return true;
    } else if (permission.equals(PermissionType.LIST)) {
        if (hasListPermission(actor, targetedAccount, entry, opt))
            return true;
    } else if (permission.equals(PermissionType.CREATE)) {
        if (hasCreatePermission(actor, targetedAccount, entry, opt))
            return true;
    } else if (permission.equals(PermissionType.UPDATE)) {
        if (hasUpdatePermission(actor, targetedAccount, entry, opt))
            return true;
    } else if (permission.equals(PermissionType.DELETE)) {
        if (hasDeletePermission(actor, targetedAccount, entry, opt))
            return true;
    }
    if (clazz != null) {
        StringBuilder sb = getActorStringBuilder(actor);
        sb.append(" is trying to access to unauthorized resource named ");
        sb.append(clazz.toString());
        appendOwner(sb, entry, opt);
        logger.error(sb.toString());
    }
    return false;
}

From source file:jmri.InstanceManager.java

/**
 * Retrieve the last object of type T that was registered with
 * {@link #store(java.lang.Object, java.lang.Class) }.
 * <p>/*ww w  . ja v  a 2s  . com*/
 * Unless specifically set, the default is the last object stored, see the
 * {@link #setDefault(java.lang.Class, java.lang.Object) } method.
 * <p>
 * In some cases, InstanceManager can create the object the first time it's
 * requested. For more on that, see the class comment.
 * <p>
 * In most cases, system configuration assures the existence of a default
 * object, but this method also handles the case where one doesn't exist.
 * Use {@link #getDefault(java.lang.Class)} when the object is guaranteed to
 * exist.
 *
 * @param <T>  The type of the class
 * @param type The class Object for the item's type.
 * @return The default object for type.
 * @see #getOptionalDefault(java.lang.Class)
 */
@CheckForNull
public <T> T getInstance(@Nonnull Class<T> type) {
    log.trace("getOptionalDefault of type {}", type.getName());
    List<T> l = getInstances(type);
    if (l.isEmpty()) {
        synchronized (type) {

            // example of tracing where something is being initialized
            // log.error("jmri.implementation.SignalSpeedMap init", new Exception());
            if (traceFileActive) {
                traceFilePrint("Start initialization: " + type.toString());
                traceFileIndent++;
            }

            // check whether already working on this type
            InitializationState working = getInitializationState(type);
            Exception except = getInitializationException(type);
            setInitializationState(type, InitializationState.STARTED);
            if (working == InitializationState.STARTED) {
                log.error("Proceeding to initialize {} while already in initialization", type,
                        new Exception("Thread \"" + Thread.currentThread().getName() + "\""));
                log.error("    Prior initialization:", except);
                if (traceFileActive) {
                    traceFilePrint("*** Already in process ***");
                }
            } else if (working == InitializationState.DONE) {
                log.error("Proceeding to initialize {} but initialization is marked as complete", type,
                        new Exception("Thread \"" + Thread.currentThread().getName() + "\""));
            }

            // see if can autocreate
            log.debug("    attempt auto-create of {}", type.getName());
            if (InstanceManagerAutoDefault.class.isAssignableFrom(type)) {
                try {
                    T obj = type.getConstructor((Class[]) null).newInstance((Object[]) null);
                    l.add(obj);
                    // obj has been added, now initialize it if needed
                    if (obj instanceof InstanceManagerAutoInitialize) {
                        ((InstanceManagerAutoInitialize) obj).initialize();
                    }
                    log.debug("      auto-created default of {}", type.getName());
                } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
                        | InvocationTargetException e) {
                    log.error("Exception creating auto-default object for {}", type.getName(), e); // unexpected
                    setInitializationState(type, InitializationState.FAILED);
                    if (traceFileActive) {
                        traceFileIndent--;
                        traceFilePrint("End initialization (no object) A: " + type.toString());
                    }
                    return null;
                }
                setInitializationState(type, InitializationState.DONE);
                if (traceFileActive) {
                    traceFileIndent--;
                    traceFilePrint("End initialization A: " + type.toString());
                }
                return l.get(l.size() - 1);
            }
            // see if initializer can handle
            log.debug("    attempt initializer create of {}", type.getName());
            if (initializers.containsKey(type)) {
                try {
                    @SuppressWarnings("unchecked")
                    T obj = (T) initializers.get(type).getDefault(type);
                    log.debug("      initializer created default of {}", type.getName());
                    l.add(obj);
                    // obj has been added, now initialize it if needed
                    if (obj instanceof InstanceManagerAutoInitialize) {
                        ((InstanceManagerAutoInitialize) obj).initialize();
                    }
                    setInitializationState(type, InitializationState.DONE);
                    if (traceFileActive) {
                        traceFileIndent--;
                        traceFilePrint("End initialization I: " + type.toString());
                    }
                    return l.get(l.size() - 1);
                } catch (IllegalArgumentException ex) {
                    log.error("Known initializer for {} does not provide a default instance for that class",
                            type.getName());
                }
            } else {
                log.debug("        no initializer registered for {}", type.getName());
            }

            // don't have, can't make
            setInitializationState(type, InitializationState.FAILED);
            if (traceFileActive) {
                traceFileIndent--;
                traceFilePrint("End initialization (no object) E: " + type.toString());
            }
            return null;
        }
    }
    return l.get(l.size() - 1);
}

From source file:com.chinamobile.bcbsp.bspcontroller.BSPController.java

/**
 * BSPcontroller construction method initalize BSP master.
 * @param controllerClass//from  ww w.j  a  v  a  2s.  c  o  m
 *        extend from BSPcontroller.
 * @param conf
 *        BSP system configuration to initalize the controller.
 * @return
 *        BSP controller that has been constructed.
 */
public static BSPController constructController(Class<? extends BSPController> controllerClass,
        final Configuration conf) {
    try {
        Constructor<? extends BSPController> c = controllerClass.getConstructor(Configuration.class);
        return c.newInstance(conf);
    } catch (Exception e) {
        throw new RuntimeException("Failed construction of " + "Master: " + controllerClass.toString()
                + ((e.getCause() != null) ? e.getCause().getMessage() : ""), e);
    }
}

From source file:org.kuali.rice.krad.util.ObjectUtils.java

/**
 * Returns a Formatter instance for the given property name in the given given business object. First
 * checks if a formatter is defined for the attribute in the data dictionary, is not found then returns
 * the registered formatter for the property type in Formatter
 *
 * @param bo - business object instance with property to get formatter for
 * @param propertyName - name of property to get formatter for
 * @return Formatter instance//from   w  ww.j a v a 2 s  .co  m
 */
@Deprecated
public static Formatter getFormatterWithDataDictionary(Object bo, String propertyName) {
    Formatter formatter = null;

    Class boClass = bo.getClass();
    String boPropertyName = propertyName;

    // for collections, formatter should come from property on the collection type
    if (StringUtils.contains(propertyName, "]")) {
        Object collectionParent = getNestedValue(bo, StringUtils.substringBeforeLast(propertyName, "].") + "]");
        if (collectionParent != null) {
            boClass = collectionParent.getClass();
            boPropertyName = StringUtils.substringAfterLast(propertyName, "].");
        }
    }

    Class<? extends Formatter> formatterClass = KRADServiceLocatorWeb.getDataDictionaryService()
            .getAttributeFormatter(boClass, boPropertyName);
    if (formatterClass == null) {
        try {
            formatterClass = Formatter.findFormatter(getPropertyType(boClass.newInstance(), boPropertyName,
                    KNSServiceLocator.getPersistenceStructureService()));
        } catch (InstantiationException e) {
            LOG.warn("Unable to find a formater for bo class " + boClass + " and property " + boPropertyName);
            // just swallow the exception and let formatter be null
        } catch (IllegalAccessException e) {
            LOG.warn("Unable to find a formater for bo class " + boClass + " and property " + boPropertyName);
            // just swallow the exception and let formatter be null
        }
    }

    if (formatterClass != null) {
        try {
            formatter = formatterClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(
                    "cannot create new instance of formatter class " + formatterClass.toString(), e);
        }
    }

    return formatter;
}

From source file:com.alibaba.wasp.fserver.FServer.java

/**
 * Utility for constructing an instance of the passed FServer class.
 *
 * @param fserverClass//from  w  w  w  .j av a2 s .c o  m
 * @param conf
 * @return FServer instance.
 */
public static FServer constructFServer(Class<? extends FServer> fserverClass, final Configuration conf) {
    try {
        Constructor<? extends FServer> c = fserverClass.getConstructor(Configuration.class);
        return c.newInstance(conf);
    } catch (Exception e) {
        throw new RuntimeException("Failed construction of " + "FServer: " + fserverClass.toString(), e);
    }
}