Example usage for java.lang Class cast

List of usage examples for java.lang Class cast

Introduction

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

Prototype

@SuppressWarnings("unchecked")
@HotSpotIntrinsicCandidate
public T cast(Object obj) 

Source Link

Document

Casts an object to the class or interface represented by this Class object.

Usage

From source file:fr.juanwolf.mysqlbinlogreplicator.service.MySQLEventListener.java

public void actionOnEvent(Event event) throws Exception {
    if (tableName != null && isMappingConcern()) {
        DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get(tableName);
        CrudRepository currentRepository = domainClass.getCrudRepository();
        Class currentClass = domainClass.getDomainClass();
        if (EventType.isDelete(event.getHeader().getEventType())) {
            Object domainObject = currentClass.cast(generateDomainObjectForDeleteEvent(event, tableName));
            currentRepository.delete(domainObject);
            log.debug("Object deleted : {}", domainObject.toString());
        } else if (EventType.isUpdate(event.getHeader().getEventType())) {
            UpdateRowsEventData data = event.getData();
            log.debug("Update event received data = {}", data);
            Object domainObject = currentClass.cast(generateDomainObjectForUpdateEvent(event, tableName));
            currentRepository.save(domainObject);
        } else if (EventType.isWrite(event.getHeader().getEventType())) {
            WriteRowsEventData data = event.getData();
            log.debug("Write event received with data = {}", data);
            Object currentClassInstance = currentClass
                    .cast(generateDomainObjectForWriteEvent(event, tableName));
            currentRepository.save(currentClassInstance);
        }/* ww  w.  j  a  va2s  . com*/
    }
    if (tableName != null && isNestedConcern() && isCrudEvent(event.getHeader().getEventType())) {
        DomainClass domainClass = domainClassAnalyzer.getNestedDomainClassMap().get(tableName);
        for (SQLRequester sqlRequester : domainClass.getSqlRequesters().values()) {
            if (sqlRequester.getExitTableName().equals(tableName)) {
                String primaryKeyValue = getPrimaryKeyFromEvent(event, sqlRequester, tableName);
                Object mainObject = sqlRequester.reverseQueryEntity(sqlRequester.getForeignKey(),
                        sqlRequester.getPrimaryKeyForeignEntity(), primaryKeyValue);
                CrudRepository crudRepository = domainClass.getCrudRepository();
                if (mainObject instanceof List) {
                    List<Object> mainObjectList = (List<Object>) mainObject;
                    for (Object object : mainObjectList) {
                        crudRepository.save(object);
                    }
                } else {
                    crudRepository.save(mainObject);
                }
            }
        }
    }
    if (event.getHeader().getEventType() == EventType.TABLE_MAP) {
        TableMapEventData tableMapEventData = event.getData();
        tableName = tableMapEventData.getTable();
        if (!columnsTypes.containsKey(tableName)) {
            columnsTypes.put(tableName, tableMapEventData.getColumnTypes());
        }
    }
}

From source file:com.haulmont.cuba.web.gui.components.WebAbstractComponent.java

@Override
public <X> X unwrapComposition(Class<X> internalCompositionClass) {
    return internalCompositionClass.cast(getComposition());
}

From source file:com.tascape.qa.th.webui.driver.WebApp.java

public <T extends WebPage> T open(Class<T> pageClass) throws EntityCommunicationException {
    WebPage page = loadedPages.get(pageClass);
    if (page == null) {
        page = PageFactory.initElements(webBrowser.getWebDriver(), pageClass);
        page.setApp(this);
        loadedPages.put(pageClass, page);
    }/*from  ww  w.  j  ava2 s .  co  m*/
    page.get();
    return pageClass.cast(page);
}

From source file:com.jwt.common.aspects.LoggerAspect.java

/**
 * Capture returning of every call to a set function to print parameters of
 * failed call. Will be used for an easier debug.
 *
 * @param joinPoint/*w w  w  .j  a va2  s . c o  m*/
 * @param retVal
 */
@AfterReturning(pointcut = "setPointcut()", returning = "retVal")
public void afterSuccessfulReturn(JoinPoint joinPoint, Object retVal) {
    Date date = new Date();
    System.out.println("Accessed the save pointcut");
    System.out.println("Returned value " + retVal.getClass());

    Class<?> classCast = retVal.getClass();
    Object[] signatureArgs = joinPoint.getArgs();

    for (Object signatureArg : signatureArgs) {
        //TEMPORARY DEV FIX, UNTILL A BETTER SOLUTION IS FOUND
        if (retVal.getClass().getName().equals(signatureArg.getClass().getName())) {

            String classInfo = classCast.cast(retVal).toString().split(",")[0];
            String replacedString = classInfo.replaceAll("result=", "");
            Integer result = Integer.parseInt(replacedString);

            if (result < 0) {
                System.out.println("Reponse " + classCast.cast(retVal));
                //TODO REPLACE WITH LOGGER FILE CALL
                System.out.println(date + "->Salvarea a esuat cu codul " + result + " cu parametrii "
                        + classCast.cast(signatureArg));
            } else {
                System.out.println("Reponse " + classCast.cast(retVal));
                //TODO REPLACE WITH LOGGER FILE CALL
                System.out.println(date + "->Salvarea a fost efectuata cu success cu codul " + result
                        + " cu parametrii " + classCast.cast(signatureArg));
            }

        }
    }
}

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * Method used to parse values for the methods declared in {@link Input}.
 *///from  w  w  w  .ja v a  2  s  . c o  m
public <X> X getInput(String name, Class<X> type, AnnotatedElement anno) {
    // Special case for file uploads
    if (type.isAssignableFrom(UploadedFile.class))
        return type.cast(fileUploads.get(name));

    // Also support just getting the bytes from a file without the name
    if (type.isArray() && type.getComponentType() == Byte.TYPE) {
        UploadedFile uploadedFile = fileUploads.get(name);
        return uploadedFile != null ? type.cast(uploadedFile.getBytes()) : null;
    }

    if (type.isArray() && anno.isAnnotationPresent(Input.MultiValued.class)) {
        // return type is an array; grab all
        Object o = inputParams.get(name);
        return type.cast(parseMultiValue(type, o, anno));
    }

    String v = Strings.extract(inputParams.get(name));

    // boolean is used for checkboxes, and false is encoded as a missing value
    if (type == Boolean.class || type == Boolean.TYPE) {
        @SuppressWarnings("unchecked")
        X x = (X) Boolean.valueOf(v != null && !"false".equalsIgnoreCase(v));
        return x;
    }

    // the remaining types have proper null values
    if (v == null)
        return null;

    return cast(parseSingleValue(type, v, anno, inputArgParsers));
}

From source file:haven.Utils.java

public static <C> C hascause(Throwable t, Class<C> c) {
    while (t != null) {
        if (c.isInstance(t))
            return (c.cast(t));
        t = t.getCause();//w w w  .j av  a  2 s  .c  o m
    }
    return (null);
}

From source file:com.kurtraschke.wmata.gtfsrealtime.services.WMATAAPIService.java

private <T> T mapUrl(URI url, boolean cache, Class<T> theClass, ObjectMapper mapper) throws IOException {

    Element e = _cache.get(url);//  w  ww  . j av a2  s  .c om

    if (cache && e != null) {
        Object value = e.getObjectValue();
        if (theClass.isInstance(value)) {
            return theClass.cast(value);
        }
    }

    CloseableHttpClient client = HttpClients.custom().setConnectionManager(_connectionManager).build();

    HttpGet httpget = new HttpGet(url);
    _limiter.acquire();
    try (CloseableHttpResponse response = client.execute(httpget);
            InputStream responseInputStream = response.getEntity().getContent()) {

        T value = mapper.readValue(responseInputStream, theClass);

        if (cache) {
            _cache.put(new Element(url, value));
        }

        return value;
    }
}

From source file:com.ushahidi.android.presentation.view.ui.fragment.MapPostFragment.java

private <C> C getMapPostComponent(Class<C> componentType) {
    return componentType.cast(((PostActivity) getActivity()).getMapPostComponent());
}

From source file:com.hmsinc.epicenter.model.surveillance.SurveillanceSet.java

/**
 * @param <T>//from   w  ww  .  ja va  2 s.  c o  m
 * @param attributeType
 * @return
 */
@Transient
public <T extends Attribute> Set<T> getAttribute(final Class<T> attributeType) {
    final Set<T> attrs = new HashSet<T>();
    for (Attribute attribute : getAttributes()) {
        if (attributeType.isInstance(attribute)) {
            attrs.add(attributeType.cast(attribute));
        }
    }
    return attrs;
}

From source file:com.wasteofplastic.acidisland.schematics.Schematic.java

/**
 * Get child tag of a NBT structure./*from  w ww . j  av a  2s  .co  m*/
 * 
 * @param items
 *            The parent tag map
 * @param key
 *            The name of the tag to get
 * @param expected
 *            The expected type of the tag
 * @return child tag casted to the expected type
 * @throws DataException
 *             if the tag does not exist or the tag is not of the
 *             expected type
 */
private static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected)
        throws IllegalArgumentException {
    if (!items.containsKey(key)) {
        throw new IllegalArgumentException("Schematic file is missing a \"" + key + "\" tag");
    }
    Tag tag = items.get(key);
    if (!expected.isInstance(tag)) {
        throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName());
    }
    return expected.cast(tag);
}