Example usage for java.lang.reflect Proxy getInvocationHandler

List of usage examples for java.lang.reflect Proxy getInvocationHandler

Introduction

In this page you can find the example usage for java.lang.reflect Proxy getInvocationHandler.

Prototype

@CallerSensitive
public static InvocationHandler getInvocationHandler(Object proxy) throws IllegalArgumentException 

Source Link

Document

Returns the invocation handler for the specified proxy instance.

Usage

From source file:com.github.cherimojava.data.mongo.entity.EntityInvocationHandler.java

/**
 * equals method of the entity represented by this EntityInvocationHandler instance. Objects are considered unequal
 * (false) if o is://from www  . j av  a  2  s.c  o m
 * <ul>
 * <li>null
 * <li>no Proxy
 * <li>different Proxy class
 * <li>Different Entity class
 * <li>Data doesn't match
 * </ul>
 * If all the above is false both entities are considered equal and true will be returned
 *
 * @param o object to compare this instance with
 * @return true if both objects match the before mentioned criteria otherwise false
 */
private boolean _equals(Object o) {
    if (o == null) {
        return false;
    }
    if (!Proxy.isProxyClass(o.getClass())) {
        // for all non proxies we know that we can return false
        return false;
    }
    InvocationHandler ihandler = Proxy.getInvocationHandler(o);
    if (!ihandler.getClass().equals(getClass())) {
        // for all proxies not being EntityInvocationHandler return false
        return false;
    }
    EntityInvocationHandler handler = (EntityInvocationHandler) ihandler;
    if (!handler.properties.getEntityClass().equals(properties.getEntityClass())) {
        // this is not the same entity class, so false
        return false;
    }
    // make sure both have all lazy dependencies resolved
    lazyLoad();
    handler.lazyLoad();
    return data.equals(handler.data);
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntitySetInvocationHandler.java

@Override
public void delete(final KEY key) throws IllegalArgumentException {
    final EntityContext entityContext = EntityContainerFactory.getContext().entityContext();

    EntityTypeInvocationHandler entity = entityContext.getEntity(new EntityUUID(
            ClassUtils.getNamespace(typeRef), containerHandler.getEntityContainerName(), entitySetName,
            ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef), key));

    if (entity == null) {
        // search for entity
        final T searched = get(key);
        entity = (EntityTypeInvocationHandler) Proxy.getInvocationHandler(searched);
        entityContext.attach(entity, AttachedEntityStatus.DELETED);
    } else {/*from  www. j ava2  s .  c  o  m*/
        entityContext.setStatus(entity, AttachedEntityStatus.DELETED);
    }
}

From source file:jCloisterZone.CarcassonneEnvironment.java

@Override
protected void startState() {
    relationalWrapper_.startState();//from   w  w w  . ja  v a 2s. c  o m

    while (!ProgramArgument.EXPERIMENT_MODE.booleanValue() && client_.isRunning()) {
        try {
            Thread.yield();
        } catch (Exception e) {
        }
    }
    client_.createGame();
    earlyExit_ = false;
    earlyExitPlayers_.clear();
    prevScores_.clear();

    if (environment_ == null) {
        // Sleep only as long as it needs to to get the clientID.
        long clientID = (ProgramArgument.EXPERIMENT_MODE.booleanValue()) ? client_.getClientId() : -1;
        while (!ProgramArgument.EXPERIMENT_MODE.booleanValue() && clientID == -1) {
            try {
                Thread.yield();
                clientID = client_.getClientId();
            } catch (Exception e) {
            }
        }

        server_ = client_.getServer();
        server_.setRandomGenerator(RRLExperiment.random_);

        // Handle number of players playing
        slots_ = new ArrayList<PlayerSlot>(players_.length);
        int slotIndex = 0;
        for (String playerName : players_) {
            String playerNameIndex = playerName + slotIndex;
            if (playerName.equals(CERRLA_NAME)) {
                // Agent-controlled
                slots_.add(new PlayerSlot(slotIndex, PlayerSlot.SlotType.PLAYER, playerNameIndex, clientID));
            } else if (playerName.equals(AI_NAME)) {
                // AI controlled
                PlayerSlot slot = new PlayerSlot(slotIndex, PlayerSlot.SlotType.AI, playerNameIndex, clientID);
                slot.setAiClassName(LegacyAiPlayer.class.getName());
                slots_.add(slot);
            } else if (playerName.equals(RANDOM_NAME)) {
                // AI controlled
                PlayerSlot slot = new PlayerSlot(slotIndex, PlayerSlot.SlotType.AI, playerNameIndex, clientID);
                slot.setAiClassName(RandomAIPlayer.class.getName());
                slots_.add(slot);
            } else if (playerName.equals(HUMAN_NAME)) {
                // Human-controlled
                slots_.add(new PlayerSlot(slotIndex, PlayerSlot.SlotType.PLAYER, playerNameIndex, clientID));
            }
            slotIndex++;
        }

        // Start the game.
        environment_ = client_.getGame();
        while (!ProgramArgument.EXPERIMENT_MODE.booleanValue() && environment_ == null) {
            try {
                Thread.yield();
            } catch (Exception e) {
            }
            environment_ = client_.getGame();
        }
        relationalWrapper_.setGame(environment_);
        environment_.addGameListener(relationalWrapper_);
        // Ad-hoc fix
        if (ProgramArgument.EXPERIMENT_MODE.booleanValue())
            environment_.addUserInterface(relationalWrapper_);
        clientInterface_ = environment_.getUserInterface();
    } else if (players_.length > 1) {
        // Reset the UIs
        server_.stopGame();
        environment_.clearUserInterface();
        environment_.addUserInterface(clientInterface_);

        // Clear the slots and re-add them.
        for (int i = 0; i < PlayerSlot.COUNT; i++) {
            server_.updateSlot(new PlayerSlot(i), null);
        }
    }
    // Ad-hoc fix
    if (!ProgramArgument.EXPERIMENT_MODE.booleanValue()) {
        environment_.addUserInterface(relationalWrapper_);
    }

    // Randomise the slots
    Collections.shuffle(slots_, RRLExperiment.random_);
    for (int i = 0; i < slots_.size(); i++) {
        PlayerSlot slot = slots_.get(i);
        PlayerSlot cloneSlot = new PlayerSlot(i, slot.getType(), slot.getNick(), slot.getOwner());
        cloneSlot.setAiClassName(slot.getAiClassName());
        server_.updateSlot(cloneSlot, LegacyAiPlayer.supportedExpansions());
    }

    server_.startGame();
    // Sleep until game has started
    while (!ProgramArgument.EXPERIMENT_MODE.booleanValue() && (environment_ == null
            || environment_.getBoard() == null || environment_.getTilePack() == null)) {
        environment_ = ((ClientStub) Proxy.getInvocationHandler(server_)).getGame();
        try {
            Thread.yield();
        } catch (Exception e) {
        }
    }

    runPhases();

    currentPlayer_ = null;
}

From source file:org.wso2.carbon.apimgt.everywhere.webapp.publisher.APIPublisherLifecycleListener.java

private static void showAPIinfo(ServletContext context, Class<?> clazz, Class<Path> pathClazz) {

    Annotation rootContectAnno = clazz.getAnnotation(pathClazz);

    log.info("======================== API INFO ======================= ");
    if (context != null) {
        log.info("Application Context root = " + context.getContextPath());
    }//from w w  w.j ava 2  s  . c  o  m

    if (rootContectAnno != null) {
        InvocationHandler handler = Proxy.getInvocationHandler(rootContectAnno);
        Method[] methods = pathClazz.getMethods();
        String root;

        try {
            root = (String) handler.invoke(rootContectAnno, methods[0], null);

            log.info("API Root  Context = " + root);
            log.info("API Sub Context List ");
            for (Method method : clazz.getDeclaredMethods()) {
                Annotation methodContextAnno = method.getAnnotation(pathClazz);
                if (methodContextAnno != null) {
                    InvocationHandler methodHandler = Proxy.getInvocationHandler(methodContextAnno);
                    String subCtx = (String) methodHandler.invoke(methodContextAnno, methods[0], null);
                    ;
                    log.info("  " + root + "/" + subCtx);
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        log.info("===================================================== ");
        //todo log.info summery of the api context info resulting from the scan
    }
}

From source file:io.coala.json.DynaBean.java

/**
 * @param <T>/* w w w. j  av  a  2 s. c o m*/
 * @param wrapperType
 * @return
 */
static final <T> JsonSerializer<T> createJsonSerializer(final Class<T> type) {
    return new JsonSerializer<T>() {
        @Override
        public void serialize(final T value, final JsonGenerator jgen, final SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            // non-Proxy objects get default treatment
            if (!Proxy.isProxyClass(value.getClass())) {
                @SuppressWarnings("unchecked")
                final JsonSerializer<T> ser = (JsonSerializer<T>) serializers
                        .findValueSerializer(value.getClass());
                if (ser != this)
                    ser.serialize(value, jgen, serializers);
                else
                    LOG.warn("Problem serializing: {}", value);
                return;
            }

            // BeanWrapper gets special treatment
            if (DynaBeanInvocationHandler.class.isInstance(Proxy.getInvocationHandler(value))) {
                final DynaBeanInvocationHandler handler = (DynaBeanInvocationHandler) Proxy
                        .getInvocationHandler(value);

                // Wrapper extensions get special treatment
                if (Wrapper.class.isAssignableFrom(handler.type)) {
                    final Object wrap = handler.bean.get("wrap");
                    serializers.findValueSerializer(wrap.getClass(), null).serialize(wrap, jgen, serializers);
                    return;
                }
                // Config (Accessible) extensions get special treatment
                else if (Accessible.class.isAssignableFrom(handler.type)) {
                    final Map<String, Object> copy = new HashMap<>(handler.bean.any());
                    final Accessible config = (Accessible) handler.config;
                    for (String key : config.propertyNames())
                        copy.put(key, config.getProperty(key));
                    serializers.findValueSerializer(copy.getClass(), null).serialize(copy, jgen, serializers);
                    return;
                } else if (Config.class.isAssignableFrom(handler.type))
                    throw new JsonGenerationException("BeanWrapper should extend " + Accessible.class.getName()
                            + " required for serialization: " + Arrays.asList(handler.type.getInterfaces()),
                            jgen);

                // BeanWrappers that do not extend OWNER API's Config
                serializers.findValueSerializer(handler.bean.getClass(), null).serialize(handler.bean, jgen,
                        serializers);
                return;
            }

            // Config (Accessible) gets special treatment
            if (Accessible.class.isInstance(value)) {
                final Accessible config = (Accessible) value;
                final Properties entries = new Properties();
                for (String key : config.propertyNames())
                    entries.put(key, config.getProperty(key));
                serializers.findValueSerializer(entries.getClass(), null).serialize(entries, jgen, serializers);
                return;
            }

            if (Config.class.isInstance(value))
                throw new JsonGenerationException("Config should extend " + Accessible.class.getName()
                        + " required for serialization: " + Arrays.asList(value.getClass().getInterfaces()),
                        jgen);

            throw new JsonGenerationException(
                    "No serializer found for proxy of: " + Arrays.asList(value.getClass().getInterfaces()),
                    jgen);
        }
    };
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntitySetInvocationHandler.java

@Override
public <S extends T> void delete(final Iterable<S> entities) {
    final EntityContext entityContext = EntityContainerFactory.getContext().entityContext();

    for (T en : entities) {
        final EntityTypeInvocationHandler entity = (EntityTypeInvocationHandler) Proxy.getInvocationHandler(en);
        if (entityContext.isAttached(entity)) {
            entityContext.setStatus(entity, AttachedEntityStatus.DELETED);
        } else {//w  ww.j  a v a 2 s  .  c  o m
            entityContext.attach(entity, AttachedEntityStatus.DELETED);
        }
    }
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntityTypeInvocationHandler.java

private void setNavigationPropertyValue(final NavigationProperty property, final Object value) {
    // 1) attach source entity
    attach(AttachedEntityStatus.CHANGED, false);

    // 2) attach the target entity handlers
    for (Object link : AbstractEntityCollection.class.isAssignableFrom(value.getClass())
            ? (AbstractEntityCollection) value
            : Collections.singleton(value)) {

        final InvocationHandler etih = Proxy.getInvocationHandler(link);
        if (!(etih instanceof EntityTypeInvocationHandler)) {
            throw new IllegalArgumentException("Invalid argument type");
        }/*from   w  w w  .  jav a  2s  .  c  o m*/

        final EntityTypeInvocationHandler handler = (EntityTypeInvocationHandler) etih;
        if (!handler.getTypeRef().isAnnotationPresent(EntityType.class)) {
            throw new IllegalArgumentException("Invalid argument type " + handler.getTypeRef().getSimpleName());
        }

        if (!entityContext.isAttached(handler)) {
            entityContext.attach(handler, AttachedEntityStatus.LINKED);
        }
    }

    // 3) add links
    linkChanges.put(property, value);
}

From source file:com.github.cherimojava.data.mongo.entity.EntityInvocationHandler.java

/**
 * returns the {@link com.github.cherimojava.data.mongo.entity.EntityInvocationHandler} of the given entity
 * /*from   www.ja  va  2  s .com*/
 * @param e entity to retrieve handler from
 * @return EntityInvocationHandler the entity is baked by
 */
public static EntityInvocationHandler getHandler(Entity e) {
    return (EntityInvocationHandler) Proxy.getInvocationHandler(checkNotNull(e));
}

From source file:org.apache.olingo.ext.proxy.commons.AbstractStructuredInvocationHandler.java

protected void setPropertyValue(final Property property, final Object value) {
    if (EdmPrimitiveTypeKind.Stream.getFullQualifiedName().toString().equalsIgnoreCase(property.type())) {
        setStreamedProperty(property, (EdmStreamValue) value);
    } else {/*from w  w  w.ja v  a 2  s. c  o m*/
        addPropertyChanges(property.name(), value);

        if (value != null) {
            Collection<?> coll;
            if (Collection.class.isAssignableFrom(value.getClass())) {
                coll = Collection.class.cast(value);
            } else {
                coll = Collections.singleton(value);
            }

            for (Object item : coll) {
                if (item instanceof Proxy) {
                    final InvocationHandler handler = Proxy.getInvocationHandler(item);
                    if ((handler instanceof ComplexInvocationHandler)
                            && ((ComplexInvocationHandler) handler).getEntityHandler() == null) {
                        ((ComplexInvocationHandler) handler).setEntityHandler(getEntityHandler());
                    }
                }
            }
        }
    }

    attach(AttachedEntityStatus.CHANGED);
}

From source file:org.wso2.carbon.device.mgt.core.config.permission.AnnotationProcessor.java

private void setPermission(Annotation currentMethod, Permission permission) throws Throwable {
    InvocationHandler methodHandler = Proxy.getInvocationHandler(currentMethod);
    Annotation[] extensions = (Annotation[]) methodHandler.invoke(currentMethod,
            apiOperation.getMethod(SWAGGER_ANNOTATIONS_EXTENSIONS, null), null);
    if (extensions != null) {
        methodHandler = Proxy.getInvocationHandler(extensions[0]);
        Annotation[] properties = (Annotation[]) methodHandler.invoke(extensions[0],
                extensionClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES, null), null);
        Scope scope;//from  www .j a  v a  2  s  .  co m
        String scopeKey;
        String propertyName;
        for (Annotation property : properties) {
            methodHandler = Proxy.getInvocationHandler(property);
            propertyName = (String) methodHandler.invoke(property,
                    extensionPropertyClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME, null), null);
            if (ANNOTATIONS_SCOPE.equals(propertyName)) {
                scopeKey = (String) methodHandler.invoke(property,
                        extensionPropertyClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_VALUE, null), null);
                if (!scopeKey.isEmpty()) {
                    scope = apiScopes.get(scopeKey);
                    if (scope != null) {
                        permission.setName(scope.getName());
                        //TODO: currently permission tree supports only adding one permission per API point.
                        permission.setPath(scope.getRoles().split(" ")[0]);
                    } else {
                        log.warn("No Scope mapping is done for scope key: " + scopeKey);
                        permission.setName(DEFAULT_PERM_NAME);
                        permission.setPath(DEFAULT_PERM);
                    }
                }
            }
        }
    }
}