/*
Note: this should really just throw NoSuchFieldException... need
to change related signatures and code.
189700
protected static Invocable resolveExpectedJavaField(
            Class<?> clas, String fieldName, boolean staticOnly)
            throws UtilEvalError, ReflectError {
        Invocable field = BshClassManager.memberCache
                .get(clas).findField(fieldName);

        if (null == field)
            throw new ReflectError("No such field: "
                    + fieldName + " for class: " + clas.getName());

        if ( staticOnly && !field.isStatic() )
            throw new UtilEvalError(
                "Can't reach instance field: " + fieldName
              + " from static context: " + clas.getName() );

        return field;
    }
157638
protected void checkFieldNotNull( Object fieldValue,
                                      String fieldName ) throws RepositoryException {
        if (fieldValue == null) {
            throw new RepositoryException(JcrI18n.requiredFieldNotSetInConnector.text(getSourceName(), getClass(), fieldName));
        }
    }
459112
private final void sign() throws Exception {
        String dataStr = this.getUserData().toString();
        byte[] data = Base64Coder.getBytes(dataStr);
        byte[] signature = sign(data, this.privateKey);
        this.setSignature(signature);
    }
721509
public static void updateWithSelfSignedServerCertificate(KeyStore pKeyStore)
            throws NoSuchProviderException, NoSuchAlgorithmException, IOException,
                   InvalidKeyException, CertificateException, SignatureException, KeyStoreException {

        final Object x500Name;
        final Object[] certAttributes = { "Jolokia Agent " + Version.getAgentVersion(), // CN
                                          "JVM",                                        // OU
                                          "jolokia.org",                                // O
                                          "Pegnitz",                                    // L
                                          "Franconia",                                  // ST
                                          "DE" };
        if (ClassUtil.checkForClass(X500_NAME_SUN)) {
            x500Name = ClassUtil.newInstance(X500_NAME_SUN, certAttributes);
        } else if (ClassUtil.checkForClass(X500_NAME_IBM)) {
            x500Name = ClassUtil.newInstance(X500_NAME_IBM, certAttributes);
        } else {
            throw new IllegalStateException("Neither Sun- nor IBM-style JVM found.");
        }

        // Need to do it via reflection because Java8 moved class to a different package
        Object keypair = createKeyPair();
        PrivateKey privKey = getPrivateKey(keypair);

        X509Certificate[] chain = new X509Certificate[1];
        chain[0] = getSelfCertificate(keypair, x500Name, new Date(), (long) 3650 * 24 * 60 * 60);
        pKeyStore.setKeyEntry("jolokia-agent", privKey, new char[0], chain);
    }
803864
private Object getFieldValue(Object oldInstance, String fieldName) throws NoSuchFieldException, IllegalAccessException
	{
		Class<? extends Object> c = oldInstance.getClass();
		final Field f = c.getDeclaredField(fieldName);
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			public Object run()
			{
				f.setAccessible(true);
				return null;
			}
		});
		return f.get(oldInstance);
	}
904891
protected void init(Map stormConf, TopologyContext topologyContext) {
		setId(topologyContext.getThisComponentId());

		try {
			method = inputSignature.findMethod(beanType);
			logger.info("{} uses {}", this, method.toGenericString());
		} catch (ReflectiveOperationException e) {
			throw new IllegalStateException("Unusable input signature", e);
		}

		if (spring == null)
			spring = SingletonApplicationContext.get(stormConf, topologyContext);

		spring.getBean(beanType);
		logger.debug("Bean lookup successful");
	}
1160879
public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException {
		doWithFields(clazz, fc, null);
	}
514731
public static void applyKVToBean(Object bean, String key, Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Method getterMethod = bean.getClass().getMethod(Util.getterMethodName(key));
        Method setterMethod = bean.getClass().getMethod(Util.setterMethodName(key), getterMethod.getReturnType());
        setterMethod.invoke(bean, value);
    }
418042
public static void setFieldValue(final Class<?> source, final Object target, final String fieldName, final Object value) throws NoSuchFieldException
    {
        try
        {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>()
            {
                @Override
                public Void run() throws Exception
                {
                    Field field = source.getDeclaredField(fieldName);
                    if(!field.isAccessible())
                    {
                        field.setAccessible(true);
                    }
                    field.set(target, value);
                    return null;
                }
            });
        }
        // Unwrap
        catch (final PrivilegedActionException pae)
        {
            final Throwable t = pae.getCause();
            // Rethrow
            if (t instanceof NoSuchFieldException)
            {
                throw (NoSuchFieldException) t;
            }
            else
            {
                // No other checked Exception thrown by Class.getConstructor
                try
                {
                    throw (RuntimeException) t;
                }
                // Just in case we've really messed up
                catch (final ClassCastException cce)
                {
                    throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
                }
            }
        }
    }
929199
@Override
    public void setNonPersistentMapping(String nonPersistentMapping) throws JMSException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "setNonPersistentMapping", nonPersistentMapping);

        if (nonPersistentMapping == null) {
            throw (JMSException) JmsErrorUtils.newThrowable(
                                                            JMSException.class,
                                                            "INVALID_VALUE_CWSIA0261",
                                                            new Object[] { "nonPersistentMapping", null },
                                                            tc
                            );
        }

        if (nonPersistentMapping.equals(ApiJmsConstants.MAPPING_BEST_EFFORT_NONPERSISTENT) ||
            nonPersistentMapping.equals(ApiJmsConstants.MAPPING_EXPRESS_NONPERSISTENT) ||
            nonPersistentMapping.equals(ApiJmsConstants.MAPPING_RELIABLE_NONPERSISTENT) ||
            nonPersistentMapping.equals(ApiJmsConstants.MAPPING_RELIABLE_PERSISTENT) ||
            nonPersistentMapping.equals(ApiJmsConstants.MAPPING_ASSURED_PERSISTENT) ||
            nonPersistentMapping.equals(ApiJmsConstants.MAPPING_NONE)) {
            jcaManagedConnectionFactory.setNonPersistentMapping(nonPersistentMapping);
        }
        else if (nonPersistentMapping.equals(ApiJmsConstants.MAPPING_AS_SIB_DESTINATION)) {
            jcaManagedConnectionFactory.setNonPersistentMapping(ApiJmsConstants.MAPPING_NONE);
        }
        else {
            throw (JMSException) JmsErrorUtils.newThrowable(
                                                            JMSException.class,
                                                            "INVALID_VALUE_CWSIA0261",
                                                            new Object[] { "nonPersistentMapping", nonPersistentMapping },
                                                            tc
                            );
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "setNonPersistentMapping");
    }
133041
private static JaxInfo[] buildFields(Class<?> clazz, String defaultNS) throws SecurityException, NoSuchFieldException, ClassNotFoundException {
		ArrayList<JaxInfo> fields = null; // allow for lazy instantiation, because many structures won't have XmlType
		Class<?> cls = clazz;
		// Build up Method names from JAXB Annotations
		XmlType xt;
		while((xt = cls.getAnnotation(XmlType.class))!=null) {
			if(fields==null)fields = new ArrayList<JaxInfo>();
			for(String field : xt.propOrder()) {
				if("".equals(field)) break; // odd bug.  "" returned when no fields exist, rather than empty array
				Field rf = cls.getDeclaredField(field);
				Class<?> ft = rf.getType();
				
				boolean required = false;
				boolean nillable = false;
				String xmlName = field;
				String namespace = defaultNS;
				
				XmlElement xe = rf.getAnnotation(XmlElement.class);
				if(xe!=null) {
					xmlName=xe.name();
					required = xe.required();
					nillable = false;
					if(DEFAULT.equals(xmlName)) {
						xmlName = field;
					}
					namespace = xe.namespace();
					if(DEFAULT.equals(namespace)) {
						namespace = defaultNS;
					}
				}
				// If object is a List, then it is possible multiple, per XML/JAXB evaluation
				if(ft.isAssignableFrom(List.class)) {
					Type t = rf.getGenericType();
					String classname = t.toString();
					int start = classname.indexOf('<');
					int end = classname.indexOf('>');
					Class<?> genClass = Class.forName(classname.substring(start+1, end));
					xe = genClass.getAnnotation(XmlElement.class);
					if(xe!=null && !DEFAULT.equals(xe.namespace())) {
						namespace = xe.namespace();
					}
					// add recursed recursed member, marked as array
					fields.add(new JaxInfo(xmlName,namespace,genClass,buildFields(genClass,namespace), genClass.equals(String.class),true,required,nillable));
				} else {
					boolean isString = ft.equals(String.class) || ft.equals(XMLGregorianCalendar.class);
					// add recursed member
					fields.add(new JaxInfo(xmlName,namespace,ft,buildFields(ft,namespace),isString,false,required,nillable));
				}
			}
			cls = cls.getSuperclass();
		};
		if(fields!=null) {
			JaxInfo[] rv = new JaxInfo[fields.size()];
			fields.toArray(rv);
			return rv;
		} else {
			return null;
		}
	}
627138
private void processKeyField(Field field) {
    String fieldName = field.getName();
    Class<?> type = field.getType();
    if (!type.equals(DatastoreKey.class)) {
      String message = String.format("Invalid type, %s, for Key field %s in class %s. ", type,
          fieldName, entityClass);
      throw new EntityManagerException(message);
    }
    KeyMetadata keyMetadata = new KeyMetadata(field);
    entityMetadata.setKeyMetadata(keyMetadata);
  }
368050
@Override
    public FieldVisitor visitField(final int access, final String name,
            final String desc, final String signature, final Object value) {
        if (computeSVUID) {
            if ("serialVersionUID".equals(name)) {
                // since the class already has SVUID, we won't be computing it.
                computeSVUID = false;
                hasSVUID = true;
            }
            /*
             * Remember field for SVUID computation For field modifiers, only
             * the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
             * ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
             * computing serialVersionUID values.
             */
            if ((access & Opcodes.ACC_PRIVATE) == 0
                    || (access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0) {
                int mods = access
                        & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
                                | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
                                | Opcodes.ACC_FINAL | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
                svuidFields.add(new Item(name, mods, desc));
            }
        }

        return super.visitField(access, name, desc, signature, value);
    }
1062925
private Optional<MapPositionSetter> createField(final Class<?> beanClass, final String fieldName) {
        
        final String positionFieldName = fieldName + "Position";
        
        final Field positionField;
        try {
            positionField = beanClass.getDeclaredField(positionFieldName);
            positionField.setAccessible(true);
            
        } catch (NoSuchFieldException | SecurityException e) {
            return Optional.empty();
        }
        
        if(!Map.class.isAssignableFrom(positionField.getType())) {
            return Optional.empty();
        }
        
        final ParameterizedType type = (ParameterizedType) positionField.getGenericType();
        final Class<?> keyType = (Class<?>) type.getActualTypeArguments()[0];
        final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[1];
        
        if(keyType.equals(String.class) && valueType.equals(CellPosition.class)) {
            
            return Optional.of(new MapPositionSetter() {
                
                @SuppressWarnings("unchecked")
                @Override
                public void set(final Object beanObj, final CellPosition position, final String key) {
                    ArgUtils.notNull(beanObj, "beanObj");
                    ArgUtils.notNull(position, "position");
                    
                   try {
                       Map<String, CellPosition> positionMapObj = (Map<String, CellPosition>) positionField.get(beanObj);
                       if(positionMapObj == null) {
                           positionMapObj = new LinkedHashMap<>();
                           positionField.set(beanObj, positionMapObj);
                       }
                       
                       positionMapObj.put(key, position);
                       
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException("fail access position field.", e);
                    }
                }
            });
            
        } else if(keyType.equals(String.class) && valueType.equals(Point.class)) {
            
            return Optional.of(new MapPositionSetter() {
                
                @SuppressWarnings("unchecked")
                @Override
                public void set(final Object beanObj, final CellPosition position, final String key) {
                    ArgUtils.notNull(beanObj, "beanObj");
                    ArgUtils.notNull(position, "position");
                    
                    try {
                        Map<String, Point> positionMapObj = (Map<String, Point>) positionField.get(beanObj);
                        if(positionMapObj == null) {
                            positionMapObj = new LinkedHashMap<>();
                            positionField.set(beanObj, positionMapObj);
                        }
                        
                        
                        positionMapObj.put(key, position.toPoint());
                        
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException("fail access position field.", e);
                    }
                }
            });
            
        } else if(keyType.equals(String.class) && valueType.equals(CellAddress.class)) {
            
            return Optional.of(new MapPositionSetter() {
                
                @SuppressWarnings("unchecked")
                @Override
                public void set(final Object beanObj, final CellPosition position, final String key) {
                    ArgUtils.notNull(beanObj, "beanObj");
                    ArgUtils.notNull(position, "position");
                    
                    try {
                        Map<String, CellAddress> positionMapObj = (Map<String, CellAddress>) positionField.get(beanObj);
                        if(positionMapObj == null) {
                            positionMapObj = new LinkedHashMap<>();
                            positionField.set(beanObj, positionMapObj);
                        }
                        
                        
                        positionMapObj.put(key, position.toCellAddress());
                        
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException("fail access position field.", e);
                    }
                }
            });
        
        }
        
        return Optional.empty();
    }
1352429
public static void badConversion(Field destinationField, Class<?> destinationClass, Field sourceField, Class<?> sourceClass,String plus){
		throw new UndefinedMappingException(MSG.INSTANCE.message(undefinedMappingException,destinationField.getName(),destinationClass.getSimpleName(),sourceField.getName(),sourceClass.getSimpleName()) + ". More information: "+plus);
	}
178784
@Override
    public void visitCode(Code obj) {
        try {
            String signature = SignatureUtils.getReturnSignature(getMethod().getSignature());
            if (signature.startsWith(Values.SIG_QUALIFIED_CLASS_PREFIX) && CollectionUtils.isListSetMap(SignatureUtils.stripSignature(signature))) {
                stack.resetForMethodEntry(this);
                imType = ImmutabilityType.UNKNOWN;

                super.visitCode(obj);

                if ((imType == ImmutabilityType.IMMUTABLE) || (imType == ImmutabilityType.POSSIBLY_IMMUTABLE)) {
                    Method m = getMethod();
                    Statistics.getStatistics().addImmutabilityStatus(clsName, m.getName(), m.getSignature(), imType);
                }
            }
        } catch (ClassNotFoundException cnfe) {
            bugReporter.reportMissingClass(cnfe);
        }
    }
162694
private static void fieldTypeSignature(Result sb, TypeMirror type) throws IOException
    {
        switch (type.getKind())
        {
            case DECLARED:
                classTypeSignature(sb, type);
                break;
            case TYPEVAR:
                typeVariableSignature(sb, (TypeVariable)type);
                break;
            case ARRAY:
                arrayTypeSignature(sb, (ArrayType)type);
                break;
            default:
                //throw new UnsupportedOperationException(type.getKind()+" unsupported");
        }
    }