You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by GitBox <gi...@apache.org> on 2023/01/10 08:20:58 UTC

[GitHub] [maven] laeubi commented on a diff in pull request #950: Use proxies for session scoped beans

laeubi commented on code in PR #950:
URL: https://github.com/apache/maven/pull/950#discussion_r1065459793


##########
maven-core/src/main/java/org/apache/maven/session/scope/internal/InstanceBuilder.java:
##########
@@ -0,0 +1,139 @@
+/*
+ * 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.maven.session.scope.internal;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.stream.Collectors;
+
+import com.google.common.base.Preconditions;
+import com.google.inject.Provider;
+import com.google.inject.internal.Errors;
+import com.google.inject.spi.Message;
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
+import net.bytebuddy.implementation.InvocationHandlerAdapter;
+import net.bytebuddy.matcher.ElementMatchers;
+
+/**
+ * Builds a proxy instance which is backed by a scoped provider.
+ *
+ * @author Simon Taddiken
+ * @param <T> Type of the proxy to create.
+ */
+final class InstanceBuilder<T> {
+
+    private Class<T> superType;
+    private InvocationHandler dispatcher;
+
+    private InstanceBuilder(Class<T> superType) {
+        this.superType = superType;
+    }
+
+    /**
+     * Builds a scoped proxy instance which is a subtype of the given class.
+     *
+     * @param type The class.
+     * @return Builder object for further configuration.
+     */
+    public static <E> InstanceBuilder<E> forType(Class<E> type) {
+        Preconditions.checkNotNull(type, "type");
+        Preconditions.checkArgument(
+                !Modifier.isFinal(type.getModifiers()), "can not proxy final type %s", type.getName());
+        return new InstanceBuilder<>(type);
+    }
+
+    /**
+     * Specifies the scoped provider. Every method call on the object created by this
+     * builder will be delegated to the object returned by the given provider.
+     *
+     * @param provider The scoped provider.
+     * @return Builder object for further configuration.
+     */
+    public InstanceBuilder<T> dispatchTo(Provider<T> provider) {
+        Preconditions.checkNotNull(provider, "provider");
+        final InvocationHandler callback = (proxy, method, args) -> method.invoke(provider.get(), args);
+        this.dispatcher = callback;
+        return this;
+    }
+
+    /**
+     * Creates the scoped proxy object using the given provider.
+     *
+     * @return The scoped proxy object.
+     */
+    @SuppressWarnings("unchecked")
+    public T create() {
+        Preconditions.checkState(this.dispatcher != null, "no provider set");
+        Class<? extends T> enhanced = new ByteBuddy()
+                .subclass(superType)
+                .method(ElementMatchers.any())
+                .intercept(InvocationHandlerAdapter.of(this.dispatcher))
+                .make()
+                .load(superType.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
+                .getLoaded();
+        Errors errors = new Errors();
+        T proxyInstance = createInstanceWithNullValues(enhanced, errors);
+        errors.throwProvisionExceptionIfErrorsExist();
+        return proxyInstance;
+    }
+
+    private <T> T createInstanceWithNullValues(Class<T> proxyClass, Errors errors) {
+        try {
+            final Constructor<T> ctor = getConstructorFor(proxyClass);
+            final Object[] args = new Object[ctor.getParameterCount()];
+            return callConstructor(ctor, errors, args);
+        } catch (final NoSuchMethodException e) {
+            errors.addMessage(new Message(e.getMessage(), e));
+            return null;
+        }
+    }
+
+    private <T> Constructor<T> getConstructorFor(Class<T> proxyClass) throws NoSuchMethodException {
+        final Collection<Constructor<?>> ctors = Arrays.stream(proxyClass.getConstructors())

Review Comment:
   Not sure if it is required, but from my testing I have the impression that one either need an `@Inject` annotated constructor or a default contructor without arguments.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org