List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java
public static <RESPONSE_T, REQUEST_T> RESPONSE_T call(HttpClient taxiiClient, URI endpoint, REQUEST_T request, HttpClientContext context, Class<RESPONSE_T> responseClazz) throws JAXBException, IOException { //TaxiiXml taxiiXml = xmlFactory.get().createTaxiiXml(); //String req = taxiiXml.marshalToString(request, true); // Call the service Object responseObj = taxiiClient.callTaxiiService(endpoint, request, context); LOG.info("Request made : " + request.getClass().getCanonicalName() + " => " + responseObj.getClass().getCanonicalName() + " (expected " + responseClazz.getCanonicalName() + ")"); //String resp = taxiiXml.marshalToString(responseObj, true); try {/* w w w . j a va 2 s . co m*/ return responseClazz.cast(responseObj); } catch (ClassCastException cce) { TaxiiXml taxiiXml = xmlFactory.get().createTaxiiXml(); String resp = taxiiXml.marshalToString(responseObj, true); String msg = "Didn't return the response we expected: " + responseObj.getClass() + " \n" + resp; LOG.error(msg, cce); throw new RuntimeException(msg, cce); } }
From source file:demo.config.PropertyConverter.java
/** * Convert the specified value into a Java 5 enum. * /* w w w . j a v a 2 s . c o m*/ * @param value * the value to convert * @param cls * the type of the enumeration * @return the converted value * @throws ConversionException * thrown if the value cannot be converted to an enumeration * * @since 1.5 */ static <E extends Enum<E>> E toEnum(Object value, Class<E> cls) throws ConversionException { if (value.getClass().equals(cls)) { return cls.cast(value); } else if (value instanceof String) { try { return Enum.valueOf(cls, (String) value); } catch (Exception e) { throw new ConversionException("The value " + value + " can't be converted to a " + cls.getName()); } } else if (value instanceof Number) { try { E[] enumConstants = cls.getEnumConstants(); return enumConstants[((Number) value).intValue()]; } catch (Exception e) { throw new ConversionException("The value " + value + " can't be converted to a " + cls.getName()); } } else { throw new ConversionException("The value " + value + " can't be converted to a " + cls.getName()); } }
From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.JobcopyBuilder.java
/** * Reimplementation of {@link Jenkins#getItem(String, ItemGroup, Class)} * //from w w w . ja v a2 s .c o m * Existing implementation has following problems: * * Falls back to {@link Jenkins#getItemByFullName(String)} * * Cannot get {@link ItemGroup} * * @param pathName * @param context * @param klass * @return */ public static <T> T getRelative(String pathName, ItemGroup<?> context, Class<T> klass) { if (context == null) { context = Jenkins.getInstance().getItemGroup(); } if (pathName == null) { return null; } if (pathName.startsWith("/")) { // absolute Item item = Jenkins.getInstance().getItemByFullName(pathName); return klass.isInstance(item) ? klass.cast(item) : null; } Object/*Item|ItemGroup*/ ctx = context; StringTokenizer tokens = new StringTokenizer(pathName, "/"); while (tokens.hasMoreTokens()) { String s = tokens.nextToken(); if (s.equals("..")) { if (!(ctx instanceof Item)) { // can't go up further return null; } ctx = ((Item) ctx).getParent(); continue; } if (s.equals(".")) { continue; } if (!(ctx instanceof ItemGroup)) { return null; } ItemGroup<?> g = (ItemGroup<?>) ctx; Item i = g.getItem(s); if (i == null || !i.hasPermission(Item.READ)) { return null; } ctx = i; } return klass.isInstance(ctx) ? klass.cast(ctx) : null; }
From source file:com.flexive.faces.FxJsfUtils.java
/** * Returns the managed beans of the given class. Works only for flexive beans that * have the full class name and a "fx" prefix by convention. For example, * the ContentEditorBean is registered with JSF as "fxContentEditorBean". * * @param beanClass the beans class/* w ww .j a v a 2 s . c o m*/ * @return the managed beans of the given class, or null if none exists */ public static <T> T getManagedBean(Class<T> beanClass) { return beanClass.cast(getManagedBean("fx" + beanClass.getSimpleName())); }
From source file:com.dicksoft.ocr.xml.Parser.java
/** * Download and parse the specified data set. * /* ww w. j av a 2s. c o m*/ * @param <T> * @param clazz * the Class of the type to be parsed * @param elements * the set of elements to add parsed data to * @throws NotParseableException * if the contract of Parseable is breached */ public static <T extends Parseable> void parse(Class<T> clazz, Set<T> elements) throws NotParseableException { int numElements = 0; try { numElements = parseSize( (String) clazz.getMethod(Parseable.LIST_URL_METHOD, new Class[0]).invoke(null, new Object[0])); for (int i = 0; i < numElements; i++) { String xml = null; try { xml = HttpUtil.fetchText( (String) clazz.getMethod(Parseable.ELEMENT_URL_METHOD, new Class[] { Integer.TYPE }) .invoke(null, new Object[] { i })); } catch (IOException e) { LOG.debug("Composer with ID " + i + "was not found."); continue; } elements.add(clazz.cast( clazz.getMethod("parse", new Class[] { String.class }).invoke(null, new Object[] { xml }))); } } catch (IllegalArgumentException e) { throw new NotParseableException(e); } catch (SecurityException e) { throw new NotParseableException(e); } catch (IllegalAccessException e) { throw new NotParseableException(e); } catch (InvocationTargetException e) { throw new NotParseableException(e); } catch (NoSuchMethodException e) { throw new NotParseableException(e); } }
From source file:com.flexive.shared.EJBLookup.java
/** * Lookup the EJB found under the given Class's name. Uses default flexive naming scheme. * * @param type EJB interface class instance * @param appName EJB application name * @param environment optional environment for creating the initial context * @param <T> EJB interface type * @return a reference to the given EJB//from www . j a v a 2 s . c o m */ protected static <T> T getInterface(Class<T> type, String appName, Hashtable<String, String> environment) { // Try to obtain interface from the lookup cache Object ointerface = ejbCache.get(type.getName()); if (ointerface != null) { return type.cast(ointerface); } // Cache miss: obtain interface and store it in the cache Hashtable<String, String> env; synchronized (EJBLookup.class) { String name; InitialContext ctx = null; env = new Hashtable<String, String>(10); try { if (environment != null) env.putAll(environment); if (used_strategy == null) { appName = discoverStrategy(appName, env, type); if (used_strategy != null) { LOG.info("Working lookup strategy: " + used_strategy); } else { LOG.error("No working lookup strategy found! Possibly because of pending redeployment."); } } prepareEnvironment(used_strategy, env); ctx = new InitialContext(env); name = buildName(appName, type); ointerface = ctx.lookup(name); ejbCache.putIfAbsent(type.getName(), ointerface); return type.cast(ointerface); } catch (Exception exc) { //try one more time with a strategy rediscovery for that bean //this can happen if some beans use mapped names and some not used_strategy = null; try { env.clear(); if (environment != null) env.putAll(environment); appName = discoverStrategy(appName, env, type); if (used_strategy != null) { prepareEnvironment(used_strategy, env); ctx = new InitialContext(env); name = buildName(appName, type); ointerface = ctx.lookup(name); ejbCache.putIfAbsent(type.getName(), ointerface); return type.cast(ointerface); } } catch (Exception e) { LOG.warn("Attempt to rediscover lookup strategy for " + type + " failed!", e); } throw new FxLookupException(LOG, exc, "ex.ejb.lookup.failure", type, exc).asRuntimeException(); } finally { if (ctx != null) try { ctx.close(); } catch (NamingException e) { LOG.error("Failed to close context: " + e.getMessage(), e); } } } }
From source file:com.chiorichan.plugin.loader.Plugin.java
/** * This method provides fast access to the plugin that has {@link #getProvidingPlugin(Class) provided} the given plugin class, which is * usually the plugin that implemented it. * <p>//from w w w. j a v a 2 s . co m * An exception to this would be if plugin's jar that contained the class does not extend the class, where the intended plugin would have resided in a different jar / classloader. * * @param clazz * the class desired * @return the plugin that provides and implements said class * @throws IllegalArgumentException * if clazz is null * @throws IllegalArgumentException * if clazz does not extend {@link Plugin} * @throws IllegalStateException * if clazz was not provided by a plugin, * for example, if called with <code>Plugin.getPlugin(Plugin.class)</code> * @throws IllegalStateException * if called from the static initializer for * given Plugin * @throws ClassCastException * if plugin that provided the class does not * extend the class */ public static <T extends Plugin> T getPlugin(Class<T> clazz) { Validate.notNull(clazz, "Null class cannot have a plugin"); if (!Plugin.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(clazz + " does not extend " + Plugin.class); } final ClassLoader cl = clazz.getClassLoader(); if (!(cl instanceof PluginClassLoader)) { throw new IllegalArgumentException(clazz + " is not initialized by " + PluginClassLoader.class); } Plugin plugin = ((PluginClassLoader) cl).plugin; if (plugin == null) { throw new IllegalStateException("Cannot get plugin for " + clazz + " from a static initializer"); } return clazz.cast(plugin); }
From source file:gov.nih.nci.system.web.util.RESTUtil.java
public static String getLinkIdValue(Element rootElement, String linkName, String targetClassName, String targetClassIdName, String base64encodedUsernameAndPassword) throws gov.nih.nci.system.client.util.xml.XMLUtilityException { log.debug("linkName " + linkName); log.debug("targetClassName " + targetClassName); if (rootElement == null) return null; String idValue = null;/* w w w.java 2 s .c o m*/ try { Element element = rootElement; List children = element.getChildren(); if (children == null || children.size() == 0) return null; Iterator iter = children.iterator(); while (iter.hasNext()) { Element child = (Element) iter.next(); log.debug("child.getName(): " + child.getName()); if (child.getName().equals("link")) { String refName = child.getAttributeValue("ref"); log.debug("refName: " + refName); log.debug("linkName: " + linkName); if (linkName != null && refName.trim().equals(linkName.trim())) { log.debug("Equallllllll"); String href = child.getAttributeValue("href"); log.debug("href " + href); String resourceStr = href.substring(href.indexOf("/rest/") + 6, href.length()); boolean isCollection = false; if (resourceStr.indexOf("/") != resourceStr.lastIndexOf("/")) isCollection = true; log.debug("isCollection " + isCollection); if (isCollection) { Object results = queryLink(targetClassName, href, base64encodedUsernameAndPassword); log.debug("results " + results); if (results == null) return ""; Collection collecton = (Collection) results; Iterator iterator = collecton.iterator(); StringBuffer ids = new StringBuffer(); while (iterator.hasNext()) { Object resultObj = iterator.next(); Class klass = Class.forName(targetClassName); Object targetObject = klass.cast(resultObj); String getIdMethod = "get" + ((targetClassIdName.charAt(0) + "").toUpperCase()) + targetClassIdName.substring(1, targetClassIdName.length()); Method method = klass.getMethod(getIdMethod); Object id = method.invoke(targetObject, null); log.debug("id " + id); ids.append(id.toString()); if (iterator.hasNext()) ids.append(","); } return ids.toString(); } else { Object results = queryLink(targetClassName, href, base64encodedUsernameAndPassword); log.debug("results " + results); Class klass = Class.forName(targetClassName); Object targetObject = klass.cast(results); String getIdMethod = "get" + ((targetClassIdName.charAt(0) + "").toUpperCase()) + targetClassIdName.substring(1, targetClassIdName.length()); Method method = klass.getMethod(getIdMethod); Object id = method.invoke(targetObject, null); return id.toString(); } } } } } catch (Exception e) { e.printStackTrace(); } log.debug("idValue: " + idValue); return idValue; }
From source file:com.databasepreservation.visualization.utils.SolrUtils.java
private static <T> T solrDocumentTo(Class<T> resultClass, SolrDocument doc) throws GenericException { T ret = null;//from ww w .j av a 2s. co m try { if (resultClass.equals(ViewerDatabase.class)) { ret = resultClass.cast(SolrTransformer.toDatabase(doc)); } else if (resultClass.equals(ViewerRow.class)) { ret = resultClass.cast(SolrTransformer.toRow(doc)); } else if (resultClass.equals(SavedSearch.class)) { ret = resultClass.cast(SolrTransformer.toSavedSearch(doc)); } else { throw new GenericException("Cannot find class index name: " + resultClass.getName()); } } catch (ViewerException e) { throw new GenericException("Cannot retrieve " + resultClass.getName(), e); } // if (resultClass.equals(IndexedAIP.class)) { // ret = resultClass.cast(solrDocumentToIndexAIP(doc)); // } else if (resultClass.equals(IndexedRepresentation.class) || // resultClass.equals(Representation.class)) { // ret = resultClass.cast(solrDocumentToRepresentation(doc)); // } else { // throw new GenericException("Cannot find class index name: " + // resultClass.getName()); // } return ret; }
From source file:com.hihsoft.baseclass.web.controller.BaseController.java
public static <T> T getOrCreateRequestAttribute(HttpServletRequest request, String key, Class<T> clazz) { Object value = request.getAttribute(key); if (value == null) { try {//from w w w . j a v a 2 s . c om value = clazz.newInstance(); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } request.setAttribute(key, value); } return clazz.cast(value); }