Example usage for java.lang Class getSimpleName

List of usage examples for java.lang Class getSimpleName

Introduction

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

Prototype

public String getSimpleName() 

Source Link

Document

Returns the simple name of the underlying class as given in the source code.

Usage

From source file:com.evolveum.midpoint.web.util.WebModelUtils.java

public static <T extends ObjectType> List<PrismObject<T>> searchObjects(Class<T> type, ObjectQuery query,
        Collection<SelectorOptions<GetOperationOptions>> options, OperationResult result, PageBase page,
        PrismObject<UserType> principal) {
    LOGGER.debug("Searching {} with oid {}, options {}", new Object[] { type.getSimpleName(), query, options });

    OperationResult subResult;/*  w ww .  j  av a2 s  .  co m*/
    if (result != null) {
        subResult = result.createMinorSubresult(OPERATION_SEARCH_OBJECTS);
    } else {
        subResult = new OperationResult(OPERATION_SEARCH_OBJECTS);
    }
    List<PrismObject<T>> objects = new ArrayList<PrismObject<T>>();
    try {
        Task task = page.createSimpleTask(subResult.getOperation(), principal);
        List<PrismObject<T>> list = page.getModelService().searchObjects(type, query, options, task, subResult);
        if (list != null) {
            objects.addAll(list);
        }
    } catch (Exception ex) {
        subResult.recordFatalError("WebModelUtils.couldntSearchObjects", ex);
        LoggingUtils.logException(LOGGER, "Couldn't search objects", ex);
    } finally {
        subResult.computeStatus();
    }

    if (result == null && WebMiscUtil.showResultInPage(subResult)) {
        page.showResultInSession(subResult);
    }

    LOGGER.debug("Loaded ({}) with result {}", new Object[] { objects.size(), subResult });

    return objects;
}

From source file:com.hurence.logisland.documentation.DocGenerator.java

/**
 * Generates documentation into the work/docs dir specified from a specified set of class
 *//*from w w  w.ja  v a2s . c  om*/
public static void generate(final File docsDirectory, final String writerType) {

    Map<String, Class> extensionClasses = new TreeMap<>();

    PluginLoader.getRegistry().forEach((className, classLoader) -> {
        try {
            extensionClasses.put(className, classLoader.loadClass(className));
        } catch (Exception e) {
            logger.error("Unable to load class " + className, e);

        }
    });

    ClassFinder.findClasses(clazz -> {
        if (!clazz.startsWith("BOOT-INF") && clazz.contains("logisland") && !clazz.contains("Mock")
                && !clazz.contains("shade")) {
            try {
                Class c = Class.forName(clazz);
                if (c.isAssignableFrom(ConfigurableComponent.class) && !Modifier.isAbstract(c.getModifiers())) {
                    extensionClasses.put(c.getSimpleName(), c);
                }
            } catch (Throwable e) {
                logger.error("Unable to load class " + clazz + " : " + e.getMessage());
            }
        }

        return true; // return false if you don't want to see any more classes
    });

    docsDirectory.mkdirs();

    // write headers for single rst file
    if (writerType.equals("rst"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        if (baseDocumenationFile.exists())
            baseDocumenationFile.delete();

        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("Components");
            writer.println("==========");
            writer.println(
                    "You'll find here the list of all usable Processors, Engines, Services and other components "
                            + "that can be usable out of the box in your analytics streams");
            writer.println();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    } else if (writerType.equals("json"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        if (baseDocumenationFile.exists())
            baseDocumenationFile.delete();

        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("[");
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    }

    Class[] sortedExtensionsClasses = new Class[extensionClasses.size()];
    extensionClasses.values().

            toArray(sortedExtensionsClasses);

    Arrays.sort(sortedExtensionsClasses, new Comparator<Class>()

    {
        @Override
        public int compare(Class s1, Class s2) {
            // the +1 is to avoid including the '.' in the extension and to avoid exceptions
            // EDIT:
            // We first need to make sure that either both files or neither file
            // has an extension (otherwise we'll end up comparing the extension of one
            // to the start of the other, or else throwing an exception)
            final int s1Dot = s1.getName().lastIndexOf('.');
            final int s2Dot = s2.getName().lastIndexOf('.');
            if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
                String s1Name = s1.getName().substring(s1Dot + 1);
                String s2Name = s2.getName().substring(s2Dot + 1);
                return s1Name.compareTo(s2Name);
            } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
                return -1;
            } else { // only s1 has an extension, so s1 goes second
                return 1;
            }
        }
    });

    logger.info("Generating " + writerType + " documentation for " + Arrays.stream(sortedExtensionsClasses).

            count() + " components in: " + docsDirectory);

    Arrays.stream(sortedExtensionsClasses).

            forEach(extensionClass ->

    {
                final Class componentClass = extensionClass.asSubclass(ConfigurableComponent.class);
                try {
                    document(docsDirectory, componentClass, writerType);

                } catch (Exception e) {
                    logger.error("Unexpected error for " + extensionClass, e);
                }

            });

    if (writerType.equals("json"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("]");
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    }

}

From source file:de.cbb.mplayer.util.ReflectionHelper.java

/**
 * Searches for a field in the given class and all of its super classes.
 * @param clazz Class to start the search for the field
 * @param name Name of the field//from  w ww  .  j a v  a 2  s  . co m
 * @return The field that was found
 * @throws NoSuchFieldException
 */
public static Field getField(Class<?> clazz, String name) throws NoSuchFieldException {
    Class<?> searchClass = clazz;
    Field field = null;
    while (field == null && searchClass != null) {
        try {
            field = searchClass.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            searchClass = searchClass.getSuperclass();
        }
    }
    if (field == null) {
        throw new NoSuchFieldException(clazz.getSimpleName() + "." + name); //$NON-NLS-1$
    }
    return field;
}

From source file:com.evolveum.midpoint.model.client.ModelClientUtil.java

public static QName getElementName(Class<? extends ObjectType> type) {
    String local = type.getSimpleName();
    int typeIndex = local.lastIndexOf("Type");
    if (typeIndex > 0) {
        local = local.substring(0, typeIndex);
    }/*from  w  w w. j a v  a  2 s  .  c  om*/
    if (Character.isUpperCase(local.charAt(0))) {
        local = local.substring(0, 1).toLowerCase() + local.substring(1);
    }
    return new QName(NS_COMMON, local);
}

From source file:com.feilong.core.lang.ClassLoaderUtil.java

/**
 * ? {@link ClassLoader}./*from  www . jav  a2  s . c  om*/
 * 
 * @param callingClass
 *            the calling class
 * @return  <code>callingClass</code> null, {@link NullPointerException}<br>
 * @see java.lang.Class#getClassLoader()
 */
private static ClassLoader getClassLoaderByClass(Class<?> callingClass) {
    Validate.notNull(callingClass, "callingClass can't be null!");
    ClassLoader classLoader = callingClass.getClassLoader();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[{}].getClassLoader():{}", callingClass.getSimpleName(), formatClassLoader(classLoader));
    }
    return classLoader;
}

From source file:com.feilong.core.lang.ClassUtilTest.java

/**
 *  class info map for LOGGER.//from www .  ja va2  s  .  c om
 *
 * @param klass
 *            the klass
 * @return  <code>klass</code> nullempty, {@link Collections#emptyMap()}<br>
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {
    if (isNullOrEmpty(klass)) {
        return Collections.emptyMap();
    }

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.feilong.core.date.DatePattern"
    map.put("clz.getName()", klass.getName());//"com.feilong.core.date.DatePattern"
    map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern"

    map.put("clz.getComponentType()", klass.getComponentType());
    // ?"". ,voidboolean?byte?char?short?int?long?float  double?.
    map.put("clz.isPrimitive()", klass.isPrimitive());

    // ?"".,.
    map.put("clz.isLocalClass()", klass.isLocalClass());
    // ?"?".?,?,?"""??".
    map.put("clz.isMemberClass()", klass.isMemberClass());

    //isSynthetic()?Class?"??".java??false,?true.,JVM???,java??"??"?
    map.put("clz.isSynthetic()", klass.isSynthetic());
    map.put("clz.isArray()", klass.isArray());
    map.put("clz.isAnnotation()", klass.isAnnotation());

    //??true.
    map.put("clz.isAnonymousClass()", klass.isAnonymousClass());
    map.put("clz.isEnum()", klass.isEnum());

    return map;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static String prettyPrint(Type type) {
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = (GenericArrayType) type;
        return prettyPrint(genericArrayType.getGenericComponentType()) + "[]";
    }// w ww.  j  av  a 2  s .c om
    if (type instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) type;
        return wildcardType.toString();
    }
    if (type instanceof TypeVariable) {
        TypeVariable<?> typeVariable = (TypeVariable) type;
        return typeVariable.getName();
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        StringBuilder sb = new StringBuilder();
        sb.append(prettyPrint(parameterizedType.getRawType()));
        Type[] typeArguments = parameterizedType.getActualTypeArguments();
        if (typeArguments != null && typeArguments.length > 0) {
            sb.append("<");
            for (Type typeArgument : typeArguments) {
                sb.append(prettyPrint(typeArgument)).append(", ");
            }
            sb.delete(sb.length() - 2, sb.length()); // last ", "
            sb.append(">");
        }
        return sb.toString();
    }
    Class<?> clazz = (Class<?>) type;
    if (clazz.isArray()) {
        return prettyPrint(clazz.getComponentType()) + "[]";
    }
    return clazz.getSimpleName();
}

From source file:iing.uabc.edu.mx.persistencia.util.JSON.java

private static Object parseObject(JsonParser parser, BeanManager manager) {
    Event evt;/*  w  w w  .ja v a 2s . c  om*/
    String keyName = "";

    do {
        evt = parser.next();

        switch (evt) {
        case START_OBJECT:
            Class objectClass = manager.getType(keyName);
            System.out.println("Nuevo Objeto: " + objectClass.getSimpleName());
            //Create new BeanManager for the new object with its class
            BeanManager objectManager = new BeanManager(objectClass);

            Object result = parseObject(parser, objectManager);

            manager.setProperty(keyName, result);
            break;

        case START_ARRAY:
            //Get element class of the collection
            Class elementClass = manager.getCollectionElementType(keyName);

            System.out.println("Nueva Colleccion de clase: " + elementClass.getSimpleName());

            //Get collection instance from the bean
            Collection collection = (Collection) manager.getProperty(keyName);

            //Create new collection manager with the given class
            CollectionManager collectionManager = new CollectionManager(collection, elementClass);

            collection = parseArray(parser, collectionManager);

            manager.setProperty(keyName, collection);
            break;

        case KEY_NAME:
            //Get attribute name
            keyName = parser.getString();
            System.out.println("KeyName: " + keyName);
            break;

        case VALUE_FALSE:
            manager.setProperty(keyName, false);
            System.out.println("Valor " + keyName + ": " + false);
            break;

        case VALUE_NULL:
            manager.setProperty(keyName, null);
            System.out.println("Valor " + keyName + ": null");
            break;

        case VALUE_NUMBER:
            //double or int
            if (parser.isIntegralNumber()) {
                int value = parser.getInt();
                manager.setProperty(keyName, value);
                System.out.println("Valor " + keyName + ": " + value);
            } else {
                double value = parser.getBigDecimal().doubleValue();
                manager.setProperty(keyName, value);
                System.out.println("Valor " + keyName + ": " + value);
            }
            break;

        case VALUE_STRING:
            String value = parser.getString();

            //Validate if the field is of type Date
            if (manager.getType(keyName) == Date.class) {
                Calendar cal = DatatypeConverter.parseDateTime(value);
                Date date = cal.getTime();
                manager.setProperty(keyName, date);

                System.out.println("Valor " + keyName + ": " + date);
            } else {
                manager.setProperty(keyName, value);
                System.out.println("Valor " + keyName + ": " + value);
            }
            break;
        case VALUE_TRUE:
            manager.setProperty(keyName, true);
            System.out.println("Valor " + keyName + ": " + true);
            break;
        }
    } while (evt != Event.END_OBJECT);

    return manager.getBean();
}

From source file:com.github.woki.payments.adyen.action.Endpoint.java

@SuppressWarnings("unchecked")
private static <ResType extends Error> ResType handleResponse(final HttpResponse response,
        final Class<ResType> responseClass) throws IOException {
    ResType retval;/*from   w w w . ja va2s.  c om*/
    HttpOutcome httpOutcome = handleHttpResponse(response, responseClass);
    if (httpOutcome.content != null) {
        retval = (ResType) httpOutcome.content;
    } else {
        if (httpOutcome.statusCode != HttpStatus.SC_OK) {
            LOG.warn("{} handling failed: {} - {}", responseClass.getSimpleName(), httpOutcome.statusCode,
                    httpOutcome.message);
        }
        try {
            retval = responseClass.newInstance();
            retval.setStatus(httpOutcome.statusCode);
            retval.setMessage(httpOutcome.message);
        } catch (InstantiationException | IllegalAccessException e) {
            LOG.error("{} instantiation failure", responseClass.getSimpleName());
            throw new IOException(e);
        }
    }
    return retval;
}

From source file:com.evolveum.midpoint.model.client.ModelClientUtil.java

public static String getTypeUri(Class<? extends ObjectType> type) {
    String typeUri = NS_COMMON + "#" + type.getSimpleName();
    return typeUri;
}