List of usage examples for java.lang Class equals
public boolean equals(Object obj)
From source file:com.databasepreservation.visualization.utils.SolrUtils.java
private static <T extends Serializable> void generateRangeValue(StringBuilder ret, Class<T> valueClass, T value) {/*from w w w . j a v a2 s. co m*/ if (value != null) { if (valueClass.equals(Date.class)) { String date = Instant.ofEpochMilli((Date.class.cast(value).getTime())).toString(); LOGGER.trace("Appending date value \"{}\" to range", date); ret.append(date); } else if (valueClass.equals(Long.class)) { ret.append(Long.class.cast(value)); } else if (valueClass.equals(String.class)) { ret.append(String.class.cast(value)); } else { LOGGER.error("Cannot process range of the type {}", valueClass); } } else { ret.append("*"); } }
From source file:com.microsoft.windowsazure.mobileservices.MobileServiceTableBase.java
/** * Returns the id property class defined or annotated in the entity class * @param clazz Target entity class// www . j a v a 2 s. com * @return Property class */ protected static <F> boolean isIntegerClass(Class<F> clazz) { return clazz.equals(Integer.class) || clazz.equals(Long.class) || clazz.equals(int.class) || clazz.equals(long.class); }
From source file:framework.GlobalHelpers.java
public static void setValueOfFieldOrProperty(Object object, String name, Object value) { Field field;//w w w.j ava2 s . c o m try { field = findInheritedField(object.getClass(), name); if (field != null) { field.setAccessible(true); Class<?> type = field.getType(); if (value != null && !type.equals(value.getClass())) { // TODO conversion if (type.equals(String.class)) { value = String.valueOf(value); } else if (type.equals(short.class) || type.equals(Short.class)) { value = Short.valueOf(String.valueOf(value)); } else if (type.equals(int.class) || type.equals(Integer.class)) { value = Integer.valueOf(String.valueOf(value)); } else if (type.equals(long.class) || type.equals(Long.class)) { value = Long.valueOf(String.valueOf(value)); } else if (type.equals(boolean.class) || type.equals(Boolean.class)) { value = Boolean.valueOf(String.valueOf(value)); } else if (type.equals(float.class) || type.equals(Float.class)) { value = Float.valueOf(String.valueOf(value)); } else if (type.equals(double.class) || type.equals(Double.class)) { value = Double.valueOf(String.valueOf(value)); } else if (type.equals(BigDecimal.class)) { value = new BigDecimal(String.valueOf(value)); } } field.set(object, value); } else { BeanUtils.setProperty(object, name, value); } } catch (Exception e) { // do nth, just skip not existing field (maybe log sth?) } }
From source file:com.thesoftwarefactory.vertx.web.model.Form.java
public final static String fieldTypefromClass(Class<?> cls) { Objects.requireNonNull(cls);/* w w w . j av a 2s .c om*/ // by default return TEXT String result = "text"; if (cls.equals(Boolean.class) || cls.equals(boolean.class)) { result = "checkbox"; } else if (Number.class.isAssignableFrom(cls)) { result = "number"; } else if (cls.isEnum()) { result = "select"; } return result; }
From source file:me.hurel.hqlbuilder.internal.ProxyUtil.java
public static Constructor<?> findBestConstructor(Constructor<?>[] constructors) { // First try : find a constructor with only primitive arguments for (Constructor<?> c : constructors) { Class<?>[] parameterTypes = c.getParameterTypes(); if (parameterTypes.length == 0) { return c; } else {/*from ww w .ja v a 2 s . c om*/ boolean useConstructor = true; for (Class<?> parameterType : parameterTypes) { if (!parameterType.isPrimitive()) { useConstructor = false; break; } } if (useConstructor) { return c; } } } // Second try : Okay, let's give a chance to String parameters too for (Constructor<?> c : constructors) { Class<?>[] parameterTypes = c.getParameterTypes(); if (parameterTypes.length == 0) { return c; } else { boolean useConstructor = true; for (Class<?> parameterType : parameterTypes) { if (!parameterType.isPrimitive() && !parameterType.equals(String.class)) { useConstructor = false; break; } } if (useConstructor) { return c; } } } return null; }
From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//*from w w w. ja va 2s. c o m*/ public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject() || root == null) { return root; } Class rootClass = root.getClass(); if (rootClass.isInterface()) { throw new JSONException("Root bean is an interface. " + rootClass); } Map classMap = jsonConfig.getClassMap(); if (classMap == null) { classMap = Collections.EMPTY_MAP; } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) { continue; } String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig); try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key); if (pd != null && pd.getWriteMethod() == null) { log.warn("Property '" + key + "' has no write method. SKIPPED."); continue; } if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig); setProperty(root, key, list, jsonConfig); } else { Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType()); Class targetInnerType = findTargetClass(key, classMap); if (innerType.equals(Object.class) && targetInnerType != null && !targetInnerType.equals(Object.class)) { innerType = targetInnerType; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null); Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig); if (innerType.isPrimitive() || JSONUtils.isNumber(innerType) || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) { array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } else if (!array.getClass().equals(pd.getPropertyType())) { if (!pd.getPropertyType().equals(Object.class)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(Array.newInstance(innerType, 0).getClass()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher( new BeanMorpher(innerType, JSONUtils.getMorpherRegistry())); JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher); } array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } } setProperty(root, key, array, jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(root, key, null, jsonConfig); } else if (!pd.getPropertyType().isInstance(value)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(pd.getPropertyType()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + pd.getPropertyType().getName() + ". Will register a default BeanMorpher"); JSONUtils.getMorpherRegistry().registerMorpher( new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry())); } setProperty(root, key, JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value), jsonConfig); } else { setProperty(root, key, value, jsonConfig); } } else if (root instanceof Map) { setProperty(root, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + root.getClass().getName()); } } else { if (pd != null) { Class targetClass = pd.getPropertyType(); if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass, null); if (targetClass.isArray()) { setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig), jsonConfig); } else if (Collection.class.isAssignableFrom(targetClass)) { setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetClass)) { setProperty(root, key, array, jsonConfig); } else { setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else { if (targetClass == Object.class) { targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else if (root instanceof Map) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + rootClass.getName()); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(root, key, null, jsonConfig); } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return root; }
From source file:com.buaa.cfs.utils.NetUtils.java
/** * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the * socket to./*from ww w .j a v a2 s . c om*/ * * @param socket * @param endpoint the remote address * @param localAddr the local address to bind the socket to * @param timeout timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { Class localClass = localAddr.getClass(); Class remoteClass = endpoint.getClass(); Preconditions.checkArgument(localClass.equals(remoteClass), "Local address %s must be of same family as remote address %s.", localAddr, endpoint); socket.bind(localAddr); } try { if (ch == null) { // let the default implementation handle it. socket.connect(endpoint, timeout); } else { // SocketIOWithTimeout.connect(ch, endpoint, timeout); } } catch (SocketTimeoutException ste) { // throw new ConnectTimeoutException(ste.getMessage()); } // There is a very rare case allowed by the TCP specification, such that // if we are trying to connect to an endpoint on the local machine, // and we end up choosing an ephemeral port equal to the destination port, // we will actually end up getting connected to ourself (ie any data we // send just comes right back). This is only possible if the target // daemon is down, so we'll treat it like connection refused. if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) { LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException("Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port."); } }
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 w w w .j a v a2 s. 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.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils.java
/** * Not really a generic method for printing random object graphs. But it * works for events and decisions./* w ww . ja va2s.c o m*/ */ private static String prettyPrintObject(Object object, String methodToSkip, boolean skipNullsAndEmptyCollections, String indentation, boolean skipLevel) { StringBuffer result = new StringBuffer(); if (object == null) { return "null"; } Class<? extends Object> clz = object.getClass(); if (Number.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (Boolean.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (clz.equals(String.class)) { return (String) object; } if (clz.equals(Date.class)) { return String.valueOf(object); } if (Map.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (Collection.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (!skipLevel) { result.append(" {"); } Method[] eventMethods = object.getClass().getMethods(); boolean first = true; for (Method method : eventMethods) { String name = method.getName(); if (!name.startsWith("get")) { continue; } if (name.equals(methodToSkip) || name.equals("getClass")) { continue; } if (Modifier.isStatic(method.getModifiers())) { continue; } Object value; try { value = method.invoke(object, (Object[]) null); if (value != null && value.getClass().equals(String.class) && name.equals("getDetails")) { value = printDetails((String) value); } } catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } catch (RuntimeException e) { throw (RuntimeException) e; } catch (Exception e) { throw new RuntimeException(e); } if (skipNullsAndEmptyCollections) { if (value == null) { continue; } if (value instanceof Map && ((Map<?, ?>) value).isEmpty()) { continue; } if (value instanceof Collection && ((Collection<?>) value).isEmpty()) { continue; } } if (!skipLevel) { if (first) { first = false; } else { result.append(";"); } result.append("\n"); result.append(indentation); result.append(" "); result.append(name.substring(3)); result.append(" = "); result.append(prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation + " ", false)); } else { result.append( prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation, false)); } } if (!skipLevel) { result.append("\n"); result.append(indentation); result.append("}"); } return result.toString(); }
From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java
private static void assignMapValue(Method getter, Object sourceValue, Method setter, Object destInstance) { System.out.println("*** Map found, resolving its payload types..."); if (sourceValue == null || ((Map) sourceValue).isEmpty()) return;/* w w w .j a v a2 s. co m*/ Map<Integer, Class> sourceMapTypes = detectSourceMapPayload(getter); if (sourceMapTypes.isEmpty() || sourceMapTypes.size() != 2) { System.err.println("Failed to determine source Map payload types, operation aborted !!!"); return; } Class firstSourceArgClass = sourceMapTypes.get(0); Class secondSourceArgClass = sourceMapTypes.get(1); Map<Integer, Class> destMapTypes = detectDestMapPayload(setter); if (destMapTypes.isEmpty() || destMapTypes.size() != 2) { System.err.println("Failed to determine destination Map payload types, operation aborted !!!"); return; } Class firstDestArgClass = destMapTypes.get(0); Class secordDestArgsClass = destMapTypes.get(1); if (!firstSourceArgClass.equals(firstDestArgClass)) { System.err.println("Map key types are different, can't translate values !!!"); return; } System.out.println("*** Map types sorted, populating values..."); Map sourceItems = (Map) sourceValue; Map destItems = createMapOfTypes(firstDestArgClass, secordDestArgsClass); for (Object key : sourceItems.entrySet()) { Entry entry = (Entry) destItems.get(key); Object destValue = transposeModel(secondSourceArgClass, secordDestArgsClass, entry.getValue()); destItems.put(entry.getKey(), destValue); } try { setter.invoke(destInstance, destItems); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("*** done"); }