Search in sources :

Example 96 with Field

use of java.lang.reflect.Field in project persistence by casidiablo.

the class SqliteAdapterImpl method delete.

@Override
public <T> int delete(Class<T> theClass, String where, String[] whereArgs, boolean onCascade) {
    DatabaseSpec.Relationship relationship = mDatabaseSpec.getRelationship(theClass);
    if (!relationship.equals(DatabaseSpec.Relationship.UNKNOWN)) {
        Field idField = SQLHelper.getPrimaryKeyField(theClass);
        idField.setAccessible(true);
        switch(relationship) {
            case HAS_MANY:
                if (onCascade) {
                    HasMany hasMany = mDatabaseSpec.has(theClass);
                    List<T> toDelete = findAll(theClass, where, whereArgs);
                    for (T object : toDelete) {
                        try {
                            Object objectId = idField.get(object);
                            Class<?> containedClass = hasMany.getContainedClass();
                            String whereForeign = String.format("%s = '%s'", hasMany.getForeignKey(), String.valueOf(objectId));
                            delete(containedClass, whereForeign, null);
                        } catch (IllegalAccessException ignored) {
                        }
                    }
                }
                break;
            case MANY_TO_MANY:
                List<ManyToMany> manyToManyList = mDatabaseSpec.getManyToMany(theClass);
                for (ManyToMany manyToMany : manyToManyList) {
                    String foreignKey;
                    String foreignCurrentKey;
                    Class<?> relationTable;
                    if (manyToMany.getFirstRelation() == theClass) {
                        foreignKey = manyToMany.getMainKey();
                        foreignCurrentKey = manyToMany.getSecondaryKey();
                        relationTable = manyToMany.getSecondRelation();
                    } else {
                        foreignKey = manyToMany.getSecondaryKey();
                        foreignCurrentKey = manyToMany.getMainKey();
                        relationTable = manyToMany.getFirstRelation();
                    }
                    List<T> toRemove = findAll(theClass, where, whereArgs);
                    for (T object : toRemove) {
                        try {
                            Object objectId = idField.get(object);
                            String whereForeign = String.format("%s = '%s'", foreignKey, String.valueOf(objectId));
                            List<String> ids = new ArrayList<String>();
                            if (onCascade) {
                                Cursor deletionCursor = mDbHelper.getDatabase().query(manyToMany.getTableName(), null, whereForeign, null, null, null, null);
                                if (deletionCursor.moveToFirst()) {
                                    do {
                                        int index = deletionCursor.getColumnIndex(foreignCurrentKey);
                                        ids.add(deletionCursor.getString(index));
                                    } while (deletionCursor.moveToNext());
                                }
                                deletionCursor.close();
                            }
                            mDbHelper.getDatabase().delete(manyToMany.getTableName(), whereForeign, null);
                            for (String id : ids) {
                                String whereRest = String.format("%s = '%s'", foreignCurrentKey, id);
                                Cursor cursorRest = mDbHelper.getDatabase().query(manyToMany.getTableName(), null, whereRest, null, null, null, null);
                                // this means there is no other relation with this object, so we can delete it on cascade :)
                                if (cursorRest.getCount() == 0) {
                                    mDbHelper.getDatabase().delete(SQLHelper.getTableName(relationTable), SQLHelper._ID + " = ?", new String[] { id });
                                }
                            }
                        } catch (IllegalAccessException ignored) {
                        }
                    }
                }
                break;
        }
    }
    return mDbHelper.getDatabase().delete(SQLHelper.getTableName(theClass), where, whereArgs);
}
Also used : ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) Field(java.lang.reflect.Field)

Example 97 with Field

use of java.lang.reflect.Field in project checkstyle by checkstyle.

the class TokenUtilsTest method testTokenValueIncorrect2.

@Test
public void testTokenValueIncorrect2() throws Exception {
    final Integer id = 0;
    String[] originalValue = null;
    Field fieldToken = null;
    try {
        // overwrite static field with new value
        final Field[] fields = TokenUtils.class.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if ("TOKEN_VALUE_TO_NAME".equals(field.getName())) {
                fieldToken = field;
                final Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
                originalValue = (String[]) field.get(null);
                field.set(null, new String[] { null });
            }
        }
        TokenUtils.getTokenName(id);
        fail("IllegalArgumentException is expected");
    } catch (IllegalArgumentException expected) {
        // restoring original value, to let other tests pass
        fieldToken.set(null, originalValue);
        assertEquals("given id " + id, expected.getMessage());
    } catch (IllegalAccessException | NoSuchFieldException ex) {
        fail("Exception is expected");
    }
}
Also used : Field(java.lang.reflect.Field) Test(org.junit.Test)

Example 98 with Field

use of java.lang.reflect.Field in project checkstyle by checkstyle.

the class TokenUtilsTest method testGetIntFromInaccessibleField.

@Test
public void testGetIntFromInaccessibleField() throws NoSuchFieldException {
    final Field field = Integer.class.getDeclaredField("value");
    try {
        TokenUtils.getIntFromField(field, 0);
        fail("IllegalStateException is expected");
    } catch (IllegalStateException expected) {
        assertTrue(expected.getMessage().startsWith("java.lang.IllegalAccessException: Class" + " com.puppycrawl.tools.checkstyle.utils.TokenUtils" + " can not access a member of class java.lang.Integer with modifiers "));
    }
}
Also used : Field(java.lang.reflect.Field) Test(org.junit.Test)

Example 99 with Field

use of java.lang.reflect.Field in project checkstyle by checkstyle.

the class TokenUtilsTest method testGetIntFromAccessibleField.

@Test
public void testGetIntFromAccessibleField() throws NoSuchFieldException {
    final Field field = Integer.class.getField("MAX_VALUE");
    assertEquals(Integer.MAX_VALUE, TokenUtils.getIntFromField(field, 0));
}
Also used : Field(java.lang.reflect.Field) Test(org.junit.Test)

Example 100 with Field

use of java.lang.reflect.Field in project clojure by clojure.

the class Reflector method setInstanceField.

public static Object setInstanceField(Object target, String fieldName, Object val) {
    Class c = target.getClass();
    Field f = getField(c, fieldName, false);
    if (f != null) {
        try {
            f.set(target, boxArg(f.getType(), val));
        } catch (IllegalAccessException e) {
            throw Util.sneakyThrow(e);
        }
        return val;
    }
    throw new IllegalArgumentException("No matching field found: " + fieldName + " for " + target.getClass());
}
Also used : Field(java.lang.reflect.Field)

Aggregations

Field (java.lang.reflect.Field)4517 Method (java.lang.reflect.Method)500 Test (org.junit.Test)475 ArrayList (java.util.ArrayList)434 IOException (java.io.IOException)276 HashMap (java.util.HashMap)263 Map (java.util.Map)253 List (java.util.List)146 InvocationTargetException (java.lang.reflect.InvocationTargetException)136 Pattern (java.util.regex.Pattern)121 Matcher (java.util.regex.Matcher)115 File (java.io.File)93 HashSet (java.util.HashSet)91 Support_Field (tests.support.Support_Field)82 Annotation (java.lang.annotation.Annotation)77 Collection (java.util.Collection)70 SienaException (siena.SienaException)65 Test (org.testng.annotations.Test)64 Before (org.junit.Before)61 Type (java.lang.reflect.Type)57