Example usage for java.lang.reflect Modifier FINAL

List of usage examples for java.lang.reflect Modifier FINAL

Introduction

In this page you can find the example usage for java.lang.reflect Modifier FINAL.

Prototype

int FINAL

To view the source code for java.lang.reflect Modifier FINAL.

Click Source Link

Document

The int value representing the final modifier.

Usage

From source file:org.openmrs.module.distrotools.test.TestUtils.java

/**
 * Modifies a constant in a constants class. If the constant is final and not based on a runtime expression, then
 * it's value will have been inlined by the compiler and this method will have no effect.
 * @param constantsClass the class of constants
 * @param fieldName the field name of the constant
 * @param newValue the new value for the constant
 * @throws Exception if field not found or couldn't be modified
 *//*w ww .  j ava 2  s .  co  m*/
public static void modifyConstant(Class<?> constantsClass, String fieldName, Object newValue) throws Exception {
    Field field = constantsClass.getDeclaredField(fieldName);
    field.setAccessible(true);

    int existingModifiers = field.getModifiers();

    // Remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, existingModifiers & ~Modifier.FINAL);

    field.set(null, newValue);

    // Reset previous modifiers
    modifiersField.setInt(field, existingModifiers);
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteria.java

/**
 * Set the criterion that selects only {@link Member}s that exactly have the
 * specified modifiers. The access modifiers are set separately. Use
 * {@link #withAccess(AccessType...)} to set access modifiers.
 *
 * @param modifiers//w w w .ja v a  2s .  c om
 * @since 1.0.0.0
 */
public void withModifiers(int modifiers) {
    if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers)) {
        throw new IllegalArgumentException(
                "access modifiers are not allowed as argument. Use withAccess() instead.");
    }
    int allowedModifiers = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT
            | Modifier.VOLATILE | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.STRICT
            | Modifier.INTERFACE;

    if ((modifiers & allowedModifiers) == 0) {
        throw new IllegalArgumentException(
                "modifiers must be one of [" + Modifier.toString(allowedModifiers) + "]");
    }

    this.modifiers = modifiers;
}

From source file:org.gradle.build.docs.dsl.source.SourceMetaDataVisitor.java

private int extractModifiers(GroovySourceAST ast) {
    GroovySourceAST modifiers = ast.childOfType(MODIFIERS);
    if (modifiers == null) {
        return 0;
    }/*from w w w  . j  av a 2 s.  c o m*/
    int modifierFlags = 0;
    for (GroovySourceAST child = (GroovySourceAST) modifiers
            .getFirstChild(); child != null; child = (GroovySourceAST) child.getNextSibling()) {
        switch (child.getType()) {
        case LITERAL_private:
            modifierFlags |= Modifier.PRIVATE;
            break;
        case LITERAL_protected:
            modifierFlags |= Modifier.PROTECTED;
            break;
        case LITERAL_public:
            modifierFlags |= Modifier.PUBLIC;
            break;
        case FINAL:
            modifierFlags |= Modifier.FINAL;
            break;
        case LITERAL_static:
            modifierFlags |= Modifier.STATIC;
            break;
        }
    }
    return modifierFlags;
}

From source file:org.eclipse.buildship.docs.source.SourceMetaDataVisitor.java

private int extractModifiers(GroovySourceAST ast) {
    GroovySourceAST modifiers = ast.childOfType(MODIFIERS);
    if (modifiers == null) {
        return 0;
    }/*from  w  w w. jav  a 2  s .c om*/
    int modifierFlags = 0;
    for (GroovySourceAST child = (GroovySourceAST) modifiers
            .getFirstChild(); child != null; child = (GroovySourceAST) child.getNextSibling()) {
        switch (child.getType()) {
        case LITERAL_private:
            modifierFlags |= Modifier.PRIVATE;
            break;
        case LITERAL_protected:
            modifierFlags |= Modifier.PROTECTED;
            break;
        case LITERAL_public:
            modifierFlags |= Modifier.PUBLIC;
            break;
        case FINAL:
            modifierFlags |= Modifier.FINAL;
            break;
        case LITERAL_static:
            modifierFlags |= Modifier.STATIC;
            break;
        case ABSTRACT:
            modifierFlags |= Modifier.ABSTRACT;
            break;
        }
    }
    return modifierFlags;
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

public AAIService(URL propURL) {
    LOG.info("Entered AAIService.ctor");

    String runtime = System.getProperty("aaiclient.runtime");
    if (runtime != null && runtime.equals("OSGI")) {
        runtimeOSGI = true;/*from w  ww .ja v  a2s  .co m*/
    } else {
        runtimeOSGI = false;
    }

    Properties props = null;
    try {
        props = initialize(propURL);
        AAIRequest.setProperties(props, this);

    } catch (Exception exc) {
        LOG.error("AicAAIResource.static", exc);
    }

    executor = new AAIRequestExecutor();

    user_name = props.getProperty(CLIENT_NAME);
    user_password = props.getProperty(CLIENT_PWWD);

    if (user_name == null || user_name.isEmpty()) {
        LOG.debug("Basic user name is not set");
    }
    if (user_password == null || user_password.isEmpty()) {
        LOG.debug("Basic password is not set");
    }

    truststore_path = props.getProperty(TRUSTSTORE_PATH);
    truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
    keystore_path = props.getProperty(KEYSTORE_PATH);
    keystore_password = props.getProperty(KEYSTORE_PSSWD);

    target_uri = props.getProperty(TARGET_URI);
    query_path = props.getProperty(QUERY_PATH);
    update_path = props.getProperty(UPDATE_PATH);

    String applicationId = props.getProperty(APPLICATION_ID);
    if (applicationId == null || applicationId.isEmpty()) {
        applicationId = "SDNC";
    }
    application_id = applicationId;

    // connection timeout
    int tmpConnectionTimeout = 30000;
    int tmpReadTimeout = 30000;

    try {
        String tmpValue = null;
        tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
        tmpConnectionTimeout = Integer.parseInt(tmpValue);
        tmpValue = props.getProperty(READ_TIMEOUT, "30000");
        tmpReadTimeout = Integer.parseInt(tmpValue);
    } catch (Exception exc) {
        LOG.error("Failed setting connection timeout", exc);
        tmpConnectionTimeout = 30000;
        tmpReadTimeout = 30000;
    }
    connection_timeout = tmpConnectionTimeout;
    read_timeout = tmpReadTimeout;

    network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH);

    svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
    //      "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";

    //      svc_inst_qry_path   = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance");
    svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance");

    param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");

    // P-Interfaces
    p_interface_path = props.getProperty(P_INTERFACE_PATH);

    vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);

    ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
    selflink_avpn = props.getProperty(SELFLINK_AVPN);
    selflink_fqdn = props.getProperty(SELFLINK_FQDN);

    service_path = props.getProperty(SERVICE_PATH);

    site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);

    query_nodes_path = props.getProperty(QUERY_NODES_PATH);

    String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
    boolean host_error = false;
    if (iche != null && !iche.isEmpty()) {
        host_error = Boolean.valueOf(iche);
    }

    ignore_certificate_host_error = host_error;

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String string, SSLSession ssls) {
            return ignore_certificate_host_error;
        }
    });

    if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
        System.setProperty("javax.net.ssl.trustStore", truststore_path);
        System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
    }

    if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) {
        DefaultClientConfig config = new DefaultClientConfig();
        //both jersey and HttpURLConnection can use this
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");

            KeyManagerFactory kmf = null;
            try {
                String def = "SunX509";
                String storeType = "PKCS12";
                def = KeyStore.getDefaultType();
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                FileInputStream fin = new FileInputStream(keystore_path);
                //                KeyStore ks = KeyStore.getInstance("PKCS12");

                String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);

                if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
                    storeType = "JKS";
                }
                KeyStore ks = KeyStore.getInstance(storeType);

                char[] pwd = keystore_password.toCharArray();
                ks.load(fin, pwd);
                kmf.init(ks, pwd);
            } catch (Exception ex) {
                LOG.error("AAIResource", ex);
            }

            ctx.init(kmf.getKeyManagers(), null, null);
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return ignore_certificate_host_error;
                        }
                    }, ctx));

            CTX = ctx;
            LOG.debug("SSLContext created");

        } catch (KeyManagementException | NoSuchAlgorithmException exc) {
            LOG.error("AAIResource", exc);
        }
    }

    LOG.info("AAIResource.ctor initialized.");

    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
        methodsField.setAccessible(true);
        // get the methods field modifiers
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        // bypass the "private" modifier
        modifiersField.setAccessible(true);

        // remove the "final" modifier
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        /* valid HTTP methods */
        String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" };
        // set the new methods - including patch
        methodsField.set(null, methods);

    } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
        e.printStackTrace();
    }

}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtilityTest.java

private Log applyMockLog(final LockFileVerifier verifier) throws NoSuchFieldException, IllegalAccessException {
    Log log = mock(Log.class);

    if (verifier != null) {
        doAnswer(new Answer<Void>() {

            @Override/* w  w w.j  a  v  a 2 s .  co  m*/
            public Void answer(InvocationOnMock invocation) throws Throwable {
                verifier.verify();
                return null;
            }
        }).when(log).debug(expectedLockFileDebugString(verifier));
    }
    Field field = VfsFileTransferUtility.class.getDeclaredField("log");
    field.setAccessible(true);

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, log);
    return log;
}

From source file:com.bosscs.spark.commons.utils.Utils.java

/**
 * Returns an instance clone./*from   ww  w .j  a  v  a  2s .  c  om*/
 * this method gets every class property by reflection, including its parents properties
 * @param t
 * @param <T>
 * @return T object.
 */
public static <T> T cloneObjectWithParents(T t) throws IllegalAccessException, InstantiationException {
    T clone = (T) t.getClass().newInstance();

    List<Field> allFields = new ArrayList<>();

    Class parentClass = t.getClass().getSuperclass();

    while (parentClass != null) {
        Collections.addAll(allFields, parentClass.getDeclaredFields());
        parentClass = parentClass.getSuperclass();
    }

    Collections.addAll(allFields, t.getClass().getDeclaredFields());

    for (Field field : allFields) {
        int modifiers = field.getModifiers();
        //We skip final and static fields
        if ((Modifier.FINAL & modifiers) != 0 || (Modifier.STATIC & modifiers) != 0) {
            continue;
        }
        field.setAccessible(true);

        Object value = field.get(t);

        if (Collection.class.isAssignableFrom(field.getType())) {
            Collection collection = (Collection) field.get(clone);
            if (collection == null) {
                collection = (Collection) field.get(t).getClass().newInstance();
            }
            collection.addAll((Collection) field.get(t));
            value = collection;
        } else if (Map.class.isAssignableFrom(field.getType())) {
            Map clonMap = (Map) field.get(t).getClass().newInstance();
            clonMap.putAll((Map) field.get(t));
            value = clonMap;
        }
        field.set(clone, value);
    }

    return clone;
}

From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServletTest.java

private void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);/* ww w  . ja  v a  2 s  .  c om*/
    // remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}

From source file:org.jenkinsci.plugins.ghprb.GhprbTestUtil.java

static void setFinal(Object o, Field field, Object newValue) throws Exception {
    field.setAccessible(true);/*from   w  w w . j a  v a2 s  . co  m*/

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    int prevModifiers = field.getModifiers();
    modifiersField.setInt(field, prevModifiers & ~Modifier.FINAL);

    field.set(o, newValue);
    modifiersField.setInt(field, prevModifiers);
    modifiersField.setAccessible(false);
    field.setAccessible(false);

}

From source file:org.eclipse.wb.internal.swing.model.property.editor.accelerator.KeyStrokePropertyEditor.java

/**
 * Prepares {@link Map}'s for key code/name conversion.
 *//*from  w  w  w . j  a  va 2  s.  c o m*/
private static synchronized void prepareKeyMaps() {
    if (m_keyCodeToName == null) {
        m_keyFields = Lists.newArrayList();
        m_keyCodeToName = Maps.newTreeMap();
        m_keyNameToCode = Maps.newTreeMap();
        // add fields
        try {
            int expected_modifiers = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
            Field[] fields = KeyEvent.class.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                if (field.getModifiers() == expected_modifiers && field.getType() == Integer.TYPE
                        && field.getName().startsWith("VK_")) {
                    String name = field.getName().substring(3);
                    Integer value = (Integer) field.get(null);
                    m_keyFields.add(name);
                    m_keyCodeToName.put(value, name);
                    m_keyNameToCode.put(name, value);
                }
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
        }
    }
}