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:com._4dconcept.springframework.data.marklogic.core.convert.MappingMarklogicConverter.java

@Override
public <R> R read(Class<R> returnType, MarklogicContentHolder holder) {
    ResultItem resultItem = (ResultItem) holder.getContent();
    if (String.class.equals(returnType)) {
        return returnType.cast(resultItem.asString());
    }//from  w  ww  .j av a  2  s  .  c o  m

    R result = null;
    if (returnType.isPrimitive()) {
        try {
            Method method = MarklogicTypeUtils.primitiveMap.get(returnType).getMethod("valueOf", String.class);
            @SuppressWarnings("unchecked")
            R obj = (R) method.invoke(null, resultItem.asString());
            result = obj;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            LOGGER.debug("Unable to generate primitive value for type " + returnType.getName());
        }
    }

    if (result != null) {
        return result;
    }

    ConversionService conversionService = getConversionService();

    if (conversionService.canConvert(resultItem.getClass(), returnType)) {
        R convert = conversionService.convert(resultItem, returnType);

        if (convert == null) {
            throw new ConversionFailedException(TypeDescriptor.forObject(resultItem),
                    TypeDescriptor.valueOf(returnType), resultItem, new NullPointerException());
        }

        return convert;
    } else {
        throw new ConverterNotFoundException(TypeDescriptor.forObject(resultItem),
                TypeDescriptor.valueOf(returnType));
    }
}

From source file:jp.go.aist.six.util.core.xml.castor.CastorXmlMapper.java

public <T> T unmarshalFromString(final String xml, final Class<T> type) {
    Object obj = unmarshalFromString(xml);
    return type.cast(obj);
}

From source file:org.solmix.runtime.support.spring.SpringBeanProvider.java

/**
 * {@inheritDoc}//w ww  .j  a v  a  2  s  .  c o  m
 * 
 * @see org.solmix.api.bean.ConfiguredBeanProvider#getBeanOfType(java.lang.String, java.lang.Class)
 */
@Override
public <T> T getBeanOfType(String name, Class<T> type) {
    T t = null;
    try {
        t = type.cast(context.getBean(name, type));
    } catch (NoSuchBeanDefinitionException nsbde) {
        // ignore
    }
    if (t == null && context.getParent() != null) {
        t = dogetBeanOfType0(context.getParent(), name, type);
    }
    if (t == null && original != null) {
        t = original.getBeanOfType(name, type);
    }
    return t;
}

From source file:com.shigengyu.hyperion.core.WorkflowContextBinarySerializer.java

@Override
public <T extends WorkflowContext> T deserialize(final Class<T> clazz, String input) {
    Object workflowContext = null;
    try {/*from  ww  w .  j  a  va 2 s  .  c  o  m*/
        workflowContext = SerializationUtils.deserialize(Base64.decodeBase64(input));
        if (workflowContext == null) {
            return null;
        }
        return clazz.cast(workflowContext);
    } catch (ClassCastException e) {
        if (workflowContext != null) {
            throw new WorkflowContextException("Unable to cast workflow context of type ["
                    + workflowContext.getClass().getName() + "] to [" + clazz.getName() + "]");
        } else {
            throw new WorkflowContextException(e);
        }
    }
}

From source file:com.formkiq.core.form.bean.UUIDConverter.java

/**
 * Convert the specified input object into an output object of the
 * specified type./*  w  ww  .  jav a2s . c  om*/
 *
 * @param <T> Target type of the conversion.
 * @param type Data type to which this value should be converted.
 * @param value The input value to be converted.
 * @return The converted value.
 * @throws Throwable if an error occurs converting to the specified type
 */
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {
    // We have to support Object, too, because this class is sometimes
    // used for a standard to Object conversion
    if (UUID.class.equals(type) || Object.class.equals(type)) {
        return type.cast(value.toString());
    }
    throw conversionException(type, value);
}

From source file:org.solmix.runtime.support.spring.SpringBeanProvider.java

private <T> T dogetBeanOfType0(ApplicationContext context, String name, Class<T> type) {
    T t = null;// ww  w .  ja v a2s. c o m
    if (context != null) {
        t = type.cast(context.getBean(name, type));
        if (t == null && context.getParent() != null)
            t = dogetBeanOfType0(context.getParent(), name, type);
    }
    return t;
}

From source file:uk.ac.imperial.presage2.db.json.JsonStorage.java

private <T> T returnAsType(JsonNode n, Class<T> type) {
    if (type == String.class)
        return type.cast(n.textValue());
    else if (type == Integer.class || type == Integer.TYPE)
        return type.cast(n.asInt());
    else if (type == Double.class || type == Double.TYPE)
        return type.cast(n.asDouble());
    else if (type == Boolean.class || type == Boolean.TYPE)
        return type.cast(n.asBoolean());
    else if (type == Long.class || type == Long.TYPE)
        return type.cast(n.asLong());

    throw new RuntimeException("Unknown type cast request");
}

From source file:de.decoit.simu.cbor.ifmap.deserializer.IdentifierDeserializerManager.java

/**
 * Deserialize an object of the specified class from the specified data items.
 * The attributes and nested tags arrays may be empty but never null.
 *
 * @param <T> Type of the object to be deserialized, must be a subclass of {@link AbstractIdentifier}
 * @param namespace CBOR data item representing the element namespace
 * @param cborName CBOR data item representing the element name
 * @param attributes CBOR array data item containing the element's attributes
 * @param nestedTags CBOR array data item containing the element's nested tags
 * @param identifierType Type of the object to be deserialized
 * @return The deserialized object//w  w  w  .jav  a 2 s.  co m
 * @throws CBORDeserializationException if deserialization failed
 */
public static <T extends AbstractIdentifier> T deserialize(final DataItem namespace, final DataItem cborName,
        final Array attributes, final Array nestedTags, final Class<T> identifierType)
        throws CBORDeserializationException {
    if (namespace == null) {
        throw new IllegalArgumentException("Namespace must not be null");
    }

    if (cborName == null) {
        throw new IllegalArgumentException("CBOR name must not be null");
    }

    if (attributes == null) {
        throw new IllegalArgumentException("Attributes array must not be null");
    }

    if (nestedTags == null) {
        throw new IllegalArgumentException("Nested tags array must not be null");
    }

    if (identifierType == null) {
        throw new IllegalArgumentException("Target identifier type must not be null");
    }

    try {
        // If default deserializers were not registered yet, do so
        if (!initialized) {
            init();
        }

        // Check if a deserializer for this type was registered
        if (registeredDeserializers.containsKey(identifierType)) {
            DictionarySimpleElement elementEntry = getTopLevelElement(namespace, cborName);

            return identifierType.cast(registeredDeserializers.get(identifierType).deserialize(attributes,
                    nestedTags, elementEntry));
        }

        // If no deserializer was found, fail with exception
        throw new UnsupportedOperationException(
                "Cannot deserialize class: " + identifierType.getCanonicalName());
    } catch (RuntimeException ex) {
        throw new CBORDeserializationException(
                "RuntimeException during deserialization, see nested exception" + "for details", ex);
    }
}

From source file:fr.aliasource.webmail.book.MinigContact.java

public <T> T adapt(Class<T> target) {
    if (target.equals(Contact.class)) {
        return target.cast(obm);
    }// w w  w  .  java2s  . c  o  m
    logger.warn("Cannot cast MinigContact to type " + target);
    return null;
}

From source file:io.cettia.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override//from  www  .ja v a 2s  . c  om
        public void on(final ServerSocket socket) {
            log.debug("socket.uri() is {}", socket.uri());
            socket.on("abort", new VoidAction() {
                @Override
                public void on() {
                    socket.close();
                }
            }).on("echo", new Action<Object>() {
                @Override
                public void on(Object data) {
                    socket.send("echo", data);
                }
            }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() {
                @Override
                public void on(Reply<Map<String, Object>> reply) {
                    Map<String, Object> data = reply.data();
                    switch ((String) data.get("type")) {
                    case "resolved":
                        reply.resolve(data.get("data"));
                        break;
                    case "rejected":
                        reply.reject(data.get("data"));
                        break;
                    }
                }
            }).on("/reply/outbound", new Action<Map<String, Object>>() {
                @Override
                public void on(Map<String, Object> data) {
                    switch ((String) data.get("type")) {
                    case "resolved":
                        socket.send("test", data.get("data"), new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    case "rejected":
                        socket.send("test", data.get("data"), null, new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    }
                }
            });
        }
    });
    final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);

    org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server();
    ServerConnector connector = new ServerConnector(jetty);
    jetty.addConnector(connector);
    connector.setPort(8000);
    ServletContextHandler handler = new ServletContextHandler();
    jetty.setHandler(handler);
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    Map<String, String[]> params = req.getParameterMap();
                    if (params.containsKey("heartbeat")) {
                        server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0]));
                    }
                    if (params.containsKey("_heartbeat")) {
                        server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0]));
                    }
                }
            });
            regSetup.addMapping("/setup");
            // For HTTP transport
            Servlet servlet = new AsityServlet().onhttp(httpTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.addMapping("/cettia");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    // For WebSocket transport
    ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler);
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia")
            .configurator(new Configurator() {
                @Override
                public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                    return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer));
                }
            }).build();
    container.addEndpoint(config);

    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--cettia.transports")
            .addArgument("websocket,httpstream,httplongpoll");
    DefaultExecutor executor = new DefaultExecutor();
    // The exit value of mocha is the number of failed tests.
    executor.execute(cmdLine);

    jetty.stop();
}