Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
*/
public interface _ProxyFactoryService {

String WRAPPER_INVOCATION_CONTEXT_FIELD_NAME = "__causeway_wrapperInvocationContext";

<T> _ProxyFactory<T> factory(
Class<T> base,
@Nullable Class<?>[] interfaces,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@
*/
package org.apache.causeway.core.codegen.bytebuddy.services;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.function.Function;

import org.springframework.lang.Nullable;
Expand All @@ -29,6 +34,7 @@
import org.apache.causeway.commons.internal._Constants;
import org.apache.causeway.commons.internal.base._Casts;
import org.apache.causeway.commons.internal.base._NullSafe;
import org.apache.causeway.commons.internal.collections._Maps;
import org.apache.causeway.commons.internal.context._Context;
import org.apache.causeway.commons.internal.proxy._ProxyFactory;
import org.apache.causeway.commons.internal.proxy._ProxyFactoryServiceAbstract;
Expand All @@ -44,8 +50,35 @@
@Service
public class ProxyFactoryServiceByteBuddy extends _ProxyFactoryServiceAbstract {


private final ClassLoadingStrategyAdvisor strategyAdvisor = new ClassLoadingStrategyAdvisor();

/**
* Cached proxy class by invocation handler.
*
* <p>
* For the wrapper factory, the passed in implementation of invocation handler
* (<code>org.apache.causeway.core.runtimeservices.wrapper.handlers.DomainObjectInvocationHandler</code>)
* implements equals/hashCode based only on the
* <code>org.apache.causeway.core.metamodel.spec.ObjectSpecification</code> (effectively the target class,
* which might be a mixin class); the corresponding proxied class is therefore cached.
* </p>
*
* <p>
* For other implementations, if the invocation handler does not explicitly implement equals/hashCode, then
* effectively there is no caching, and therefore there will be a metaclass memory leak. Use
* {@link org.apache.causeway.commons.memory.MemoryUsage#measureMetaspace(String, Callable)} to determine
* whether this is a problem. Note that at the time of writing, the proxy classes for parented collections
* of (wrapped) domain objects are <i>not</i> proxied; but these are rarely used.
* </p>
*
* <p>
* The remaining state (defined by WrapperInvocationContext) is held in the proxy object itself as a field.
* </p>
* @return
*/
private Map<InvocationHandler, Class<?>> proxyClassByInvocationHandler = _Maps.newConcurrentHashMap();

@Override
public <T> _ProxyFactory<T> factory(
final Class<T> base,
Expand All @@ -54,21 +87,34 @@ public <T> _ProxyFactory<T> factory(

val objenesis = new ObjenesisStd();

final Function<InvocationHandler, Class<? extends T>> proxyClassFactory = handler->
nextProxyDef(base, interfaces)
.intercept(InvocationHandlerAdapter.of(handler))
.make()
.load(_Context.getDefaultClassLoader(),
strategyAdvisor.getSuitableStrategy(base))
.getLoaded();
final Function<InvocationHandler, Class<? extends T>> proxyClassFactory = new Function<>() {

@Override
public Class<? extends T> apply(InvocationHandler handler) {
return (Class<? extends T>) proxyClassByInvocationHandler.computeIfAbsent(handler, this::createClass);
}

private Class<? extends T> createClass(InvocationHandler handler) {
try (final var unloaded = nextProxyDef(base, interfaces)
.intercept(InvocationHandlerAdapter.of(handler))
.defineField(WRAPPER_INVOCATION_CONTEXT_FIELD_NAME, Object.class, Modifier.PUBLIC)
.make()
) {
return unloaded
.load(_Context.getDefaultClassLoader(), strategyAdvisor.getSuitableStrategy(base))
.getLoaded();
} catch (IOException e) {
throw new UncheckedIOException("Failed to generate proxy class", e);
}
}
};

return new _ProxyFactory<T>() {

@Override
public T createInstance(final InvocationHandler handler, final boolean initialize) {

try {

if(initialize) {
ensureSameSize(constructorArgTypes, null);
return _Casts.uncheckedCast( createUsingConstructor(handler, null) );
Expand Down Expand Up @@ -101,20 +147,18 @@ public T createInstance(final InvocationHandler handler, final Object[] construc

private Object createNotUsingConstructor(final InvocationHandler invocationHandler) {
final Class<? extends T> proxyClass = proxyClassFactory.apply(invocationHandler);
final Object object = objenesis.newInstance(proxyClass);
return object;
return objenesis.newInstance(proxyClass);
}

// -- HELPER (create with initialize)

private Object createUsingConstructor(final InvocationHandler invocationHandler, @Nullable final Object[] constructorArgs)
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
final Class<? extends T> proxyClass = proxyClassFactory.apply(invocationHandler);
return proxyClass
.getConstructor(constructorArgTypes==null ? _Constants.emptyClasses : constructorArgTypes)
.newInstance(constructorArgs==null ? _Constants.emptyObjects : constructorArgs);
final var proxyClass = proxyClassFactory.apply(invocationHandler); // creates or fetches from cache
final var constructor =
proxyClass.getConstructor(constructorArgTypes == null ? _Constants.emptyClasses : constructorArgTypes);
return constructor.newInstance(constructorArgs == null ? _Constants.emptyObjects : constructorArgs);
}

};

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import org.apache.causeway.core.metamodel.facets.object.icon.ObjectIconService;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.core.metamodel.objectmanager.ObjectManager;
import org.apache.causeway.core.metamodel.services.command.CommandDtoFactory;
import org.apache.causeway.core.metamodel.services.message.MessageBroker;
import org.apache.causeway.core.metamodel.spec.ObjectSpecification;
import org.apache.causeway.core.metamodel.specloader.SpecificationLoader;
Expand Down Expand Up @@ -150,6 +151,10 @@ default InteractionService getInteractionService() {
return getMetaModelContext().getInteractionService();
}

default CommandDtoFactory getCommandDtoFactory() {
return getMetaModelContext().getCommandDtoFactory();
}

default Optional<UserLocale> currentUserLocale() {
return getInteractionService().currentInteractionContext()
.map(InteractionContext::getLocale);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import org.apache.causeway.core.metamodel.facets.object.icon.ObjectIconService;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.core.metamodel.objectmanager.ObjectManager;
import org.apache.causeway.core.metamodel.services.command.CommandDtoFactory;
import org.apache.causeway.core.metamodel.specloader.SpecificationLoader;
import org.apache.causeway.core.security.authentication.manager.AuthenticationManager;
import org.apache.causeway.core.security.authorization.manager.AuthorizationManager;
Expand Down Expand Up @@ -160,6 +161,10 @@ void onDestroy() {
private final InteractionService interactionService =
getSingletonElseFail(InteractionService.class);

@Getter(lazy = true)
private final CommandDtoFactory commandDtoFactory =
getSingletonElseFail(CommandDtoFactory.class);

@Override
public final ManagedObject getHomePageAdapter() {
final Object pojo = getHomePageResolverService().getHomePage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
import org.apache.causeway.core.metamodel.interactions.VisibilityContext;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.core.metamodel.object.ManagedObjects;
import org.apache.causeway.core.metamodel.services.command.CommandDtoFactory;
import org.apache.causeway.core.metamodel.spec.feature.MixedInMember;
import org.apache.causeway.core.metamodel.spec.feature.ObjectMember;
import org.apache.causeway.schema.cmd.v2.CommandDto;
Expand Down Expand Up @@ -322,10 +321,6 @@ protected InteractionProvider getInteractionContext() {
return getServiceRegistry().lookupServiceElseFail(InteractionProvider.class);
}

protected CommandDtoFactory getCommandDtoFactory() {
return getServiceRegistry().lookupServiceElseFail(CommandDtoFactory.class);
}

@Override
public String asciiId() {
return getMetaModelContext().getAsciiIdentifierService().asciiIdFor(getId());
Expand Down
1 change: 1 addition & 0 deletions core/runtimeservices/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
requires spring.tx;
requires org.apache.causeway.core.codegen.bytebuddy;
requires spring.aop;
requires java.management;

opens org.apache.causeway.core.runtimeservices.wrapper;
opens org.apache.causeway.core.runtimeservices.wrapper.proxy; //to org.apache.causeway.core.codegen.bytebuddy
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.core.runtimeservices.wrapper;

import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;

import org.apache.causeway.applib.services.wrapper.control.AsyncControl;
import org.apache.causeway.commons.internal.reflection._GenericResolver;
import org.apache.causeway.core.metamodel.context.MetaModelContext;
import org.apache.causeway.core.metamodel.spec.ObjectSpecification;
import org.apache.causeway.core.metamodel.spec.feature.MixedIn;
import org.apache.causeway.core.metamodel.spec.feature.MixedInMember;
import org.apache.causeway.core.metamodel.spec.feature.ObjectAction;
import org.apache.causeway.core.runtimeservices.session.InteractionIdGenerator;
import org.apache.causeway.core.runtimeservices.wrapper.handlers.DomainObjectInvocationHandler;

import lombok.NonNull;
import lombok.val;

class InvocationHandlerForAsyncWrapMixin<T, R> extends InvocationHandlerforAsyncAbstract<T,R> {

private final @NonNull Object mixeePojo;

public InvocationHandlerForAsyncWrapMixin(
final MetaModelContext metaModelContext,
final InteractionIdGenerator interactionIdGenerator,
final ExecutorService commonExecutorService,
final @NonNull AsyncControl<R> asyncControl,
final T targetPojo,
final ObjectSpecification targetSpecification,
final @NonNull Object mixeePojo) {
super(metaModelContext, interactionIdGenerator, commonExecutorService, asyncControl, targetPojo, targetSpecification);
this.mixeePojo = mixeePojo;
}

@Override
public Object invoke(Object proxyObject, Method method, Object[] args) throws Throwable {

val resolvedMethod = _GenericResolver.resolveMethod(method, targetPojo.getClass())
.orElseThrow(); // fail early on attempt to invoke method that is not part of the meta-model

if (isInheritedFromJavaLangObject(method)) {
return method.invoke(targetPojo, args);
}

if (shouldCheckRules(asyncControl)) {
val doih = new DomainObjectInvocationHandler<>(
metaModelContext,
null, targetSpecification
);

try {
doih.invoke(proxyObject, method, args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}

val memberAndTarget = locateMemberAndTarget(resolvedMethod, mixeePojo, targetSpecification);
if (!memberAndTarget.isMemberFound()) {
return method.invoke(targetPojo, args);
}

return submitAsync(memberAndTarget, args, asyncControl);
}

<Q> MemberAndTarget locateMemberAndTarget(
final _GenericResolver.ResolvedMethod method,
final Q mixeePojo,
final ObjectSpecification targetSpecification
) {

final var mixinMember = targetSpecification.getMember(method).orElse(null);
if (mixinMember == null) {
return MemberAndTarget.notFound();
}

// find corresponding action of the mixee (this is the 'real' target, the target usable for invocation).
final var mixeeClass = mixeePojo.getClass();

// don't care about anything other than actions
// (contributed properties and collections are read-only).
final ObjectAction targetAction = metaModelContext.getSpecificationLoader().specForType(mixeeClass)
.flatMap(mixeeSpec->mixeeSpec.streamAnyActions(MixedIn.ONLY)
.filter(act -> ((MixedInMember)act).hasMixinAction((ObjectAction) mixinMember))
.findFirst()
)
.orElseThrow(()->new UnsupportedOperationException(String.format(
"Could not locate objectAction delegating to mixinAction id='%s' on mixee class '%s'",
mixinMember.getId(), mixeeClass.getName())));

return MemberAndTarget.foundAction(targetAction, metaModelContext.getObjectManager().adapt(mixeePojo), method.method());
}

}
Loading