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.janusgraph.diskstorage.cql.CassandraStorageSetup.java

private static void setWrapperStoreManager() {
    try {/* ww  w .j  a  v  a2 s  . c o m*/
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);

        Field field = StandardStoreManager.class.getDeclaredField("managerClass");
        field.setAccessible(true);
        field.set(StandardStoreManager.CQL, CachingCQLStoreManager.class.getCanonicalName());

        field = StandardStoreManager.class.getDeclaredField("ALL_SHORTHANDS");
        field.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, ImmutableList.copyOf(StandardStoreManager.CQL.getShorthands()));

        field = StandardStoreManager.class.getDeclaredField("ALL_MANAGER_CLASSES");
        field.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, ImmutableMap.of(StandardStoreManager.CQL.getShorthands().get(0),
                StandardStoreManager.CQL.getManagerClass()));
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to set wrapper CQL store manager", e);
    }
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.property.field.FieldPropertyResolver.java

/**
 * Resolves the mutator./* w  w w  .jav  a2  s  .co  m*/
 * 
 * @param methods
 *            Candidate methods.
 * @param builder
 *            The builder.
 * @param type
 *            The property type.
 * @param name
 *            The property name.
 * @param <P>
 *            The property type.
 */
private <P> void resolveMutator(final List<Method> methods, final PropertyBuilder<P> builder,
        final Class<P> type, final String name) {
    Method mutator = null;
    for (final Method method : methods) {
        if (this.getMutatorMatcherResolver().matches(method, name, type)) {
            for (final Annotation a : method.getAnnotations()) {
                builder.addAnnotation(a);
            }
            mutator = method;
        }
    }
    if (CheckUtil.isNull(mutator)) {
        builder.addModifier(Modifier.FINAL);
    } else {
        builder.mutator(mutator);
    }
}

From source file:org.codehaus.griffon.ast.GriffonASTUtils.java

public static void injectConstant(ClassNode classNode, String propertyName, Class propertyClass, Object value) {
    final boolean hasProperty = hasOrInheritsProperty(classNode, propertyName);

    if (!hasProperty) {
        // inject into furthest relative
        // ClassNode parent = getFurthestParent(classNode);
        Expression initialExpression = new ConstantExpression(value);
        classNode.addProperty(propertyName, Modifier.PUBLIC | Modifier.FINAL, new ClassNode(propertyClass),
                initialExpression, null, null);
    }//from   w ww .  j  a v  a  2s .  c om
}

From source file:org.codehaus.griffon.ast.GriffonASTUtils.java

public static void addReadOnlyProperty(ClassNode classNode, String propertyName, ClassNode propertyClass,
        Object value) {/* w  ww. j  a  v a2 s.com*/
    final boolean hasProperty = hasOrInheritsProperty(classNode, propertyName);

    if (!hasProperty) {
        int visibility = Modifier.PRIVATE | Modifier.FINAL;
        Expression initialValue = value != null && !(value instanceof Expression)
                ? initialValue = new ConstantExpression(value)
                : (Expression) value;
        classNode.addField(propertyName, visibility, propertyClass, initialValue);
        addMethod(classNode, new MethodNode("get" + MetaClassHelper.capitalize(propertyName), Modifier.PUBLIC,
                propertyClass, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement(
                        new ExpressionStatement(new FieldExpression(classNode.getField(propertyName))))));
    }
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Hack to disable crypto restrictions until Java 9 is out.
 *
 * See http://stackoverflow.com/a/22492582/2672392
 *///ww  w  .j  av a  2s. com
public static void removeRestrictions() {
    try {
        Class<?> jceSecurityClass = Class.forName("javax.crypto.JceSecurity");
        Class<?> cryptoPermissionsClass = Class.forName("javax.crypto.CryptoPermissions");
        Class<?> cryptoAllPermissionClass = Class.forName("javax.crypto.CryptoAllPermission");

        Field isRestrictedField = jceSecurityClass.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        Field defaultPolicyField = jceSecurityClass.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        Field permsField = cryptoPermissionsClass.getDeclaredField("perms");
        permsField.setAccessible(true);
        ((Map<?, ?>) permsField.get(defaultPolicy)).clear();

        Field cryptoAllPermissionInstanceField = cryptoAllPermissionClass.getDeclaredField("INSTANCE");
        cryptoAllPermissionInstanceField.setAccessible(true);
        defaultPolicy.add((Permission) cryptoAllPermissionInstanceField.get(null));
    } catch (Exception e) {
        // ignore
    }
}

From source file:org.apache.ambari.server.controller.AmbariManagementControllerImplTest.java

@Test
public void testgetAmbariServerURI() throws Exception {
    // create mocks
    Injector injector = createStrictMock(Injector.class);
    Capture<AmbariManagementController> controllerCapture = new Capture<AmbariManagementController>();

    // set expectations
    injector.injectMembers(capture(controllerCapture));
    expect(injector.getInstance(Gson.class)).andReturn(null);

    //replay//from   ww w .jav  a2  s  .c  om
    replay(injector);

    AmbariManagementControllerImpl controller = new AmbariManagementControllerImpl(null, null, injector);

    class AmbariConfigsSetter {
        public void setConfigs(AmbariManagementController controller, String masterProtocol,
                String masterHostname, Integer masterPort) throws Exception {
            // masterProtocol
            Class<?> c = controller.getClass();
            Field f = c.getDeclaredField("masterProtocol");
            f.setAccessible(true);

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

            f.set(controller, masterProtocol);

            // masterHostname
            f = c.getDeclaredField("masterHostname");
            f.setAccessible(true);

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

            f.set(controller, masterHostname);

            // masterPort
            f = c.getDeclaredField("masterPort");
            f.setAccessible(true);

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

            f.set(controller, masterPort);
        }
    }

    AmbariConfigsSetter ambariConfigsSetter = new AmbariConfigsSetter();

    ambariConfigsSetter.setConfigs(controller, "http", "hostname", 8080);
    assertEquals("http://hostname:8080/jdk_path", controller.getAmbariServerURI("/jdk_path"));

    ambariConfigsSetter.setConfigs(controller, "https", "somesecuredhost", 8443);
    assertEquals("https://somesecuredhost:8443/mysql_path", controller.getAmbariServerURI("/mysql_path"));

    ambariConfigsSetter.setConfigs(controller, "https", "othersecuredhost", 8443);
    assertEquals("https://othersecuredhost:8443/oracle/ojdbc/",
            controller.getAmbariServerURI("/oracle/ojdbc/"));

    verify(injector);
}

From source file:test.unit.be.fedict.eid.applet.shared.AppletProtocolMessageCatalogTest.java

private void describeClass(Class<?> catalogClass, PrintWriter writer)
        throws IllegalArgumentException, IllegalAccessException {
    writer.println("<section id=\"" + catalogClass.getSimpleName() + "\">");
    writer.println("<title>" + catalogClass.getSimpleName() + "</title>");

    StartRequestMessage startRequestMessage = catalogClass.getAnnotation(StartRequestMessage.class);
    if (null != startRequestMessage) {
        writer.println("<para>");
        writer.println(//from   w  w  w  .j  a v  a  2  s. c  o m
                "This message starts a communication session between eID Applet and eID Applet Service.");
        writer.println("It sets the protocol state to: " + startRequestMessage.value());
        writer.println("</para>");
    }

    StopResponseMessage stopResponseMessage = catalogClass.getAnnotation(StopResponseMessage.class);
    if (null != stopResponseMessage) {
        writer.println("<para>");
        writer.println(
                "This message stops a communication session between eID Applet and the eID Applet Service.");
        writer.println("</para>");
    }

    ProtocolStateAllowed protocolStateAllowed = catalogClass.getAnnotation(ProtocolStateAllowed.class);
    if (null != protocolStateAllowed) {
        writer.println("<para>");
        writer.println("This message is only accepted if the eID Applet Service protocol state is: "
                + protocolStateAllowed.value());
        writer.println("</para>");
    }

    Field bodyField = null;

    writer.println("<table>");
    writer.println("<title>" + catalogClass.getSimpleName() + " HTTP headers</title>");
    writer.println("<tgroup cols=\"3\">");
    {
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<colspec colwidth=\"1*\" />");
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<thead>");
        writer.println("<row>");
        writer.println("<entry>Header name</entry>");
        writer.println("<entry>Required</entry>");
        writer.println("<entry>Value</entry>");
        writer.println("</row>");
        writer.println("</thead>");
        writer.println("<tbody>");
        {
            Field[] fields = catalogClass.getFields();
            for (Field field : fields) {
                if (field.getAnnotation(HttpBody.class) != null) {
                    bodyField = field;
                }
                HttpHeader httpHeaderAnnotation = field.getAnnotation(HttpHeader.class);
                if (null == httpHeaderAnnotation) {
                    continue;
                }
                writer.println("<row>");
                writer.println("<entry>");
                writer.println("<code>" + httpHeaderAnnotation.value() + "</code>");
                writer.println("</entry>");
                writer.println("<entry>");
                writer.println((null != field.getAnnotation(NotNull.class))
                        || (0 != (field.getModifiers() & Modifier.FINAL)));
                writer.println("</entry>");
                writer.println("<entry>");
                if (0 != (field.getModifiers() & Modifier.FINAL)) {
                    Object value = field.get(null);
                    writer.println("<code>" + value.toString() + "</code>");
                } else {
                    writer.println("Some " + field.getType().getSimpleName() + " value.");
                }
                writer.println("</entry>");
                writer.println("</row>");
            }
        }
        writer.println("</tbody>");
    }
    writer.println("</tgroup>");
    writer.println("</table>");

    if (null != bodyField) {
        writer.println("<para>HTTP body should contain the data.</para>");
    }

    ResponsesAllowed responsesAllowedAnnotation = catalogClass.getAnnotation(ResponsesAllowed.class);
    if (null != responsesAllowedAnnotation) {
        Class<?>[] responsesAllowed = responsesAllowedAnnotation.value();
        writer.println("<para>");
        writer.println("Allowed eID Applet Service response messages are: ");
        for (Class<?> responseAllowed : responsesAllowed) {
            writer.println("<xref linkend=\"" + responseAllowed.getSimpleName() + "\"/>");
        }
        writer.println("</para>");
    }

    StateTransition stateTransition = catalogClass.getAnnotation(StateTransition.class);
    if (null != stateTransition) {
        writer.println("<para>");
        writer.println("This message will perform an eID Applet protocol state transition to: "
                + stateTransition.value());
        writer.println("</para>");
    }

    writer.println("</section>");
}

From source file:org.venice.piazza.servicecontroller.messaging.ServiceMessageThreadManagerTest.java

static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);//from ww w. j a  v a  2  s  .  c  om
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);

}

From source file:org.agiso.core.lang.util.ObjectUtils.java

/**
 * Metoda generujca reprezentacj acuchow obiektu. Przeglda wszystkie
 * pola obiektu i pobiera ich reprezentacj acuchow. Na tej podstawie
 * generuje acuch wynikowy./*ww  w  .ja  v a 2s  .  c o  m*/
 * 
 * @param clazz
 * @param object
 */
private static void toStringObject(Class<?> clazz, Object object) {
    StringBuffer buffer = (StringBuffer) ThreadUtils.getAttribute(TOSTRING_TCBUFF);

    String hexHash = Integer.toHexString(System.identityHashCode(object));
    if (0 == buffer.length()) {
        buffer.append(clazz.getSimpleName()).append('@').append(hexHash).append(TOSTRING_PREFIX);
    }

    @SuppressWarnings("unchecked")
    Set<String> converted = (Set<String>) ThreadUtils.getAttribute(TOSTRING_TCATTR);
    converted.add(object.getClass().getCanonicalName() + "@" + hexHash);

    // Rekurencyjne przegldanie wszystkich klas nadrzdnych:
    Class<?> superClass = clazz.getSuperclass();
    if (superClass != null) {
        toStringObject(superClass, object);
    }

    String hyphen = "";
    if (TOSTRING_PREFIX.charAt(0) != buffer.charAt(buffer.length() - 1)) {
        hyphen = TOSTRING_HYPHEN;
    }

    for (Field field : clazz.getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.isAnnotationPresent(InToString.class)) {
                InToString inToString = field.getAnnotation(InToString.class);
                if (!inToString.ignore()) {
                    String name = inToString.name();
                    buffer.append(hyphen).append((name.length() > 0) ? name : field.getName())
                            .append(TOSTRING_COLON);
                    toStringField(field.get(object));
                    hyphen = TOSTRING_HYPHEN;
                }
            } else if ((field.getModifiers() & (Modifier.STATIC | Modifier.FINAL)) == 0) {
                buffer.append(hyphen).append(field.getName()).append(TOSTRING_COLON);
                toStringField(field.get(object));
                hyphen = TOSTRING_HYPHEN;
            }
        } catch (Exception e) {
            // TODO: Zaimplementowa logowanie wyjtku
            e.printStackTrace();
        }
    }
}

From source file:org.kaaproject.kaa.server.appenders.oraclenosql.appender.OracleNoSqlLogAppenderTest.java

@Test
public void doAppendClosedTest()
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    Logger testLogger = Mockito.mock(Logger.class);

    Field field = logAppender.getClass().getDeclaredField("LOG");

    field.setAccessible(true);/*from   ww w  .  j av a  2  s  .  c  o  m*/

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

    field.set(null, testLogger);

    logAppender.close();
    TestLogDeliveryCallback callback = new TestLogDeliveryCallback();

    LogSchemaDto schemaDto = new LogSchemaDto();
    LogSchema schema = new LogSchema(schemaDto, BasicEndpointProfile.SCHEMA$.toString());

    EndpointProfileDataDto profileDto = new EndpointProfileDataDto("1", ENDPOINT_KEY, 1, "test", 0, null);
    BaseLogEventPack logEventPack = new BaseLogEventPack(profileDto, DATE_CREATED, schema.getVersion(), null);
    logEventPack.setLogSchema(schema);

    logAppender.doAppend(logEventPack, callback);
    Assert.assertTrue(callback.internallError);
}