Skip to content

Causeway 3883 #2926

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 43 commits into
base: maintenance-branch
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
9f8f80c
CAUSEWAY-3883: adds integ test and utility class to demonstrate the i…
danhaywood Apr 8, 2025
72cdbaf
CAUSEWAY-3883: adds Params to hold state instead of ...
danhaywood Apr 8, 2025
c8bebb8
CAUSEWAY-3883: adds Params to hold state instead of ...
danhaywood Apr 8, 2025
5244cd0
CAUSEWAY-3883: passes MetaModelContext into DOIH
danhaywood Apr 8, 2025
c71cbb6
CAUSEWAY-3883: simplifies DOIH a little
danhaywood Apr 8, 2025
2cd92ae
CAUSEWAY-3883: passes MetaModelContext into DOIH (2)
danhaywood Apr 8, 2025
51e4d96
CAUSEWAY-3883: passes mixee as well as mixeeAdapter
danhaywood Apr 8, 2025
2017723
CAUSEWAY-3883: renames parameters is all
danhaywood Apr 8, 2025
b8122a9
CAUSEWAY-3883: derives mixeeAdapter from mixee, in DOIH
danhaywood Apr 8, 2025
7c57aba
CAUSEWAY-3883: removes mixeeAdapter from DOIH constructor, no longer …
danhaywood Apr 8, 2025
f73d944
CAUSEWAY-3883: passes ObjectSpecification into DOIH
danhaywood Apr 8, 2025
f6f328f
CAUSEWAY-3883: towards removing use of adapters in DOIH etc
danhaywood Apr 8, 2025
d9275c6
CAUSEWAY-3883: removes EntityFacet
danhaywood Apr 8, 2025
9a61e01
CAUSEWAY-3883: moves parameters around a little in DOIH
danhaywood Apr 8, 2025
9880734
CAUSEWAY-3883: captures WrapperInvocationContext as a field on the pr…
danhaywood Apr 8, 2025
d579a04
CAUSEWAY-3883: extending scope of tests for collections
danhaywood Apr 8, 2025
3407d75
CAUSEWAY-3883: introduces delegateClass in DelegatingInvocationHandle…
danhaywood Apr 8, 2025
68ba73c
CAUSEWAY-3883: simplifying DelegatingIHA
danhaywood Apr 8, 2025
eda59d0
CAUSEWAY-3883: minor tidy ups
danhaywood Apr 8, 2025
f1fc46a
CAUSEWAY-3883: integ tests passing...
danhaywood Apr 8, 2025
21e705d
CAUSEWAY-3883: access mixeePojo from WrapperInteractionContext
danhaywood Apr 8, 2025
bb1c953
CAUSEWAY-3883: renames delegate --> target
danhaywood Apr 8, 2025
418273e
CAUSEWAY-3883: completes rename
danhaywood Apr 8, 2025
f1c883f
CAUSEWAY-3883: adds some unit tests to measure
danhaywood Apr 8, 2025
98752b8
CAUSEWAY-3883: removes debugging statements
danhaywood Apr 8, 2025
a351f40
CAUSEWAY-3883: improves test measurements
danhaywood Apr 9, 2025
ce9cbb1
CAUSEWAY-3883: minor tidy-up
danhaywood Apr 14, 2025
7b4ac3d
CAUSEWAY-3883: minor tidy up
danhaywood Apr 14, 2025
782d730
ESP-3883 : adds proxyObject as param throughout
danhaywood Apr 14, 2025
49814b9
ESP-3883 : adds proxyObject as param throughout (2)
danhaywood Apr 14, 2025
ef3c93c
ESP-3883 : adds proxyObject as param throughout (3)
danhaywood Apr 14, 2025
bac895f
ESP-3883 : removes __causeway_wrapperInvocationContext method from Wr…
danhaywood Apr 14, 2025
ffdc3a0
ESP-3883 : moves InvocationHandler anonymous classes out for async.
danhaywood Apr 14, 2025
925f506
ESP-3883 : factors out superclass for InvocationHandlers for async.
danhaywood Apr 14, 2025
c28ca4c
ESP-3883 : removes mixinClass, redundant
danhaywood Apr 14, 2025
a634d51
ESP-3883 : passes in MetaModelContext
danhaywood Apr 14, 2025
dc7d2de
ESP-3883 : removes further unnecessary differences.
danhaywood Apr 14, 2025
1708cbf
CAUSEWAY-3883: minor refactorings
danhaywood Apr 14, 2025
96b622a
ESP-3883 : removes use of ThreadLocal
danhaywood Apr 15, 2025
516d636
CAUSEWAY-3883: further small refinements
danhaywood Apr 15, 2025
55b59b4
CAUSEWAY-3883: fixes compile issue
danhaywood Apr 15, 2025
34b20ea
CAUSEWAY-3883: adds a fix
danhaywood Apr 15, 2025
789d2f2
CAUSEWAY-3883: fixes invalid refactoring
danhaywood Apr 15, 2025
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 @@ -59,6 +59,7 @@ public interface WrappingObject {
*/
Object __causeway_wrapped();


/**
* The {@link ExecutionMode}(s) inferred from the
* {@link SyncControl} with which this wrapper was
Expand Down
2 changes: 2 additions & 0 deletions commons/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,10 @@
requires com.fasterxml.jackson.datatype.jsr310;
requires com.fasterxml.jackson.dataformat.yaml;
requires com.fasterxml.jackson.datatype.jdk8;
requires java.management;

opens org.apache.causeway.commons.internal.resources to java.xml.bind, com.sun.xml.bind; // JUnit test
opens org.apache.causeway.commons.io to java.xml.bind, com.sun.xml.bind;
exports org.apache.causeway.commons.memory;

}
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
@@ -0,0 +1,67 @@
package org.apache.causeway.commons.memory;

import lombok.SneakyThrows;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.concurrent.Callable;

public class MemoryUsage {

private MemoryUsage(java.lang.management.MemoryUsage usage) {
this(usage.getUsed() / 1024);
}

private MemoryUsage(final long usedInKb) {
this.usedInKb = usedInKb;
}

final long usedInKb;

@Override
public String toString() {
return String.format("%,d KB", usedInKb);
}

public static void measureMetaspace(String desc, final Runnable runnable) {
MemoryUsage before = metaspace();
try {
runnable.run();
} finally {
MemoryUsage after = metaspace();
System.out.printf("%s : %s%n", after.minus(before), desc);
}
}

static int indent = 0;

@SneakyThrows
public static <T> T measureMetaspace(final String desc, final Callable<T> runnable) {
MemoryUsage before = metaspace();
try {
indent++;
return runnable.call();
} finally {
MemoryUsage after = metaspace();
System.out.printf("%s%s : %s%n", spaces(indent), after.minus(before), desc);
indent--;
}
}

private static String spaces(int indent) {
return " ".repeat(indent * 2);
}

private MemoryUsage minus(MemoryUsage before) {
return new MemoryUsage(this.usedInKb - before.usedInKb);
}

public static MemoryUsage metaspace() {
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
if (pool.getName().contains("Metaspace")) {
return new MemoryUsage(pool.getUsage());
}
}
throw new RuntimeException("Metaspace Usage not found");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@
*/
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.function.Function;

import org.springframework.lang.Nullable;
Expand All @@ -29,6 +33,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,7 +49,9 @@
@Service
public class ProxyFactoryServiceByteBuddy extends _ProxyFactoryServiceAbstract {


private final ClassLoadingStrategyAdvisor strategyAdvisor = new ClassLoadingStrategyAdvisor();
private Map<InvocationHandler, Class<?>> proxyClassByInvocationHandler = _Maps.newConcurrentHashMap();

@Override
public <T> _ProxyFactory<T> factory(
Expand All @@ -54,21 +61,47 @@ 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<>() {

/**
* Cached proxy class by invocation handler.
*
* <p>
* The only state held in invocation handler is the org.apache.causeway.core.metamodel.spec.ObjectSpecification,
*. in effect the target class.
* </p>
*
* <p>
* The remaining state (defined by WrapperInvocationContext) is held in the proxy object itself as a field.
* </p>
* @return
*/
@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 +134,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 @@ -22,6 +22,8 @@
import java.util.function.Supplier;
import java.util.stream.Stream;

import org.apache.causeway.core.metamodel.services.command.CommandDtoFactory;

import org.springframework.lang.Nullable;

import org.apache.causeway.applib.locale.UserLocale;
Expand Down Expand Up @@ -150,6 +152,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 @@ -322,10 +322,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,115 @@
/*
* 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 org.apache.causeway.core.runtimeservices.wrapper.handlers.WrapperInvocationContext;

import static org.apache.causeway.applib.services.wrapper.control.SyncControl.control;

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