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:com.alibaba.wasp.master.FMaster.java

/**
 * Utility for constructing an instance of the passed FMaster class.
 *
 * @param masterClass/*from w  w  w. j  ava  2 s .  c  om*/
 * @param conf
 * @return FMaster instance.
 */
public static FMaster constructMaster(Class<? extends FMaster> masterClass, final Configuration conf) {
    try {
        Constructor<? extends FMaster> c = masterClass.getConstructor(Configuration.class);
        return c.newInstance(conf);
    } 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.geoserver.platform.GeoServerResourceLoader.java

/**
 * Copies a resource relative to a particular class from the classpath to the specified file. 
 * //from w ww.j a va  2  s . co  m
 * @param classpathResource Path to classpath content to be copied
 * @param target File to copy content into (must be already created)
 * @param scope Class used as base for classpathResource
 */

public void copyFromClassPath(String classpathResource, File target, Class<?> scope) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    byte[] buffer = new byte[4096];
    int read;

    try {
        // Get the resource
        if (scope == null) {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathResource);
            if (is == null) {
                throw new IOException("Could not load " + classpathResource + " from scope "
                        + Thread.currentThread().getContextClassLoader().toString() + ".");
            }
        } else {
            is = scope.getResourceAsStream(classpathResource);
            if (is == null) {
                throw new IOException(
                        "Could not load " + classpathResource + " from scope " + scope.toString() + ".");
            }
        }

        // Write it to the target
        try {
            os = new FileOutputStream(target);
            while ((read = is.read(buffer)) > 0)
                os.write(buffer, 0, read);
        } catch (FileNotFoundException targetException) {
            throw new IOException("Can't write to file " + target.getAbsolutePath()
                    + ". Check write permissions on target folder for user " + System.getProperty("user.name"));
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Error trying to copy logging configuration file", e);
        }
    } finally {
        // Clean up
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.apache.empire.struts2.jsp.tags.EmpireTagSupport.java

protected Object getObject(Object value, Object defValue, Class<?> asType) {
    if (value == null) {
        return defValue;
    }/*  ww  w. jav  a  2  s  .com*/
    // Check String
    if ((value instanceof String)) {
        // Check Value
        String strval = value.toString();
        if (strval.startsWith("%{") && strval.endsWith("}")) { // OGNL
            strval = strval.substring(2, strval.length() - 1);
            return getStack().findValue(strval, asType);
        }
        if (strval.startsWith("#")) { // OGNL
            return getStack().findValue(strval, asType);
        }
        if (strval.startsWith("$")) { // Attribute on page, request, session or application (in this order)
            strval = strval.substring(1);
            if (strval.startsWith("$") == false)
                value = getAttribute(strval);
            if (value == null)
                return defValue;
        }
    }
    // Check Class
    if (asType.isInstance(value)) { // make a cast
        return asType.cast(value);
    }
    // Error
    log.error("Cannot cast value of '" + value.toString() + " to class " + asType.toString());
    return null;
}

From source file:dk.defxws.fedoragsearch.server.Config.java

public GenericOperationsImpl getOperationsImpl(String fgsUserNameParam, String indexNameParam)
        throws ConfigException {
    GenericOperationsImpl ops = null;/*from w w w  .  j  av  a2 s.  c o m*/
    String indexName = getIndexName(indexNameParam);
    Properties indexProps = getIndexProps(indexName);
    if (indexProps == null)
        throw new ConfigException("The indexName " + indexName + " is not configured.\n");
    String operationsImpl = indexProps.getProperty("fgsindex.operationsImpl");
    if (operationsImpl == null)
        throw new ConfigException("The indexName " + indexName + " is not configured.\n");
    if (logger.isDebugEnabled())
        logger.debug("indexName=" + indexName + " operationsImpl=" + operationsImpl);
    try {
        Class operationsImplClass = Class.forName(operationsImpl);
        if (logger.isDebugEnabled())
            logger.debug("operationsImplClass=" + operationsImplClass.toString());
        ops = (GenericOperationsImpl) operationsImplClass.getConstructor(new Class[] {})
                .newInstance(new Object[] {});
        if (logger.isDebugEnabled())
            logger.debug("ops=" + ops.toString());
    } catch (ClassNotFoundException e) {
        throw new ConfigException(operationsImpl + ": class not found.\n", e);
    } catch (InstantiationException e) {
        throw new ConfigException(operationsImpl + ": instantiation error.\n", e);
    } catch (IllegalAccessException e) {
        throw new ConfigException(operationsImpl + ": instantiation error.\n", e);
    } catch (InvocationTargetException e) {
        throw new ConfigException(operationsImpl + ": instantiation error.\n", e);
    } catch (NoSuchMethodException e) {
        throw new ConfigException(operationsImpl + ": instantiation error.\n", e);
    }
    ops.init(fgsUserNameParam, indexName, this);
    return ops;
}

From source file:com.mobicage.rogerthat.MainService.java

public <E extends MobicagePlugin> E getPlugin(Class<E> plugin) {
    T.dontCare();/*w w  w. j ava 2s  . co  m*/
    @SuppressWarnings("unchecked")
    final E thePlugin = (E) mPlugins.get(plugin.toString());
    if (thePlugin == null) {
        L.bug("Requesting plugin that is not yet initialized! " + plugin.toString());
    }
    return thePlugin;
}

From source file:org.kuali.rice.krad.rules.MaintenanceDocumentRuleBase.java

/**
 * This method tests to make sure the MaintenanceDocument passed in is based on the class you are expecting.
 *
 * It does this based on the NewMaintainableObject of the MaintenanceDocument.
 *
 * @param document - MaintenanceDocument instance you want to test
 * @param clazz - class you are expecting the MaintenanceDocument to be based on
 * @return true if they match, false if not
 *///from w ww .j av  a  2 s.c  o  m
protected boolean isCorrectMaintenanceClass(MaintenanceDocument document, Class clazz) {
    // disallow null arguments
    if (document == null || clazz == null) {
        throw new IllegalArgumentException("Null arguments were passed in.");
    }

    // compare the class names
    if (clazz.toString().equals(document.getNewMaintainableObject().getDataObjectClass().toString())) {
        return true;
    } else {
        return false;
    }
}

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

@Override
protected boolean isAuthorized(Account actor, Account targetedAccount, PermissionType permission, E entry,
        Class<?> clazz, Object... opt) {
    Validate.notNull(permission);/*from w  w w .  j  a  va 2  s .  c  o m*/
    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;
    } else if (permission.equals(PermissionType.DOWNLOAD)) {
        if (hasDownloadPermission(actor, targetedAccount, entry, opt))
            return true;
    } else if (permission.equals(PermissionType.DOWNLOAD_THUMBNAIL)) {
        if (hasDownloadTumbnailPermission(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());
        if (entry != null) {
            appendOwner(sb, entry, opt);
        }
        logger.error(sb.toString());
    }
    return false;
}

From source file:com.facebook.GraphObjectWrapper.java

static <U> U coerceValueToExpectedType(Object value, Class<U> expectedType,
        ParameterizedType expectedTypeAsParameterizedType) {
    if (value == null) {
        return null;
    }//from w  w  w  .j  a v  a 2  s  . c o  m

    Class<?> valueType = value.getClass();
    if (expectedType.isAssignableFrom(valueType)) {
        @SuppressWarnings("unchecked")
        U result = (U) value;
        return result;
    }

    if (expectedType.isPrimitive()) {
        // If the result is a primitive, let the runtime succeed or fail at unboxing it.
        @SuppressWarnings("unchecked")
        U result = (U) value;
        return result;
    }

    if (GraphObject.class.isAssignableFrom(expectedType)) {
        @SuppressWarnings("unchecked")
        Class<? extends GraphObject> graphObjectClass = (Class<? extends GraphObject>) expectedType;

        // We need a GraphObject, but we don't have one.
        if (JSONObject.class.isAssignableFrom(valueType)) {
            // We can wrap a JSONObject as a GraphObject.
            @SuppressWarnings("unchecked")
            U result = (U) createGraphObjectProxy(graphObjectClass, (JSONObject) value);
            return result;
        } else if (GraphObject.class.isAssignableFrom(valueType)) {
            // We can cast a GraphObject-derived class to another GraphObject-derived class.
            @SuppressWarnings("unchecked")
            U result = (U) ((GraphObject) value).cast(graphObjectClass);
            return result;
        } else {
            throw new FacebookGraphObjectException("Can't create GraphObject from " + valueType.getName());
        }
    } else if (Iterable.class.equals(expectedType) || Collection.class.equals(expectedType)
            || List.class.equals(expectedType) || GraphObjectList.class.equals(expectedType)) {
        if (expectedTypeAsParameterizedType == null) {
            throw new FacebookGraphObjectException("can't infer generic type of: " + expectedType.toString());
        }

        Type[] actualTypeArguments = expectedTypeAsParameterizedType.getActualTypeArguments();

        if (actualTypeArguments == null || actualTypeArguments.length != 1
                || !(actualTypeArguments[0] instanceof Class<?>)) {
            throw new FacebookGraphObjectException(
                    "Expect collection properties to be of a type with exactly one generic parameter.");
        }
        Class<?> collectionGenericArgument = (Class<?>) actualTypeArguments[0];

        if (JSONArray.class.isAssignableFrom(valueType)) {
            JSONArray jsonArray = (JSONArray) value;
            @SuppressWarnings("unchecked")
            U result = (U) wrapArray(jsonArray, collectionGenericArgument);
            return result;
        } else {
            throw new FacebookGraphObjectException("Can't create Collection from " + valueType.getName());
        }
    } else if (String.class.equals(expectedType)) {
        if (Number.class.isAssignableFrom(valueType)) {
            @SuppressWarnings("unchecked")
            U result = (U) String.format("%d", value);
            return result;
        }
    } else if (Date.class.equals(expectedType)) {
        if (String.class.isAssignableFrom(valueType)) {
            for (SimpleDateFormat format : dateFormats) {
                try {
                    Date date = format.parse((String) value);
                    if (date != null) {
                        @SuppressWarnings("unchecked")
                        U result = (U) date;
                        return result;
                    }
                } catch (ParseException e) {
                    // Keep going.
                }
            }
        }
    }
    throw new FacebookGraphObjectException(
            "Can't convert type" + valueType.getName() + " to " + expectedType.getName());
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceGroupDAO.java

/**
 * Helper method for adding filter criteria
 * //w w w.j  a  v  a  2  s  .c  o m
 * @param criteria
 *            - the filter criteria
 * @param filterInfos
 *            - list for filter specifications. filter info are added in the order in the list
 *            
 * @return List<FilterParamParser.FilterInfo>
 *                             - list of added filters
 * 
 * @throws IllegalArgumentException
 */
@SuppressWarnings("unchecked")
private List<FilterParamParser.FilterInfo> addFilterCriteria(Criteria criteria,
        List<FilterParamParser.FilterInfo> filterInfos, Class persistentClass) {

    LinkedList<FilterParamParser.FilterInfo> notFound = new LinkedList<>();

    for (FilterParamParser.FilterInfo filterInfo : filterInfos) {
        String columnName = filterInfo.getColumnName();
        List<?> values = filterInfo.getColumnValue();

        //
        // Cast strings to the property type by scanning the persistent class
        //
        Class<?> typeClass = null;
        // try non-boolean-type naming.
        try {
            typeClass = persistentClass.getMethod("get" + StringUtils.capitalize(columnName)).getReturnType();
        } catch (NoSuchMethodException e) {
            logger.info("cannot find a method for " + columnName + " in " + persistentClass.toString());

        }
        // try boolean-type naming.
        if (typeClass == null) {
            try {
                typeClass = persistentClass.getMethod("is" + StringUtils.capitalize(columnName))
                        .getReturnType();
            } catch (NoSuchMethodException e) {
                logger.info("cannot find a method for " + columnName + " in " + persistentClass.toString());
            }
        }
        // property not found. skip.
        if (typeClass == null) {
            notFound.add(filterInfo);
            continue;
        }
        if (!typeClass.isAssignableFrom(String.class)) {

            // byte/short/int/long
            if (typeClass == byte.class || typeClass == short.class || typeClass == int.class
                    || typeClass == long.class) {
                LinkedList<Long> castedValues = new LinkedList<>();
                for (String stringValue : filterInfo.getColumnValue()) {
                    castedValues.add(Long.valueOf(stringValue));
                }
                // Set casted values
                values = castedValues;

                // float/double
            } else if (typeClass == float.class || typeClass == double.class) {
                LinkedList<Double> castedValues = new LinkedList<>();
                for (String stringValue : filterInfo.getColumnValue()) {
                    castedValues.add(Double.valueOf(stringValue));
                }
                // Set casted values
                values = castedValues;
                // boolean
            } else if (typeClass == boolean.class) {
                LinkedList<Boolean> castedValues = new LinkedList<>();
                for (String stringValue : filterInfo.getColumnValue()) {
                    castedValues.add(Boolean.valueOf(stringValue));
                }
                // Set casted values
                values = castedValues;
                // char
            } else if (typeClass == char.class) {
                LinkedList<Character> castedValues = new LinkedList<>();
                for (String stringValue : filterInfo.getColumnValue()) {
                    castedValues.add(Character.valueOf(stringValue.charAt(0)));
                }
                // Set casted values
                values = castedValues;
            }
        }

        //
        // Translate filters to Hibernate Criteria
        //
        if (values.size() > 1) {
            if (FilterParamParser.FilterOperator.EQUAL.equals(filterInfo.getFilterOperator())) {
                criteria.add(Restrictions.in(columnName, values));
            } else {
                throw new IllegalArgumentException(
                        "filter operation '" + filterInfo.getFilterOperator() + "' is not recognized.");
            }
        } else if (values.size() == 1) {
            if (FilterParamParser.FilterOperator.EQUAL.equals(filterInfo.getFilterOperator())) {
                criteria.add(Restrictions.eq(columnName, values.get(0)));
            } else if (FilterParamParser.FilterOperator.CONTAIN.equals(filterInfo.getFilterOperator())) {

                // Escape '_', '%', and '\' for Hibernate.
                String escapedString = values.get(0).toString();
                escapedString = escapedString.replace("\\", "\\\\").replace("_", "\\_").replace("%", "\\%");

                criteria.add(Restrictions.like(columnName, escapedString, MatchMode.ANYWHERE));
            } else {
                throw new IllegalArgumentException(
                        "filter operation '" + filterInfo.getFilterOperator() + "' is not recognized.");
            }
        }
    }

    return notFound;
}

From source file:org.opentestsystem.delivery.testreg.eligibility.EligibilityEvaluatorCache.java

@SuppressWarnings("unchecked")
private <T> T convertTo(final String value, final Class<T> clazz) {

    try {//ww w .j a  v  a2 s . c  om
        if (String.class.isAssignableFrom(clazz)) {
            return (T) value;
        } else if (Number.class.isAssignableFrom(clazz)) {
            return clazz.getConstructor(String.class).newInstance(value);
        } else if (DateTime.class.isAssignableFrom(clazz)) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            DateTime dateTime = formatter.parseDateTime(value);
            return (T) dateTime;
        } else if (Enum.class.isAssignableFrom(clazz)) {
            Method getEnum = null;
            try {
                getEnum = clazz.getDeclaredMethod("getEnumByValue", String.class);
            } catch (final NoSuchMethodException me) {
                getEnum = clazz.getMethod("valueOf", String.class);
            }
            return (T) getEnum.invoke(null, value);
        } else {
            LOGGER.error("Failure to convert value \"" + value + "\" into class type " + clazz.toString());
            throw new EligibilityException("eligibility.value.convert.error",
                    new String[] { value, clazz.toString() });
        }
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        LOGGER.error("Failure to convert value \"" + value + "\" into class type " + clazz.toString(), e);
        throw new EligibilityException("eligibility.value.convert.error",
                new String[] { value, clazz.toString() }, e);
    }
}