List of usage examples for java.lang.reflect Field getInt
@CallerSensitive @ForceInline public int getInt(Object obj) throws IllegalArgumentException, IllegalAccessException
From source file:org.apache.ddlutils.PlatformInfo.java
/** * Adds a mapping from jdbc type to database-native type. Note that this * method accesses the named constant in {@link java.sql.Types} via reflection * and is thus safe to use under JDK 1.2/1.3 even with constants defined * only in later Java versions - for these, the method simply will not add * a mapping.// www .jav a2 s .c o m * * @param jdbcTypeName The jdbc type name, one of the constants defined * in {@link java.sql.Types} * @param nativeType The native type * @param targetJdbcTypeName The jdbc type corresponding to the native type * (e.g. when reading the model from the database) */ public void addNativeTypeMapping(String jdbcTypeName, String nativeType, String targetJdbcTypeName) { try { Field sourceType = Types.class.getField(jdbcTypeName); Field targetType = Types.class.getField(targetJdbcTypeName); if ((sourceType != null) && (targetType != null)) { addNativeTypeMapping(sourceType.getInt(null), nativeType, targetType.getInt(null)); } } catch (Exception ex) { // ignore -> won't be defined _log.warn("Cannot add native type mapping for undefined jdbc type " + jdbcTypeName + ", target jdbc type " + targetJdbcTypeName, ex); } }
From source file:org.slc.sli.api.service.BasicServiceTest.java
@SuppressWarnings("unchecked") @Test//from www. jav a2 s .co m public void testGetResponseEntitiesBatchLimit() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { securityContextInjector.setDualContext(); SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT); List<Entity> entities = new ArrayList<Entity>(); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); for (int i = 0; i < 30; i++) { String id = "student" + i; entities.add( new MongoEntity("student", id, new HashMap<String, Object>(), new HashMap<String, Object>())); studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } final int mockBatchSize = 10; Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))) .thenReturn(entities.subList(0, mockBatchSize)) .thenReturn(entities.subList(mockBatchSize, mockBatchSize * 2)) .thenReturn(entities.subList(mockBatchSize * 2, mockBatchSize * 3)) .thenReturn(new ArrayList<Entity>()); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())) .thenReturn(studentContext); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())) .thenReturn(new HashSet<GrantedAuthority>()); Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection()); Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess( Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection()); NeutralQuery query = new NeutralQuery(); query.setLimit(MAX_RESULT_SIZE); Field batchSize = BasicService.class.getDeclaredField("batchSize"); batchSize.setAccessible(true); int prevBatchSize = batchSize.getInt(service); batchSize.set(service, mockBatchSize); Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class); method.setAccessible(true); RequestUtil.setCurrentRequestId(); Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))) .thenReturn(entities.subList(0, mockBatchSize)) .thenReturn(entities.subList(mockBatchSize, mockBatchSize * 2)) .thenReturn(entities.subList(mockBatchSize * 2, mockBatchSize * 3)) .thenReturn(new ArrayList<Entity>()); Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23"); assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator()); long count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); // Assure same order and count. RequestUtil.setCurrentRequestId(); Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))) .thenReturn(entities.subList(0, mockBatchSize)) .thenReturn(entities.subList(mockBatchSize, mockBatchSize * 2)) .thenReturn(entities.subList(mockBatchSize * 2, mockBatchSize * 3)) .thenReturn(new ArrayList<Entity>()); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23"); assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); batchSize.set(service, prevBatchSize); }
From source file:com.ferdi2005.secondgram.voip.VoIPService.java
public boolean hasEarpiece() { if (((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getPhoneType() != TelephonyManager.PHONE_TYPE_NONE) return true; if (mHasEarpiece != null) { return mHasEarpiece; }/* www . j a v a 2 s . c o m*/ // not calculated yet, do it now try { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); Method method = AudioManager.class.getMethod("getDevicesForStream", Integer.TYPE); Field field = AudioManager.class.getField("DEVICE_OUT_EARPIECE"); int earpieceFlag = field.getInt(null); int bitmaskResult = (int) method.invoke(am, AudioManager.STREAM_VOICE_CALL); // check if masked by the earpiece flag if ((bitmaskResult & earpieceFlag) == earpieceFlag) { mHasEarpiece = Boolean.TRUE; } else { mHasEarpiece = Boolean.FALSE; } } catch (Throwable error) { FileLog.e("Error while checking earpiece! ", error); mHasEarpiece = Boolean.TRUE; } return mHasEarpiece; }
From source file:cz.tsystems.portablecheckin.MainActivity.java
private void populateTextsAndRbtn(ViewGroup theView) { String fieldName = ""; DMCheckin checkinData = app.getCheckin(); for (int i = 0; i < theView.getChildCount(); i++) { View v = theView.getChildAt(i); Class<? extends View> c = v.getClass(); fieldName = (String) v.getTag(); if (fieldName == null) continue; Field field = null; try {// www. ja v a2 s . com field = DMCheckin.class.getField(fieldName.toLowerCase(Locale.ENGLISH)); } catch (NoSuchFieldException e) { Log.v(TAG, "NOT FOUND :" + fieldName.toLowerCase(Locale.ENGLISH)); continue; } Log.v(TAG, fieldName.toLowerCase(Locale.ENGLISH)); try { if (c == EditText.class || c == vinEditText.class || c == BaseEditText.class) { EditText editText = (EditText) v; editText.setText(""); if (field.get(checkinData) == null) continue; DecimalFormat nf = new DecimalFormat("#"); if (field.getType() == String.class)// jnCheckin.hasNonNull(fieldName)) editText.setText((String) field.get(checkinData)); else if (field.getType() == int.class) editText.setText(String.valueOf(field.getInt(checkinData))); else if (field.getType() == short.class) editText.setText(String.valueOf(field.getShort(checkinData))); else if (field.getType() == double.class) editText.setText(nf.format(field.getDouble(checkinData))); else if (field.getType() == Double.class) editText.setText(NumberFormat.getInstance().format((Double) field.get(checkinData))); else if (field.getType() == Date.class) editText.setText(sdto.format((Date) field.get(checkinData))); } else if (c == Switch.class) { ((Switch) v).setChecked(field.getBoolean(checkinData)); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.cloudera.sqoop.SqoopOptions.java
/** * Return a Properties instance that encapsulates all the "sticky" * state of this SqoopOptions that should be written to a metastore * to restore the job later.// ww w. ja v a2 s.co m */ public Properties writeProperties() { Properties props = new Properties(); try { Field[] fields = getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { putProperty(props, propName, Integer.toString(f.getInt(this))); } else if (typ.equals(boolean.class)) { putProperty(props, propName, Boolean.toString(f.getBoolean(this))); } else if (typ.equals(long.class)) { putProperty(props, propName, Long.toString(f.getLong(this))); } else if (typ.equals(String.class)) { putProperty(props, propName, (String) f.get(this)); } else if (typ.equals(Integer.class)) { putProperty(props, propName, f.get(this) == null ? "null" : f.get(this).toString()); } else if (typ.isEnum()) { putProperty(props, propName, f.get(this).toString()); } else { throw new RuntimeException("Could not set property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } if (this.getConf().getBoolean(METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) { // If the user specifies, we may store the password in the metastore. putProperty(props, "db.password", this.password); putProperty(props, "db.require.password", "false"); } else if (this.password != null) { // Otherwise, if the user has set a password, we just record // a flag stating that the password will need to be reentered. putProperty(props, "db.require.password", "true"); } else { // No password saved or required. putProperty(props, "db.require.password", "false"); } putProperty(props, "db.column.list", arrayToList(this.columns)); setDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); setDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); setArgArrayProperties(props, "tool.arguments", this.extraArgs); return props; }
From source file:com.cloudera.sqoop.SqoopOptions.java
@SuppressWarnings("unchecked") /**// ww w . j a va2 s.c o m * Given a set of properties, load this into the current SqoopOptions * instance. */ public void loadProperties(Properties props) { try { Field[] fields = getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { f.setInt(this, getIntProperty(props, propName, f.getInt(this))); } else if (typ.equals(boolean.class)) { f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this))); } else if (typ.equals(long.class)) { f.setLong(this, getLongProperty(props, propName, f.getLong(this))); } else if (typ.equals(String.class)) { f.set(this, props.getProperty(propName, (String) f.get(this))); } else if (typ.equals(Integer.class)) { String value = props.getProperty(propName, f.get(this) == null ? "null" : f.get(this).toString()); f.set(this, value.equals("null") ? null : new Integer(value)); } else if (typ.isEnum()) { f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString()))); } else { throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } // Now load properties that were stored with special types, or require // additional logic to set. if (getBooleanProperty(props, "db.require.password", false)) { // The user's password was stripped out from the metastore. // Require that the user enter it now. setPasswordFromConsole(); } else { this.password = props.getProperty("db.password", this.password); } if (this.jarDirIsAuto) { // We memoized a user-specific nonce dir for compilation to the data // store. Disregard that setting and create a new nonce dir. String localUsername = System.getProperty("user.name", "unknown"); this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile"); } String colListStr = props.getProperty("db.column.list", null); if (null != colListStr) { this.columns = listToArray(colListStr); } this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs); // Delimiters were previously memoized; don't let the tool override // them with defaults. this.areDelimsManuallySet = true; }
From source file:alice.tuprolog.lib.OOLibrary.java
/** * get the value of the field//www . ja v a 2s. co m */ private boolean java_get(PTerm objId, PTerm fieldTerm, PTerm what) { if (!fieldTerm.isAtom()) { return false; } String fieldName = ((Struct) fieldTerm).getName(); Object obj = null; try { Class<?> cl = null; if (objId.isCompound() && ((Struct) objId).getName().equals("class")) { String clName = null; if (((Struct) objId).getArity() == 1) clName = alice.util.Tools.removeApices(((Struct) objId).getArg(0).toString()); if (clName != null) { try { cl = Class.forName(clName, true, dynamicLoader); } catch (ClassNotFoundException ex) { getEngine().logger.warn("Java class not found: " + clName); return false; } catch (Exception ex) { getEngine().logger.warn("Static field " + fieldName + " not found in class " + alice.util.Tools.removeApices(((Struct) objId).getArg(0).toString())); return false; } } } else { String objName = alice.util.Tools.removeApices(objId.toString()); obj = currentObjects.get(objName); if (obj == null) { return false; } cl = obj.getClass(); } Field field = cl.getField(fieldName); Class<?> fc = field.getType(); field.setAccessible(true); if (fc.equals(Integer.TYPE) || fc.equals(Byte.TYPE)) { int value = field.getInt(obj); return unify(what, new alice.tuprolog.Int(value)); } else if (fc.equals(java.lang.Long.TYPE)) { long value = field.getLong(obj); return unify(what, new alice.tuprolog.Long(value)); } else if (fc.equals(java.lang.Float.TYPE)) { float value = field.getFloat(obj); return unify(what, new alice.tuprolog.Float(value)); } else if (fc.equals(java.lang.Double.TYPE)) { double value = field.getDouble(obj); return unify(what, new alice.tuprolog.Double(value)); } else { // the field value is an object Object res = field.get(obj); return bindDynamicObject(what, res); } } catch (NoSuchFieldException ex) { getEngine().logger.warn("Field " + fieldName + " not found in class " + objId); return false; } catch (Exception ex) { getEngine().logger.warn("Generic error in accessing the field"); return false; } }
From source file:org.restcomm.app.qoslib.Services.LibPhoneStateListener.java
private void checkCDMACellSID(CellLocation cell) { if (cell instanceof CdmaCellLocation) { CdmaCellLocation cdmaCell = (CdmaCellLocation) cell; if (cdmaCell.getSystemId() <= 0) { Field getSIDPointer = null; Field getNIDPointer = null; int SID = 0, NID = 0, BID = cdmaCell.getBaseStationId(); try { getSIDPointer = mPhoneState.previousServiceStateObj.getClass().getDeclaredField("mSystemId"); if (getSIDPointer != null) { getSIDPointer.setAccessible(true); SID = (int) getSIDPointer.getInt(cdmaCell); }/* w ww .j av a2 s .co m*/ getNIDPointer = mPhoneState.previousServiceStateObj.getClass().getDeclaredField("mNetworkId"); if (getNIDPointer != null) { getNIDPointer.setAccessible(true); NID = (int) getNIDPointer.getInt(cdmaCell); } cdmaCell.setCellLocationData(BID, cdmaCell.getBaseStationLatitude(), cdmaCell.getBaseStationLongitude(), SID, NID); // Update the SID and NID that we read from teh Servicestate } catch (Exception e) { //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "checkInnerGsmCellLocation","Field does not exist - mGsmCellLoc"); } } } }
From source file:at.treedb.backup.Import.java
private void adjustFields(DAOiface dao, Class<?> c, Iterator iter) throws Exception { ArrayList<Field> list = ClassDependency.getAllFields(c); ArrayList<Field> dbKeys = new ArrayList<Field>(); ArrayList<Field> detached = new ArrayList<Field>(); // System.out.println("adjust class:" + c.getSimpleName() + ":"); for (Field f : list) { f.setAccessible(true);/*from ww w.j av a2 s . c om*/ if (f.getAnnotation(Detach.class) != null) { detached.add(f); } else if (f.getAnnotation(DBkey.class) != null) { dbKeys.add(f); } } HashMap<Integer, Integer> detachMap = detachIdMap.get(c); HashMap<Integer, Integer> historicMap = historicIdMap.get(c); while (iter.hasNext()) { List<Object> l = iter.next(); for (Object o : l) { Base b = (Base) o; for (Field f : dbKeys) { f.setAccessible(true); Class<?> clazz = f.getAnnotation(DBkey.class).value(); HashMap<Integer, Integer> idMap; Class<?> sel = null; // ClassSelector necessary for ID re-mapping? if (clazz.equals(ClassSelector.class)) { sel = ((ClassSelector) b).getClass(f); if (sel == null) { continue; } idMap = classIdMap.get(sel); } else { idMap = classIdMap.get(clazz); } if (sel != null && f.getType().equals(Long.TYPE)) { long oldKey = f.getLong(b); if (oldKey > 0) { int id = UIelement.extractHistIdFromComposedId(oldKey); if (idMap.get(id) != null) { long newKey = (oldKey & 0xffffffff00000000L) + idMap.get(id); f.setLong(b, newKey); } } } else { int oldKey = f.getInt(b); if (oldKey > 0) { if (c.getName().contains("CIimage")) { System.out.println(f.getName() + ":" + idMap.get(oldKey)); } f.setInt(b, idMap.get(oldKey)); } } } // re-attach detached binary data for (Field f : detached) { int index = f.getAnnotation(Detach.class).index(); String path = Export.createBinaryPath(index, b.getCID(), detachMap.get(b.getDBid())); f.set(b, readData(path)); } // set new historic ID b.setHistId(historicMap.get(b.getHistId())); if (c.equals(CIfile.class)) { ciFileHashSet.add(((CIfile) b).getDBfile()); } dao.update(b); // re-import DBfile data if (c.equals(DBfile.class)) { DBfile file = (DBfile) b; if (ciFileHashSet.contains(file.getHistId())) { // adapt CIfile virtual path: // /files/ciId/uiElementId/fileName String[] split = file.getPath().split("/"); split[2] = "" + classIdMap.get(CI.class).get(Integer.parseInt(split[2])); long composed = Long.parseLong(split[3]); int id = UIelement.extractHistIdFromComposedId(composed); HashMap<Integer, Integer> idMap = classIdMap .get(UIelement.getClassIdFromComposedId(composed)); split[3] = "" + ((composed & 0xffffffff00000000L) + idMap.get(id)); StringBuffer buf = new StringBuffer(); for (String s : split) { if (s.equals("")) { continue; } buf.append("/"); buf.append(s); } dBFilePathField.set(file, buf.toString()); } writeFile(dao, file, Export.FILES_DIR + fileIdMap.get(file.getDBid())); } dao.flush(); // try to free memory if (b instanceof CIblob) { // for EclipseLink a session clearing necessary! only // detaching isn't working really - // memory consumption is increasing in spite of detaching // objects! if (dao.isJPA() && dao.getJPAimpl() == DAO.JPA_IMPL.ECLIPSELINK) { dao.clear(); } else { dao.detach(b); } // clear binary data ((CIblob) b).resetBlob(); b = null; } } } }
From source file:net.storyspace.StorySpace.java
/** * Convenience method for making Dates. Because Date is a tricksy bugger of * a class.//from www. j a v a2 s . c o m * * @param year * @param month * @param day * @return date object */ public static Date getDate(int year, String month, int day) { try { Field field = GregorianCalendar.class.getField(month.toUpperCase()); int m = field.getInt(null); Calendar date = new GregorianCalendar(year, m, day); return date.getTime(); } catch (Exception x) { throw new IllegalArgumentException(x.getMessage()); } }