List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:com.opencsv.bean.BeanFieldDate.java
/** * Converts the input to/from a calendar object. * <p>This method should work for any type that implements * {@link java.util.Calendar} or is derived from * {@link javax.xml.datatype.XMLGregorianCalendar}. The following types are * explicitly supported://from w w w .ja v a 2s. com * <ul><li>Calendar (always a GregorianCalendar)</li> * <li>GregorianCalendar</li> * <li>XMLGregorianCalendar</li></ul> * It is also known to work with * org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl.</p> * * @param <U> The type to be converted to * @param value The string to be converted into a date/time type or vice * versa * @param fieldType The class of the destination field * @return The object resulting from the conversion * @throws CsvDataTypeMismatchException If the conversion fails */ private <U> U convertCalendar(Object value, Class<U> fieldType) throws CsvDataTypeMismatchException { U o; if (value instanceof String) { // Parse input Date d; try { d = getFormat().parse((String) value); } catch (ParseException e) { CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(value, fieldType); csve.initCause(e); throw csve; } // Make a GregorianCalendar out of it, because this works for all // supported types, at least as an intermediate step. GregorianCalendar gc = new GregorianCalendar(); gc.setTime(d); // XMLGregorianCalendar requires special processing. if (fieldType == XMLGregorianCalendar.class) { try { o = fieldType.cast(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc)); } catch (DatatypeConfigurationException e) { // I've never known how to handle this exception elegantly, // especially since I can't conceive of the circumstances // under which it is thrown. CsvDataTypeMismatchException ex = new CsvDataTypeMismatchException( "It was not possible to initialize an XMLGregorianCalendar."); ex.initCause(e); throw ex; } } else { o = fieldType.cast(gc); } } else { Calendar c; if (value instanceof XMLGregorianCalendar) { c = ((XMLGregorianCalendar) value).toGregorianCalendar(); } else if (value instanceof Calendar) { c = (Calendar) value; } else { throw new CsvDataTypeMismatchException(value, fieldType, NOT_DATE); } o = fieldType.cast(getFormat().format(c.getTime())); } return o; }
From source file:edu.umn.msi.tropix.persistence.service.impl.TropixObjectServiceImpl.java
public TropixObject load(final String userId, final String objectId, final TropixObjectType type) { final Class<? extends TropixObject> clazz = PersistenceModelUtils.getClass(type); final TropixObject object = getTropixObjectDao().loadTropixObject(objectId, clazz); clazz.cast(object); // I cannot believe this needs to be here, try removing it. return object; }
From source file:org.bytesoft.openjtcc.supports.spring.PropagateBeanFactoryImpl.java
@SuppressWarnings("unchecked") public <T> T getBean(Class<T> interfaceClass, String beanId) { Object beanInst = this.applicationContext.getBean(beanId); if (interfaceClass.isInstance(beanInst) // && Compensable.class.isInstance(beanInst)// ) {/* w w w.java 2 s .c om*/ PropagateCompensableProxy<Serializable> proxy = new PropagateCompensableProxy<Serializable>(); proxy.setBeanName(beanId); proxy.setTarget((Compensable<Serializable>) beanInst); proxy.setProxyId(atomic.incrementAndGet()); proxy.setTransactionManager(this.transactionManager); ClassLoader classLoader = beanInst.getClass().getClassLoader(); Class<?>[] interfaces = null; if (Compensable.class.equals(interfaceClass)) { interfaces = new Class[] { interfaceClass }; } else { interfaces = new Class[] { interfaceClass, Compensable.class }; } Object proxyInst = Proxy.newProxyInstance(classLoader, interfaces, proxy); proxy.setFacade((Compensable<Serializable>) proxyInst); return interfaceClass.cast(proxyInst); } throw new RuntimeException(); }
From source file:com.snaplogic.snaps.uniteller.BaseService.java
@Override protected void process(Document document, String inputViewName) { try {// w w w .j av a 2 s . co m AccountBean bean = account.connect(); String UFSConfigFilePath = urlEncoder.validateAndEncodeURI(bean.getConfigFilePath(), PATTERN, null) .toString(); String UFSSecurityFilePath = urlEncoder .validateAndEncodeURI(bean.getSecurityPermFilePath(), PATTERN, null).toString(); /* instantiating USFCreationClient */ Class<?> CustomUSFCreationClient = Class.forName(UFS_FOLIO_CREATION_CLIENT_PKG_URI); Constructor<?> constructor = CustomUSFCreationClient .getDeclaredConstructor(new Class[] { IUFSConfigMgr.class, IUFSSecurityMgr.class }); Object USFCreationClientObj = constructor.newInstance(CustomUFSConfigMgr.getInstance(UFSConfigFilePath), CustomUFSSecurityMgr.getInstance(UFSSecurityFilePath)); Method setAutoUpdatePsw = CustomUSFCreationClient.getDeclaredMethod("setAutoUpdatePsw", Boolean.TYPE); setAutoUpdatePsw.invoke(USFCreationClientObj, autoUpdatePsw); /* Preparing the request for USF */ Object data; if (document != null && (data = document.get()) != null) { if (data instanceof Map) { Map<String, Object> map = (Map<String, Object>) data; Class<?> UFSRequest = Class.forName(getUFSReqClassType()); Object UFSRequestObj = UFSRequest.newInstance(); Object inputFieldValue = null; Calendar cal = Calendar.getInstance(); for (Method method : UFSRequest.getDeclaredMethods()) { if (isSetter(method) && (inputFieldValue = map.get(method.getName().substring(3))) != null) { try { String paramType = method.getParameterTypes()[0].getName(); if (paramType.equalsIgnoreCase(String.class.getName())) { method.invoke(UFSRequest.cast(UFSRequestObj), String.valueOf(inputFieldValue)); } else if (paramType.equalsIgnoreCase(Double.class.getSimpleName())) { method.invoke(UFSRequest.cast(UFSRequestObj), Double.parseDouble(String.valueOf(inputFieldValue))); } else if (paramType.equalsIgnoreCase(INT)) { method.invoke(UFSRequest.cast(UFSRequestObj), Integer.parseInt(String.valueOf(inputFieldValue))); } else if (paramType.equalsIgnoreCase(Calendar.class.getName())) { try { cal.setTime(sdtf.parse(String.valueOf(inputFieldValue))); } catch (ParseException pe1) { try { cal.setTime(sdf.parse(String.valueOf(inputFieldValue))); } catch (ParseException pe) { writeToErrorView( String.format(DATE_PARSER_ERROR, DATETIME_FORMAT, DATE_FORMAT), pe.getMessage(), ERROR_RESOLUTION, pe); } } method.invoke(UFSRequest.cast(UFSRequestObj), cal); } } catch (IllegalArgumentException iae) { writeToErrorView(String.format(ILLEGAL_ARGS_EXE, method.getName()), iae.getMessage(), ERROR_RESOLUTION, iae); } catch (InvocationTargetException ite) { writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(), ERROR_RESOLUTION, ite); } } } /* Invoking the request over USFCreationClient */ Object UFSResponseObj = null; Method creationClientMethod = CustomUSFCreationClient .getMethod(getCamelCaseForMethod(resourceType), UFSRequest); try { UFSResponseObj = creationClientMethod.invoke(USFCreationClientObj, UFSRequest.cast(UFSRequestObj)); } catch (IllegalArgumentException iae) { writeToErrorView(String.format(ILLEGAL_ARGS_EXE, creationClientMethod.getName()), iae.getMessage(), ERROR_RESOLUTION, iae); } catch (InvocationTargetException ite) { writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(), ERROR_RESOLUTION, ite); } if (null != UFSResponseObj) { outputViews.write(documentUtility.newDocument(processResponseObj(UFSResponseObj))); counter.inc(); } } else { writeToErrorView(NO_DATA_ERRMSG, NO_DATA_WARNING, NO_DATA_REASON, NO_DATA_RESOLUTION); } } } catch (Exception ex) { writeToErrorView(ERRORMSG, ex.getMessage(), ERROR_RESOLUTION, ex); } }
From source file:com.oculusinfo.factory.ConfigurableFactory.java
/** * Get one of the goods managed by this factory. * //from w ww . j a va 2 s .com * This version returns a new instance each time it is called. * * @param name The name of the factory from which to obtain the needed * goods. Null indicates that the factory name doesn't matter. * @param goodsType The type of goods desired. */ public <GT> GT produce(String name, Class<GT> goodsType) throws ConfigurationException { if (!_configured) { throw new ConfigurationException("Attempt to get value from uninitialized factory"); } if ((null == name || name.equals(_name)) && goodsType.equals(_factoryType)) { if (_isSingleton) { if (null == _singletonProduct) { synchronized (this) { if (null == _singletonProduct) { _singletonProduct = create(); } } } return goodsType.cast(_singletonProduct); } else { return goodsType.cast(create()); } } else { for (ConfigurableFactory<?> child : _children) { GT result = child.produce(name, goodsType); if (null != result) return result; } } return null; }
From source file:com.mac.tarchan.desktop.event.EventQuery.java
/** * ??????????//from ww w. j av a 2s. co m * * @param type ??? * @return ???? */ public <T> List<T> list(Class<T> type) { ArrayList<T> sublist = new ArrayList<T>(); for (Component child : list) { if (type.isInstance(child)) { sublist.add(type.cast(child)); } } return sublist; }
From source file:de.zib.gndms.infra.system.GNDMSystem.java
public void initialize() throws RuntimeException { try {/*from w w w . j av a2 s. c o m*/ printVersion(); containerHome = new File(System.getenv("GLOBUS_LOCATION")).getAbsoluteFile(); logger.info("Container home directory is '" + containerHome.toString() + '\''); initSharedDir(); createDirectories(); prepareDbStorage(); emf = createEMF(); restrictedEmf = emf; tryTxExecution(); // initialization intentionally deferred to initialize instanceDir = new GNDMSystemDirectory(getSystemName(), uuidGenDelegate, new DefaultWrapper<SystemHolder, Object>(SystemHolder.class) { @Override protected <Y> Y wrapInterfaceInstance(final Class<Y> wrapClass, @NotNull final SystemHolder wrappedParam) { wrappedParam.setSystem(GNDMSystem.this); return wrapClass.cast(wrappedParam); } }, this); instanceDir.addInstance("sys", this); instanceDir.reloadConfiglets(restrictedEmf); // Bad style, usually would be an inner class but // removed it from this source file to reduce source file size actionCaller = new ConfigActionCaller(this); logger.info("getSubGridName() /* gridconfig subGridName */ is '" + getInstanceDir().getSubGridName() + '\''); } catch (Exception e) { logger.error("Initialization failed", e); throw new RuntimeException(e); } }
From source file:bi.meteorite.util.ITestBootstrap.java
protected <T> T getOsgiService(Class<T> type, String filter, long timeout) { ServiceTracker tracker = null;/*from w w w. ja v a 2s. c o m*/ try { String flt; if (filter != null) { if (filter.startsWith("(")) { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")"; } else { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))"; } } else { flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")"; } Filter osgiFilter = FrameworkUtil.createFilter(flt); tracker = new ServiceTracker(bundleContext, osgiFilter, null); tracker.open(true); // Note that the tracker is not closed to keep the reference // This is buggy, as the service reference may change i think Object svc = type.cast(tracker.waitForService(timeout)); if (svc == null) { Dictionary dic = bundleContext.getBundle().getHeaders(); //System.err.println("Test bundle headers: " + TestUtility.explode(dic)); //for (ServiceReference ref : TestUtility.asCollection(bundleContext.getAllServiceReferences(null, null))) { //System.err.println("ServiceReference: " + ref); //} //for (ServiceReference ref : TestUtility.asCollection(bundleContext.getAllServiceReferences(null, flt))) { // System.err.println("Filtered ServiceReference: " + ref); // } throw new RuntimeException("Gave up waiting for service " + flt); } return type.cast(svc); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid filter", e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:com.sap.core.odata.core.edm.EdmBinary.java
@Override protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException { if (!validateLiteral(value, literalKind)) { throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value)); }/*w w w .j a v a 2 s . c om*/ if (!validateMaxLength(value, literalKind, facets)) { throw new EdmSimpleTypeException( EdmSimpleTypeException.LITERAL_FACETS_NOT_MATCHED.addContent(value, facets)); } byte[] result; if (literalKind == EdmLiteralKind.URI) { try { result = Hex.decodeHex( value.substring(value.startsWith("X") ? 2 : 7, value.length() - 1).toCharArray()); } catch (final DecoderException e) { throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e); } } else { result = Base64.decodeBase64(value); } if (returnType.isAssignableFrom(byte[].class)) { return returnType.cast(result); } else if (returnType.isAssignableFrom(Byte[].class)) { Byte[] byteArray = new Byte[result.length]; for (int i = 0; i < result.length; i++) { byteArray[i] = result[i]; } return returnType.cast(byteArray); } else { throw new EdmSimpleTypeException( EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType)); } }
From source file:com.hortonworks.streamline.streams.catalog.topology.component.TopologyComponentFactory.java
private <T extends StreamlineComponent> T getStreamlineComponent(Class<T> clazz, TopologyComponent topologyComponent) { TopologyComponentBundle topologyComponentBundle = getTopologyComponentBundle(topologyComponent); StreamlineComponent component = getProvider(clazz, topologyComponentBundle.getSubType()) .create(topologyComponent);/*from w ww.j a v a 2 s . co m*/ component.setId(topologyComponent.getId().toString()); component.setName(topologyComponent.getName()); component.setConfig(topologyComponent.getConfig()); component.setTopologyComponentBundleId(topologyComponentBundle.getId().toString()); component.setTransformationClass(topologyComponentBundle.getTransformationClass()); return clazz.cast(component); }