Example usage for org.apache.commons.lang3 ClassUtils getShortClassName

List of usage examples for org.apache.commons.lang3 ClassUtils getShortClassName

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ClassUtils getShortClassName.

Prototype

public static String getShortClassName(String className) 

Source Link

Document

Gets the class name minus the package name from a String.

The string passed in is assumed to be a class name - it is not checked.

Note that this method differs from Class.getSimpleName() in that this will return "Map.Entry" whilst the java.lang.Class variant will simply return "Entry" .

Usage

From source file:com.greenlaw110.rythm.toString.ToStringStyle.java

/**
 * <p>Gets the short class name for a class.</p>
 *
 * <p>The short class name is the classname excluding
 * the package name.</p>/* ww  w  . j  ava2s .c  o  m*/
 *
 * @param cls  the <code>Class</code> to get the short name of
 * @return the short name
 */
protected String getShortClassName(Class<?> cls) {
    return ClassUtils.getShortClassName(cls);
}

From source file:org.apache.apex.malhar.lib.io.WebSocketInputOperator.java

@Override
public void run() {
    try {//from   www. java 2 s.  c o  m
        connectionClosed = false;
        AsyncHttpClientConfigBean config = new AsyncHttpClientConfigBean();
        config.setIoThreadMultiplier(ioThreadMultiplier);
        config.setApplicationThreadPool(Executors.newCachedThreadPool(new ThreadFactory() {
            private long count = 0;

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName(ClassUtils.getShortClassName(this.getClass()) + "-AsyncHttpClient-" + count++);
                return t;
            }

        }));

        if (client != null) {
            client.closeAsynchronously();
        }

        client = new AsyncHttpClient(config);
        connection = client.prepareGet(uri.toString()).execute(
                new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
                    @Override
                    public void onMessage(String string) {
                        try {
                            T o = convertMessage(string);
                            if (!(skipNull && o == null)) {
                                outputPort.emit(o);
                            }
                        } catch (IOException ex) {
                            LOG.error("Got exception: ", ex);
                        }
                    }

                    @Override
                    public void onOpen(WebSocket ws) {
                        LOG.debug("Connection opened");
                    }

                    @Override
                    public void onClose(WebSocket ws) {
                        LOG.debug("Connection connectionClosed.");
                        connectionClosed = true;
                    }

                    @Override
                    public void onError(Throwable t) {
                        LOG.error("Caught exception", t);
                    }

                }).build()).get(5, TimeUnit.SECONDS);
    } catch (Exception ex) {
        LOG.error("Error reading from " + uri, ex);
        if (client != null) {
            client.close();
        }
        connectionClosed = true;
    }

}

From source file:org.cruk.genologics.api.cache.GenologicsAPICache.java

/**
 * Fetch an object from the cache or, if it's not yet been seen, from the
 * API and store the result in the cache for future use.
 *
 * <p>/*from w w  w .  jav  a2 s .  co m*/
 * Special consideration has to be made for objects that have a "state"
 * parameter to their URIs. See the class description for more details.
 * </p>
 *
 * @param pjp The join point object.
 * @param uri The URI of the object to fetch.
 * @param entityClass The type of object to fetch.
 *
 * @return The object retrieved.
 *
 * @throws Throwable if there is an error.
 */
protected Object loadOrRetrieve(ProceedingJoinPoint pjp, String uri, Class<?> entityClass) throws Throwable {
    if (!isCacheable(entityClass)) {
        return pjp.proceed();
    }

    final boolean statefulEntity = isStateful(entityClass);

    final String className = ClassUtils.getShortClassName(entityClass);

    Ehcache cache = getCache(entityClass);

    CacheStatefulBehaviour callBehaviour = behaviourOverride.get();
    if (callBehaviour == null) {
        callBehaviour = behaviour;
    }

    Locatable genologicsObject = null;
    String key = keyFromUri(uri);
    long version = NO_STATE_VALUE;

    Element wrapper = null;
    if (key != null) {
        wrapper = cache.get(key);
        if (wrapper != null) {
            if (!statefulEntity) {
                genologicsObject = getFromWrapper(wrapper);
            } else {
                version = versionFromUri(uri);

                switch (callBehaviour) {
                case ANY:
                    genologicsObject = getFromWrapper(wrapper);
                    break;

                case LATEST:
                    if (version == NO_STATE_VALUE || version <= wrapper.getVersion()) {
                        genologicsObject = getFromWrapper(wrapper);
                    }
                    break;

                case EXACT:
                    if (version == NO_STATE_VALUE || version == wrapper.getVersion()) {
                        genologicsObject = getFromWrapper(wrapper);
                    }
                    break;
                }
            }
        }
    }

    if (genologicsObject == null) {
        if (logger.isDebugEnabled()) {
            if (version == NO_STATE_VALUE) {
                logger.debug("Don't have {} {} - calling through to API {}", className, key,
                        pjp.getSignature().getName());
            } else {
                logger.debug("Have a different version of {} {} - calling through to API {}", className, key,
                        pjp.getSignature().getName());
            }
        }

        genologicsObject = (Locatable) pjp.proceed();

        if (wrapper == null) {
            // Not already in the cache, so it needs to be stored.
            cache.put(createCacheElement(genologicsObject));
        } else {
            // Most entities already in the cache will just stay there.
            // If though we have a stateful entity, there may be cause
            // to replace the object in the cache depending on how the
            // cache normally behaves. Typically this will be replacing the
            // existing with a newer version or replacing for a difference.
            // When we don't care about versions, the one already in the cache
            // can remain.

            if (statefulEntity) {
                switch (behaviour) {
                case ANY:
                    break;

                case LATEST:
                    if (version > wrapper.getVersion()) {
                        cache.put(createCacheElement(genologicsObject));
                    }
                    break;

                case EXACT:
                    if (version != wrapper.getVersion()) {
                        cache.put(createCacheElement(genologicsObject));
                    }
                    break;
                }
            }
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Already have {} {} in the cache.", className, key);
        }
    }

    return genologicsObject;
}

From source file:org.cruk.genologics.api.cache.GenologicsAPICache.java

/**
 * Join point for the {@code GenologicsAPI.loadAll} method.
 * Examines the cache for objects already loaded and only fetches those
 * that are not already seen (or, for stateful objects, those whose requested
 * state is later than that in the cache).
 *
 * @param <E> The type of LIMS entity referred to.
 * @param pjp The join point object./*from   w ww.  j a v  a2 s.c  o m*/
 *
 * @return The list of entities retrieved.
 *
 * @throws Throwable if there is an error.
 *
 * @see GenologicsAPI#loadAll(Collection)
 */
public <E extends Locatable> List<E> loadAll(ProceedingJoinPoint pjp) throws Throwable {
    @SuppressWarnings("unchecked")
    Collection<LimsLink<E>> links = (Collection<LimsLink<E>>) pjp.getArgs()[0];

    List<E> results = new ArrayList<E>(links == null ? 0 : links.size());

    if (links != null && !links.isEmpty()) {
        Ehcache cache = null;

        List<LimsLink<E>> toFetch = new ArrayList<LimsLink<E>>(links.size());
        List<E> alreadyCached = new ArrayList<E>(links.size());

        Boolean cacheable = null;
        String className = null;
        Boolean stateful = null;

        CacheStatefulBehaviour callBehaviour = behaviourOverride.get();
        if (callBehaviour == null) {
            callBehaviour = behaviour;
        }

        behaviourLock.lock();
        try {
            Iterator<LimsLink<E>> linkIterator = links.iterator();

            // Loop through the links requested and accumulate two lists of links:
            // those that are not in the cache and need to be fetched and those that
            // have already been fetched. While doing this, assemble in "results" those
            // entities already in the cache that don't need to be fetch. This list will
            // have nulls inserted where the entity needs to be fetched.

            while (linkIterator.hasNext()) {
                LimsLink<E> link = linkIterator.next();
                if (link == null) {
                    throw new IllegalArgumentException("link contains a null");
                }
                if (link.getUri() == null) {
                    throw new IllegalArgumentException("A link in the collection has no URI set.");
                }

                if (className == null) {
                    className = ClassUtils.getShortClassName(link.getEntityClass());
                    cacheable = isCacheable(link.getEntityClass());
                    stateful = isStateful(link.getEntityClass());
                }

                E entity = null;
                if (!cacheable) {
                    // Fetch always.
                    toFetch.add(link);
                } else {
                    if (cache == null) {
                        cache = getCache(link.getEntityClass());
                    }

                    String key = keyFromLocatable(link);

                    Element wrapper = cache.get(key);
                    if (wrapper == null) {
                        toFetch.add(link);
                    } else {
                        long version = versionFromLocatable(link);

                        switch (callBehaviour) {
                        case ANY:
                            entity = getFromWrapper(wrapper);
                            alreadyCached.add(entity);
                            break;

                        case LATEST:
                            if (version != NO_STATE_VALUE && version > wrapper.getVersion()) {
                                toFetch.add(link);
                            } else {
                                entity = getFromWrapper(wrapper);
                                alreadyCached.add(entity);
                            }
                            break;

                        case EXACT:
                            if (version != NO_STATE_VALUE && version != wrapper.getVersion()) {
                                toFetch.add(link);
                            } else {
                                entity = getFromWrapper(wrapper);
                                alreadyCached.add(entity);
                            }
                            break;
                        }
                    }
                }
                results.add(entity);
            }
        } finally {
            behaviourLock.unlock();
        }

        if (logger.isWarnEnabled()) {
            if (cache.getCacheConfiguration().getMaxEntriesLocalHeap() < links.size()) {
                logger.warn(
                        "{} {}s are requested, but the cache will only hold {}. Repeated fetches of this collection will always call through to the API.",
                        links.size(), className, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
            }
        }

        if (logger.isDebugEnabled()) {
            if (alreadyCached.size() == links.size()) {
                logger.debug("All {} {}s requested are already in the cache.", links.size(), className);
            } else {
                logger.debug("Have {} {}s in the cache; {} to retrieve.", alreadyCached.size(), className,
                        toFetch.size());
            }
        }

        // If there is anything to fetch, perform the call to the API then
        // fill in the nulls in the "results" list from the entities returned
        // from the API.
        // The end result is that newly fetched items are put into the cache
        // and "results" is a fully populated list.

        if (!toFetch.isEmpty()) {
            assert cacheable != null : "No cacheable flag found";
            assert stateful != null : "No stateful flag found";

            Object[] args = { toFetch };
            @SuppressWarnings("unchecked")
            List<E> fetched = (List<E>) pjp.proceed(args);

            ListIterator<E> resultIterator = results.listIterator();
            ListIterator<E> fetchIterator = fetched.listIterator();

            while (resultIterator.hasNext()) {
                E entity = resultIterator.next();
                if (entity == null) {
                    assert fetchIterator.hasNext() : "Run out of items in the fetched list.";
                    entity = fetchIterator.next();
                    resultIterator.set(entity);

                    if (cacheable) {
                        if (!stateful) {
                            // Entities without state will only have been fetched because they
                            // were not in the cache. These should just be added.

                            cache.put(createCacheElement(entity));
                        } else {
                            // Stateful entities may already be in the cache but may have been
                            // fetched because the requested version is newer or of a different
                            // state. Some care needs to be taken to update its cached version
                            // depending on how the cache normally behaves.

                            String key = keyFromLocatable(entity);
                            Element wrapper = cache.get(key);

                            if (wrapper == null) {
                                // Not already cached, so simply add this entity whatever
                                // its state.

                                cache.put(createCacheElement(entity));
                            } else {
                                // As we have a stateful entity, there may be cause
                                // to replace the object in the cache depending on how the
                                // cache normally behaves. Typically this will be replacing the
                                // existing with a newer version or replacing for a difference.
                                // When we don't care about versions, the one already in the cache
                                // can remain.

                                long version = versionFromLocatable(entity);

                                switch (behaviour) {
                                case ANY:
                                    break;

                                case LATEST:
                                    if (version > wrapper.getVersion()) {
                                        cache.put(createCacheElement(entity));
                                    }
                                    break;

                                case EXACT:
                                    if (version != wrapper.getVersion()) {
                                        cache.put(createCacheElement(entity));
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            assert !fetchIterator.hasNext() : "Have further items fetched after populating results list.";
        }
    }

    return results;
}

From source file:org.cruk.genologics.api.debugging.RestClientSnoopingAspect.java

/**
 * Join point for the rest template's {@code get} operations.
 * Logs the URI being fetched and the reply received.
 *
 * @param pjp The AspectJ join point object.
 *
 * @return The reply object.// w w w.  j a v  a2 s . co  m
 *
 * @throws Throwable if there is any failure from the operation.
 * This is also logged if logging is set to DEBUG.
 *
 * @see RestTemplate#getForEntity(java.net.URI, Class)
 * @see RestTemplate#getForObject(java.net.URI, Class)
 */
public Object checkGet(ProceedingJoinPoint pjp) throws Throwable {
    Object uri = pjp.getArgs()[0];
    Class<?> type = (Class<?>) pjp.getArgs()[1];

    if (logger.isDebugEnabled()) {
        logger.debug("Requesting a {} with {} from {}", ClassUtils.getShortClassName(type),
                pjp.getSignature().getName(), uri);
    }

    try {
        Object reply = pjp.proceed();

        if (logger.isDebugEnabled()) {
            displayAfter(reply);
        }

        return reply;
    } catch (Throwable e) {
        fail(e);
        throw e;
    }
}

From source file:org.cruk.genologics.api.debugging.RestClientSnoopingAspect.java

/**
 * Called when something about the REST call has failed. This may be an error
 * from the server (a {@code GenologicsException}) or it may be an error
 * in the code nearer the call than this aspect.
 *
 * @param e The failure.//  w w w.ja v a 2  s.c  o m
 *
 * @throws Throwable Rethrows {@code e} after logging its information.
 */
private void fail(Throwable e) throws Throwable {
    logger.debug("Call failed with {}: {}", ClassUtils.getShortClassName(e.getClass()), e.getMessage());
    throw e;
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

/**
 * Upload a file to the Genologics file store. This always uses the HTTP
 * protocol with the {@code file/id/upload} end point.
 *
 * @param fileURLResource The URL resource of the file on the local machine.
 * @param targetFile The GenologicsFile object that holds the reference to the
 * uploaded file, which was newly created using the API.
 *
 * @throws GenologicsException if the server reports a problem with the upload.
 * @throws IllegalStateException if {@code targetFile} does not have a LIMS id.
 * @throws IOException if there is a problem with the transfer.
 *///from  www .java2 s .c o m
protected void uploadViaHTTP(URLInputStreamResource fileURLResource, GenologicsFile targetFile)
        throws IOException {
    GenologicsEntity entityAnno = checkEntityAnnotated(GenologicsFile.class);

    if (targetFile.getLimsid() == null) {
        // Need to post the file back to the LIMS to obtain a URI and LIMS
        // id for the file object.

        String filesUrl = getServerApiAddress() + entityAnno.uriSection();

        ResponseEntity<GenologicsFile> response = restClient.postForEntity(filesUrl, targetFile,
                GenologicsFile.class);

        reflectiveUpdate(targetFile, response.getBody());

        assert targetFile.getLimsid() != null : "Still no LIMS id on GenologicsFile object.";
    }

    boolean uploadedOk = false;
    try {
        URI uploadURI;
        try {
            uploadURI = new URI(
                    getServerApiAddress() + entityAnno.uriSection() + "/" + targetFile.getLimsid() + "/upload");
        } catch (URISyntaxException e) {
            throw new IOException(
                    "File LIMS id " + targetFile.getLimsid() + " produces an invalid URI for upload.", e);
        }

        logger.info("Uploading {} over {} to {} on {}", fileURLResource.getURL().getPath(),
                uploadURI.getScheme().toUpperCase(), targetFile.getContentLocation().getPath(),
                targetFile.getContentLocation().getHost());

        HttpEntity<MultiValueMap<String, Resource>> requestEntity = new HttpEntity<MultiValueMap<String, Resource>>(
                new LinkedMultiValueMap<String, Resource>(1));

        requestEntity.getBody().add("file", fileURLResource);

        ResponseEntity<String> uploadEntity = fileUploadClient.exchange(uploadURI, HttpMethod.POST,
                requestEntity, String.class);

        uploadedOk = true;

        if (logger.isDebugEnabled()) {
            if (uploadEntity.hasBody()) {
                logger.debug("Upload of file returned a {}: {}",
                        ClassUtils.getShortClassName(uploadEntity.getBody().getClass()),
                        uploadEntity.getBody());
            } else {
                logger.debug("Upload of file succeeded but returned nothing.");
            }
        }
    } finally {
        if (!uploadedOk) {
            try {
                delete(targetFile);
            } catch (Exception e) {
                logger.warn("Failed to clean up GenologicsFile object {} after upload failure:",
                        targetFile.getLimsid(), e);
            }
        }
    }

    if (!uploadedOk) {
        // I don't think the code can get here as other exceptions should
        // have been thrown. To make sure though...

        throw new GenologicsUpdateException("Failed to upload " + fileURLResource.getURL());
    }
}

From source file:org.cruk.genologics.api.jaxb.JaxbAnnotationTest.java

private void fetchMarshalAndCompare(Class<?> entityClass) throws Throwable {
    final String className = ClassUtils.getShortClassName(entityClass);

    XmlRootElement rootElementAnno = entityClass.getAnnotation(XmlRootElement.class);
    if (rootElementAnno == null) {
        fail(className + " has no XmlRootElement annotation");
    }/*  w ww  . jav a2  s.c o m*/

    File exampleFile = new File(exampleDirectory, className.toLowerCase() + ".xml");

    final String originalXml = FileUtils.readFileToString(exampleFile, StandardCharsets.UTF_8);

    Object unmarshalled = marshaller.unmarshal(new StreamSource(new StringReader(originalXml)));

    StringWriter writer = new StringWriter();

    marshaller.marshal(unmarshalled, new StreamResult(writer));

    final String marshalledXml = writer.toString();

    try {
        Diff diff1 = new Diff(originalXml, marshalledXml);
        Diff diff2 = new XmlDiffIgnoreNamespaces(diff1);
        XMLAssert.assertXMLEqual("Remarshalled " + className + " does not match the original", diff2, true);
    } catch (Throwable e) {
        try {
            FileUtils.write(new File("target/" + className + "-original.xml"), originalXml,
                    StandardCharsets.UTF_8);
            FileUtils.write(new File("target/" + className + "-marshalled.xml"), marshalledXml,
                    StandardCharsets.UTF_8);
        } catch (IOException io) {
            // ignore.
        }

        throw e;
    }
}

From source file:org.cruk.genologics.api.jaxb.SerializationTest.java

private void fetchMarshalAndSerialize(Class<?> entityClass) throws Throwable {
    final String className = ClassUtils.getShortClassName(entityClass);

    XmlRootElement rootElementAnno = entityClass.getAnnotation(XmlRootElement.class);
    if (rootElementAnno == null) {
        fail(className + " has no XmlRootElement annotation");
    }/*from  w w w . j a v a  2  s.c om*/

    File exampleFile = new File(exampleDirectory, className.toLowerCase() + ".xml");

    Object unmarshalled = marshaller.unmarshal(new StreamSource(new FileReader(exampleFile)));

    // In the case where the simple serialisation test for the exception
    // hasn't got the unmarshalling aspect around it.
    // See JaxbUnmarshallingAspect.

    if (unmarshalled instanceof JAXBElement<?>) {
        unmarshalled = ((JAXBElement<?>) unmarshalled).getValue();
    }

    ByteArrayOutputStream bstream = new ByteArrayOutputStream(65536);
    try {
        ObjectOutputStream ostream = new ObjectOutputStream(bstream);
        ostream.writeObject(unmarshalled);
        ostream.close();
    } catch (NotSerializableException e) {
        fail(e.getMessage() + " is not serializable.");
    }

    ObjectInputStream istream = new ObjectInputStream(new ByteArrayInputStream(bstream.toByteArray()));
    Object deserialized = istream.readObject();

    compareObjects(unmarshalled, deserialized);
}

From source file:org.cruk.genologics.api.jaxb.SerializationTest.java

private void compareObjects(Object original, Object serialized) throws Throwable {
    assertNotNull("Original object is null", original);
    assertNotNull("Serialized object is null", serialized);

    assertEquals("Object classes are not the same class", original.getClass(), serialized.getClass());

    Class<?> objClass = original.getClass();

    List<java.lang.reflect.Field> fields = new ArrayList<java.lang.reflect.Field>(100);
    Class<?> current = objClass;
    while (!current.equals(Object.class)) {
        for (java.lang.reflect.Field f : current.getDeclaredFields()) {
            if ((f.getModifiers() & modifierMask) == 0) {
                f.setAccessible(true);//ww w .  ja v a2s .  c  o  m
                fields.add(f);
            }
        }
        current = current.getSuperclass();
    }

    for (java.lang.reflect.Field f : fields) {
        String className = ClassUtils.getShortClassName(f.getDeclaringClass());

        Object ovalue = f.get(original);
        Object svalue = f.get(serialized);

        if (ovalue == null) {
            assertNull("Field " + f.getName() + " in " + className
                    + " is null in the original but is not null in the deserialised.", svalue);
        } else {
            assertNotNull("Field " + f.getName() + " in " + className
                    + " is not null in the original but is null in the deserialised.", svalue);
        }

        if (Collection.class.isAssignableFrom(f.getType())) {
            if (ovalue != null) {
                Collection<?> ocoll = (Collection<?>) ovalue;
                Collection<?> scoll = (Collection<?>) svalue;

                assertEquals("Collection field " + f.getName() + " has different content size", ocoll.size(),
                        scoll.size());

                Iterator<?> oiter = ocoll.iterator();
                Iterator<?> siter = scoll.iterator();
                int index = 0;
                while (oiter.hasNext()) {
                    Object o = oiter.next();
                    Object s = siter.next();

                    if (o.getClass().getName().startsWith("com.genologics.ri")) {
                        compareObjects(o, s);
                    } else {
                        assertEquals("Object[" + index + "] in collection " + f.getName() + " in " + className
                                + " are not the same", o, s);
                    }

                    ++index;
                }
            }
        } else {
            if (ovalue != null) {
                if (f.getType().getName().startsWith("com.genologics.ri")
                        && !Enum.class.isAssignableFrom(f.getType())) {
                    compareObjects(ovalue, svalue);
                } else {
                    assertEquals("Objects in field " + f.getName() + " in " + className + " are not the same",
                            ovalue, svalue);
                }
            }
        }
    }
}