@SuppressLint("NewApi") private static void downloadMedia(Object sourceButton, Object mMedia) { Field contextField = XposedHelpers.findFirstFieldByExactType(sourceButton.getClass(), Context.class); if (mContext == null) { try { mContext = (Context) contextField.get(sourceButton); } catch (Exception e) { e.printStackTrace(); log("Failed to get Context"); return; } } log("Downloading media..."); Object mMediaType = getObjectField(mMedia, "b"); Field[] mMediaFields = mMedia.getClass().getDeclaredFields(); for (Field iField : mMediaFields) { String fieldType = iField.getClass().getName(); if (fieldType.contains("com.instagram.model") && !fieldType.contains("people")) { try { mMediaType = iField.get(mMedia); } catch (Exception e) { log("Failed to get MediaType class"); Toast.makeText( mContext, ResourceHelper.getString(mContext, R.string.mediatype_error), Toast.LENGTH_LONG) .show(); e.printStackTrace(); return; } } } Object videoType = getStaticObjectField(mMediaType.getClass(), "b"); String linkToDownload; String filenameExtension; String descriptionType; int descriptionTypeId = R.string.photo; if (mMediaType.equals(videoType)) { linkToDownload = (String) getObjectField(mMedia, "E"); filenameExtension = "mp4"; descriptionType = "video"; descriptionTypeId = R.string.video; } else { linkToDownload = (String) getObjectField(mMedia, "s"); filenameExtension = "jpg"; descriptionType = "photo"; descriptionTypeId = R.string.photo; } // Construct filename // username_imageId.jpg descriptionType = ResourceHelper.getString(mContext, descriptionTypeId); String toastMessage = ResourceHelper.getString(mContext, R.string.downloading, descriptionType); Toast.makeText(mContext, toastMessage, Toast.LENGTH_SHORT).show(); Object mUser = getObjectField(mMedia, "p"); String userName = (String) getObjectField(mUser, "b"); String userFullName = (String) getObjectField(mUser, "c"); String itemId = (String) getObjectField(mMedia, "t"); String fileName = userName + "_" + itemId + "." + filenameExtension; if (TextUtils.isEmpty(userFullName)) { userFullName = userName; } File directory = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) .getAbsolutePath() + "/Instagram"); if (!directory.exists()) directory.mkdirs(); String notificationTitle = ResourceHelper.getString(mContext, R.string.username_thing, userFullName, descriptionType); String description = ResourceHelper.getString(mContext, R.string.instagram_item, descriptionType); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(linkToDownload)); request.setTitle(notificationTitle); request.setDescription(description); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, "Instagram/" + fileName); DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); }
private OOFactSet create_factset(Class<?> classObj, boolean all_discrete) { // System.out.println("WorkingMemory.create_factset element "+ element ); OOFactSet newfs = new OOFactSet(classObj); Field[] element_fields = classObj.getDeclaredFields(); for (Field f : element_fields) { String f_name = f.getName(); Class<?>[] f_class = {f.getType()}; System.out.println( "WHat is this f: " + f.getType() + " the name " + f_name + " class " + f.getClass() + " and the name" + f.getClass().getName()); if (Util.isSimpleType(f_class)) { Domain<?> fieldDomain; if (!domainset.containsKey(f_name)) { fieldDomain = DomainFactory.createDomainFromClass(f.getType(), f_name); domainset.put(f_name, fieldDomain); } else fieldDomain = domainset.get(f_name); Annotation[] annotations = f.getAnnotations(); // iterate over the annotations to locate the MaxLength constraint if it exists DomainSpec spec = null; for (Annotation a : annotations) { if (a instanceof DomainSpec) { spec = (DomainSpec) a; // here it is !!! break; } } if (spec != null) { fieldDomain.setReadingSeq(spec.readingSeq()); if (!all_discrete) fieldDomain.setDiscrete(spec.discrete()); } /* * ID3 would * if it is integer and the annotation saying that the field is continuous * ignore the domain * if it is double / float and the annotation saying that the field is continuous * ignore the domain if it has more than 10 values ? * if it is string and the annotation saying that the field is continuous * what to do?? */ newfs.addDomain(f_name, fieldDomain); } } factsets.put(classObj.getName(), newfs); return newfs; }
/** * Creates a new entity * * @param instantiationValues A Map containing the values to set for this new entity. */ protected ActiveRecordBase(Map<String, Object> instantiationValues) { super(); try { Map<String, Field> classFields = EntitiesHelper.getFieldsMap(getClass()); for (String key : instantiationValues.keySet()) { if (classFields.containsKey(key)) { Field field = classFields.get(key); Class fieldClass = field.getClass(); Object data = instantiationValues.get(key); if (fieldClass == Integer.class) { field.setInt(this, ((Integer) data).intValue()); } else if (fieldClass == Byte.class) { field.setByte(this, ((Byte) data).byteValue()); } else if (fieldClass == Short.class) { field.setShort(this, ((Short) data).shortValue()); } else if (fieldClass == Long.class) { field.setLong(this, ((Long) data).longValue()); } else if (fieldClass == Double.class) { field.setDouble(this, ((Double) data).doubleValue()); } else if (fieldClass == Boolean.class) { field.setBoolean(this, ((Boolean) data).booleanValue()); } else { field.set(this, data); } } } } catch (IllegalAccessException e) { // TODO: Fixme } }
public Object toObj(Map map, Class clss, Object instance) { String clazz = (String) map.get("class"); if (TextUtils.isEmpty(clazz)) { return null; } Map fieldMap = (Map) map.get("fields"); if (fieldMap == null || fieldMap.isEmpty()) { return null; } try { Class cls = Class.forName(clazz); if (!cls.equals(clss)) { return null; } if (instance == null) { instance = clss.newInstance(); } for (Object key : fieldMap.keySet()) { Object value = fieldMap.get(key); Field field = clss.getDeclaredField((String) key); field.setAccessible(true); if (field.getClass().isPrimitive()) { field.set(instance, value); } else if (field.getClass().isArray()) { Object[] array = (Object[]) value; Object[] arrField = new Object[array.length]; for (int i = 0; i < array.length; i++) { // todo maybe not null arrField[i] = toObj((Map) array[i], field.getClass().getComponentType(), null); } field.set(instance, arrField); } else { // todo maybe not null field.set(instance, toObj((Map) value, field.getClass(), null)); } } return instance; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Get all the private fields of the obj. * * @param obj to get the fields. * @return a list of fields. */ public static List<String> getFields(Object obj) { List<String> fields = new ArrayList<String>(); Field[] fs = obj.getClass().getDeclaredFields(); for (Field f : fs) { String className = f.getClass().getName(); if (className.startsWith("java.lang") || className.startsWith("java.util.Date")) { fields.add(f.getName()); } } return fields; }
public String getFieldTypeOfValue() { if (fieldTypeOfValue == null && sampleColumnModel != null && !(sampleColumnModel instanceof Map)) { try { Field field = sampleColumnModel.getClass().getDeclaredField(fieldNameOfValue); fieldTypeOfValue = field.getClass().getName(); } catch (Exception ex) { } } return fieldTypeOfValue; }
@SuppressWarnings("unchecked") public Map toMap(Object obj, int depth) { Map outerMap = new HashMap(); if (depth < MAX_DEPTH) { String clazzName = obj.getClass().getCanonicalName(); outerMap.put("class", clazzName); Map fieldMap = new HashMap(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.getClass().isPrimitive()) { try { fieldMap.put(field.getName(), field.get(obj)); } catch (Exception e) { } } else if (field.getClass().isArray()) { try { List list = new ArrayList(); Object[] arrays = (Object[]) field.get(obj); for (Object it : arrays) { list.add(toMap(it, depth + 1)); } fieldMap.put(field.getName(), list); } catch (Exception e) { } } else { try { fieldMap.put(field.getName(), toMap(field.get(obj), depth + 1)); } catch (Exception e) { } } } outerMap.put("fields", fieldMap); } return outerMap; }
/** * Return the component for the given name. * * @param name The name of the component to get. * @return The named component, or null if there is no such component. */ public static Component forName (final String name) { try { Field f = Component.class.getField (name.toUpperCase ()); if (!Modifier.isStatic (f.getModifiers ()) || Component.class.isAssignableFrom (f.getClass ())) return null; return (Component) f.get (null); } catch (Throwable _) { return null; } }
protected AbsCCDataWrapper(Class pojo, Map params, String query) { this.pojo = pojo; this.params = params; this.query = query; // 查找主键类 Field[] pojoFields = pojo.getDeclaredFields(); for (Field pojoField : pojoFields) { if (pojoField.getAnnotation(EmbeddedId.class) != null || pojoField.getAnnotation(Id.class) != null) { this.pojoId = pojoField.getClass(); } } if (this.pojoId == null) { Method[] pojoMethods = pojo.getDeclaredMethods(); for (Method pojoMethod : pojoMethods) { if (pojoMethod.isAnnotationPresent(EmbeddedId.class) || pojoMethod.isAnnotationPresent(Id.class)) { this.pojoId = pojoMethod.getReturnType(); } } } }
private void printGetter(Object o, Class<?> clazz, PrintStream os) { for (Method m : clazz.getDeclaredMethods()) { if (m.getName().startsWith("get")) { os.print("Getter [" + clazz.getSimpleName() + "] " + m.getName()); if (ArrayUtils.contains(baseList, m.getReturnType()) && m.getParameterTypes().length == 0) { try { Object res = m.invoke(o); os.print(", value " + res); } catch (Throwable e) { } } os.println(); } } for (Field f : clazz.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isFinal(f.getModifiers())) { os.print( "Field [" + clazz.getSimpleName() + "] [" + f.getClass().getSimpleName() + "] " + f.getName()); if (ArrayUtils.contains(baseList, f.getType())) { try { Object res = f.get(o); os.print(", value " + res); } catch (Throwable e) { } } os.println(); } } if (clazz.getSuperclass() != null) { printGetter(o, clazz.getSuperclass(), os); } }
public Object getId(Object pojo) { Field idField = selectIdField(pojo.getClass()); if (idField != null) { try { idField.setAccessible(true); Object id = idField.get(pojo); if (id instanceof String && idFieldSelector.isObjectId(idField)) { return new ObjectId(id.toString()); } else { return id; } } catch (IllegalAccessException e) { throw new RuntimeException( "Unable to obtain objectid from field" + idField.getName() + ", class: " + idField.getClass(), e); } } return null; }
public Class getKnownEgressType() { return field.getClass(); }
/* 返回自增长的id,没有自增长时都是返回-1 * @author Comdex * @see com.reflectsky.cozy.Ormer#insert(java.lang.Object) */ @Override public long insert(Object obj) { // TODO 自动生成的方法存根 OperateSet oSet = generateInsertOperateSet(obj); PreparedStatement pstmt = null; ResultSet rs = null; long count = -1; if (oSet == null) { return count; } try { pstmt = conn.prepareStatement(oSet.getStrSql(), Statement.RETURN_GENERATED_KEYS); ormDebug(oSet); } catch (SQLException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } if (pstmt != null) { Vector<Object> param = oSet.getParam(); for (int i = 0; i < param.size(); i++) { Object object = param.get(i); try { pstmt.setObject(i + 1, object); } catch (SQLException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } } // 如果开启方法回调支持功能 if (callbackobj != null) { Class<?> clazz = callbackobj.getClass(); Method[] mtds = clazz.getDeclaredMethods(); for (Method mtd : mtds) { if (mtd.getName().equals("beforeInsert")) { Class<?>[] params = mtd.getParameterTypes(); if (params.length == 2) { if (params[0] == obj.getClass() && params[1] == Ormer.class) { // 用于回调的注入参数Ormer Ormer ormer = this.oManager.NewOrm(); mtd.setAccessible(true); try { mtd.invoke(callbackobj, obj, ormer); } catch (IllegalAccessException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } catch (IllegalArgumentException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } catch (InvocationTargetException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } } } } } } try { pstmt.executeUpdate(); } catch (SQLException e1) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e1.getMessage()); } try { if (!oSet.getAutoKeyName().equals("")) { rs = pstmt.getGeneratedKeys(); if (rs.next()) { long autoId = rs.getLong(1); Field field = null; try { field = obj.getClass().getDeclaredField(oSet.getAutoKeyName()); } catch (NoSuchFieldException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } catch (SecurityException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } field.setAccessible(true); try { if (field.getClass().getName().equals("Integer")) { field.set(obj, (int) autoId); } else if (field.getClass().getName().equals("Short")) { field.set(obj, (short) autoId); } else { field.set(obj, (int) autoId); } this.oManager.closeRs(rs); this.oManager.closeStmt(pstmt); count = autoId; if (callbackobj != null) { Class<?> clazz = callbackobj.getClass(); Method[] mtds = clazz.getDeclaredMethods(); for (Method mtd : mtds) { if (mtd.getName().equals("afterInsert")) { Class<?>[] params = mtd.getParameterTypes(); if (params.length == 2) { if (params[0] == obj.getClass() && params[1] == Ormer.class) { // 用于回调的注入参数Ormer Ormer ormer = this.oManager.NewOrm(); mtd.setAccessible(true); try { mtd.invoke(callbackobj, obj, ormer); } catch (IllegalAccessException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } catch (IllegalArgumentException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } catch (InvocationTargetException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } } } } } } this.oManager.closeStmt(pstmt); return count; } catch (IllegalArgumentException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } catch (IllegalAccessException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } } } else { this.oManager.closeStmt(pstmt); return count; } } catch (SQLException e) { // TODO 自动生成的 catch 块 this.oManager.deBugInfo(e.getMessage()); } } return count; }
/** * Tries to store a key=value pair into the class or object's field. * * @param seckey Section and key in one string. This have to be pre-parsed to confirm with the * naming convention of the config class. * @param value Value string to be stored. * @param into Class to store into. * @param object Object to store into if there is non-static fields. * @throws IllegalArgumentException If there is a parsing or storing problem. */ private static synchronized void storeKeyValue( String seckey, String value, Class<?> into, Object object) throws IllegalArgumentException { // long_key consists of section name/key name ... Field field = null; Class<?> type = null; String tmp; try { field = into.getDeclaredField(seckey); type = field.getType(); if (type.isEnum()) { tmp = value.replaceAll("-", "_"); // - is invalid enum stuff... replace with _. field.set(object, Enum.valueOf((Class<? extends Enum>) type, tmp)); } else if (type.isAssignableFrom(Integer.TYPE)) field.setInt(object, Integer.parseInt(value)); else if (type.isAssignableFrom(Long.TYPE)) field.setLong(object, Long.parseLong(value)); else if (type.isAssignableFrom(Float.TYPE)) field.setFloat(object, Float.parseFloat(value)); else if (type.isAssignableFrom(Double.TYPE)) field.setDouble(object, Double.parseDouble(value)); else if (type.isAssignableFrom(Byte.TYPE)) field.setByte(object, Byte.parseByte(value)); else if (type.isAssignableFrom(String.class)) field.set(object, value); else if (type.isAssignableFrom(Character.TYPE)) { tmp = value; if (tmp.length() == 2) { tmp = tmp.replaceAll("\\t", "\t"); tmp = tmp.replaceAll("\\n", "\n"); tmp = tmp.replaceAll("\\r", "\r"); tmp = tmp.replaceAll("\\\"", "\""); tmp = tmp.replaceAll("\\\'", "\'"); } if (tmp.length() != 1) throw new NumberFormatException(); field.setChar(object, tmp.charAt(0)); } else if (type.isAssignableFrom(Boolean.TYPE)) { tmp = value.toLowerCase(); tmp = tmp.replace("yes", "true"); tmp = tmp.replace("on", "true"); tmp = tmp.replace("1", "true"); field.setBoolean(object, Boolean.valueOf(tmp)); } else { // "unknown" type, lets try a default from String constructor. field.set(object, type.getConstructor(String.class).newInstance(value)); } } catch (SecurityException e) { throw new IllegalArgumentException( "unsupported option " + into.getName() + "." + seckey + ", security protected"); } catch (NoSuchFieldException e) { throw new IllegalArgumentException( "unsupported option " + into.getName() + "." + seckey + ", no such field"); /**/ } catch (NumberFormatException e) { throw new IllegalArgumentException( "illegal number format on " + into.getName() + "." + seckey + ", " + value + " is not " + (type.isAssignableFrom(Integer.TYPE) ? "an " : "a ") + type.getName()); /**/ } catch (IllegalArgumentException e) { // System.err.println("IllegalArgumentException "+e.getMessage()); if (e.getMessage().startsWith("No enum")) { throw new IllegalArgumentException( "unsupported enum value on field " + into.getName() + ", value \"" + value + "\" not valid"); } throw new IllegalArgumentException( "unsupported option field " + into.getName() + "." + seckey + ", illegal argument when setting value"); /**/ } catch (IllegalAccessException e) { throw new IllegalArgumentException( "unsupported option field " + into.getName() + "." + seckey + ", access denied"); /**/ } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", no suitable constructor"); /**/ } catch (InstantiationException e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", instantiation error"); /**/ } catch (InvocationTargetException e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", unable to invocate constructor"); /**/ } catch (EnumConstantNotPresentException e) { System.err.println("EnumConstantNotPresentException " + e.getMessage()); throw new IllegalArgumentException( "unsupported enum value on field " + into.getName() + ", constant \"" + value + "\" not present"); } catch (Exception e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", unknown error in setting value"); /**/ } }
/** * Generate a table containing the data formatted and sorted with their position/offset If the * model is Ordered than a key is created combining the annotation @Section and Position of the * field If a relation @OneToMany is defined, than we iterate recursively through this function * The result is placed in the Map<Integer, List> results */ private void generateCsvPositionMap( Class<?> clazz, Object obj, Map<Integer, List<String>> results) throws Exception { String result = ""; for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); DataField datafield = field.getAnnotation(DataField.class); if (datafield != null) { if (obj != null) { // Retrieve the format, pattern and precision associated to the type Class<?> type = field.getType(); // Create format Format<?> format = FormatFactory.getFormat(type, getLocale(), datafield); // Get field value Object value = field.get(obj); result = formatString(format, value); if (datafield.trim()) { result = result.trim(); } if (datafield.clip() && result.length() > datafield.length()) { result = result.substring(0, datafield.length()); } if (LOG.isDebugEnabled()) { LOG.debug( "Value to be formatted: {}, position: {}, and its formatted value: {}", new Object[] {value, datafield.pos(), result}); } } else { result = ""; } Integer key; if (isMessageOrdered() && obj != null) { // Generate a key using the number of the section // and the position of the field Integer key1 = sections.get(obj.getClass().getName()); Integer key2 = datafield.position(); Integer keyGenerated = generateKey(key1, key2); if (LOG.isDebugEnabled()) { LOG.debug("Key generated: {}, for section: {}", String.valueOf(keyGenerated), key1); } key = keyGenerated; } else { key = datafield.pos(); } if (!results.containsKey(key)) { List<String> list = new LinkedList<String>(); list.add(result); results.put(key, list); } else { List<String> list = results.get(key); list.add(result); } } OneToMany oneToMany = field.getAnnotation(OneToMany.class); if (oneToMany != null) { // Set global variable // Will be used during generation of CSV isOneToMany = true; List<?> list = (List<?>) field.get(obj); if (list != null) { Iterator<?> it = list.iterator(); while (it.hasNext()) { Object target = it.next(); generateCsvPositionMap(target.getClass(), target, results); } } else { // Call this function to add empty value // in the table generateCsvPositionMap(field.getClass(), null, results); } } } }