beam-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "ASF GitHub Bot (JIRA)" <j...@apache.org>
Subject [jira] [Work logged] (BEAM-4453) Provide automatic schema registration for POJOs
Date Mon, 09 Jul 2018 17:53:00 GMT

     [ https://issues.apache.org/jira/browse/BEAM-4453?focusedWorklogId=120932&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-120932
]

ASF GitHub Bot logged work on BEAM-4453:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 09/Jul/18 17:52
            Start Date: 09/Jul/18 17:52
    Worklog Time Spent: 10m 
      Work Description: reuvenlax commented on a change in pull request #5873: [BEAM-4453]
Add schema support for Java POJOs and Java Beans
URL: https://github.com/apache/beam/pull/5873#discussion_r201092123
 
 

 ##########
 File path: sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JavaBeanUtils.java
 ##########
 @@ -0,0 +1,335 @@
+/*
+ * 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.beam.sdk.schemas.utils;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.description.method.MethodDescription.ForLoadedMethod;
+import net.bytebuddy.dynamic.DynamicType;
+import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
+import net.bytebuddy.dynamic.scaffold.InstrumentedType;
+import net.bytebuddy.implementation.FixedValue;
+import net.bytebuddy.implementation.Implementation;
+import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
+import net.bytebuddy.implementation.bytecode.ByteCodeAppender.Size;
+import net.bytebuddy.implementation.bytecode.StackManipulation;
+import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
+import net.bytebuddy.implementation.bytecode.member.MethodReturn;
+import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
+import net.bytebuddy.matcher.ElementMatchers;
+import org.apache.beam.sdk.annotations.Experimental;
+import org.apache.beam.sdk.annotations.Experimental.Kind;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertType;
+import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertValueForGetter;
+import org.apache.beam.sdk.schemas.utils.ReflectUtils.ClassWithSchema;
+import org.apache.beam.sdk.schemas.utils.StaticSchemaInference.MethodType;
+import org.apache.beam.sdk.schemas.utils.StaticSchemaInference.TypeInformation;
+import org.apache.beam.sdk.values.reflect.FieldValueGetter;
+import org.apache.beam.sdk.values.reflect.FieldValueSetter;
+
+/** A set of utilities yo generate getter and setter classes for JavaBean objects. */
+@Experimental(Kind.SCHEMAS)
+public class JavaBeanUtils {
+  /** Create a {@link Schema} for a Java Bean class. */
+  public static Schema schemaFromJavaBeanClass(Class<?> clazz) {
+    return StaticSchemaInference.schemaFromClass(clazz, JavaBeanUtils::typeInformationFromClass);
+  }
+
+  private static List<TypeInformation> typeInformationFromClass(Class<?> clazz)
{
+    try {
+      List<TypeInformation> getterTypes =
+          ReflectUtils.getMethods(clazz)
+              .stream()
+              .filter(ReflectUtils::isGetter)
+              .map(m -> new TypeInformation(m, MethodType.GETTER))
+              .collect(Collectors.toList());
+
+      Map<String, TypeInformation> setterTypes =
+          ReflectUtils.getMethods(clazz)
+              .stream()
+              .filter(ReflectUtils::isSetter)
+              .map(m -> new TypeInformation(m, MethodType.SETTER))
+              .collect(Collectors.toMap(TypeInformation::getName, Function.identity()));
+      validateJavaBean(getterTypes, setterTypes);
+      return getterTypes;
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  // Make sure that there are matching setters and getters.
+  private static void validateJavaBean(
+      List<TypeInformation> getters, Map<String, TypeInformation> setters) {
+    for (TypeInformation type : getters) {
+      TypeInformation setterType = setters.get(type.getName());
+      if (setterType == null) {
+        throw new RuntimeException(
+            "JavaBean contained a setter for field "
+                + type.getName()
+                + "but did not contain a matching getter.");
+      }
+      if (!type.equals(setterType)) {
+        throw new RuntimeException(
+            "JavaBean contained mismatching setter for field" + type.getName());
+      }
+    }
+  }
+
+  // Static ByteBuddy instance used by all helpers.
+  private static final ByteBuddy BYTE_BUDDY = new ByteBuddy();
+
+  // The list of getters for a class is cached, so we only create the classes the first time
+  // getSetters is called.
+  private static final Map<ClassWithSchema, List<FieldValueGetter>> CACHED_GETTERS
=
+      Maps.newConcurrentMap();
+
+  /**
+   * Return the list of {@link FieldValueGetter}s for a Java Bean class
+   *
+   * <p>The returned list is ordered by the order of fields in the schema.
+   */
+  public static List<FieldValueGetter> getGetters(Class<?> clazz, Schema schema)
{
+    return CACHED_GETTERS.computeIfAbsent(
+        new ClassWithSchema(clazz, schema),
+        c -> {
+          try {
+            Map<String, FieldValueGetter> getterMap =
+                ReflectUtils.getMethods(clazz)
+                    .stream()
+                    .filter(ReflectUtils::isGetter)
+                    .map(JavaBeanUtils::createGetter)
+                    .collect(Collectors.toMap(FieldValueGetter::name, Function.identity()));
+            List<FieldValueGetter> getters = Lists.newArrayList();
+            for (int i = 0; i < schema.getFieldCount(); ++i) {
+              getters.add(getterMap.get(schema.getField(i).getName()));
+            }
+            System.out.println("Returning for Schema " + schema + " getters " + getters);
+
+            return getters;
+            /*
+            return schema
+                .getFields()
+                .stream()
+                .map(f -> getterMap.get(f.getName()))
+                .collect(Collectors.toList());*/
+          } catch (IOException e) {
+            throw new RuntimeException(e);
+          }
+        });
+  }
+
+  private static <T> FieldValueGetter createGetter(Method getterMethod) {
+    TypeInformation typeInformation = new TypeInformation(getterMethod, MethodType.GETTER);
+    DynamicType.Builder<FieldValueGetter> builder =
+        ByteBuddyUtils.subclassGetterInterface(
+            BYTE_BUDDY,
+            getterMethod.getDeclaringClass(),
+            new ConvertType().convert(typeInformation.getType()));
+    builder = implementGetterMethods(builder, getterMethod);
+    try {
+      return builder
+          .make()
+          .load(POJOUtils.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
+          .getLoaded()
+          .getDeclaredConstructor()
+          .newInstance();
+    } catch (InstantiationException
+        | IllegalAccessException
+        | NoSuchMethodException
+        | InvocationTargetException e) {
+      throw new RuntimeException("Unable to generate a getter for getter '" + getterMethod
+ "'");
+    }
+  }
+
+  private static DynamicType.Builder<FieldValueGetter> implementGetterMethods(
+      DynamicType.Builder<FieldValueGetter> builder, Method method) {
+    TypeInformation typeInformation = new TypeInformation(method, MethodType.GETTER);
+    return builder
+        .method(ElementMatchers.named("name"))
+        .intercept(FixedValue.reference(typeInformation.getName()))
+        .method(ElementMatchers.named("type"))
+        .intercept(FixedValue.reference(typeInformation.getType().getRawType()))
+        .method(ElementMatchers.named("get"))
+        .intercept(new InvokeGetterInstruction(method));
+  }
+
+  // The list of setters for a class is cached, so we only create the classes the first time
+  // getSetters is called.
+  private static final Map<ClassWithSchema, List<FieldValueSetter>> CACHED_SETTERS
=
+      Maps.newConcurrentMap();
+
+  /**
+   * Return the list of {@link FieldValueSetter}s for a Java Bean class
+   *
+   * <p>The returned list is ordered by the order of fields in the schema.
+   */
+  public static List<FieldValueSetter> getSetters(Class<?> clazz, Schema schema)
{
+    return CACHED_SETTERS.computeIfAbsent(
+        new ClassWithSchema(clazz, schema),
+        c -> {
+          try {
+            Map<String, FieldValueSetter> setterMap =
+                ReflectUtils.getMethods(clazz)
+                    .stream()
+                    .filter(ReflectUtils::isSetter)
+                    .map(JavaBeanUtils::createSetter)
+                    .collect(Collectors.toMap(FieldValueSetter::name, Function.identity()));
+            return schema
+                .getFields()
+                .stream()
+                .map(f -> setterMap.get(f.getName()))
+                .collect(Collectors.toList());
+          } catch (IOException e) {
+            throw new RuntimeException(e);
+          }
+        });
+  }
+
+  private static <T> FieldValueSetter createSetter(Method setterMethod) {
+    TypeInformation typeInformation = new TypeInformation(setterMethod, MethodType.SETTER);
+    DynamicType.Builder<FieldValueSetter> builder =
+        ByteBuddyUtils.subclassSetterInterface(
+            BYTE_BUDDY,
+            setterMethod.getDeclaringClass(),
+            new ConvertType().convert(typeInformation.getType()));
+    builder = implementSetterMethods(builder, setterMethod);
+    try {
+      return builder
+          .make()
+          .load(POJOUtils.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
+          .getLoaded()
+          .getDeclaredConstructor()
+          .newInstance();
+    } catch (InstantiationException
+        | IllegalAccessException
+        | NoSuchMethodException
+        | InvocationTargetException e) {
+      throw new RuntimeException("Unable to generate a getter for getter '" + setterMethod
+ "'");
 
 Review comment:
   done

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Issue Time Tracking
-------------------

    Worklog Id:     (was: 120932)
    Time Spent: 7h 40m  (was: 7.5h)

> Provide automatic schema registration for POJOs
> -----------------------------------------------
>
>                 Key: BEAM-4453
>                 URL: https://issues.apache.org/jira/browse/BEAM-4453
>             Project: Beam
>          Issue Type: Sub-task
>          Components: sdk-java-core
>            Reporter: Reuven Lax
>            Assignee: Reuven Lax
>            Priority: Major
>          Time Spent: 7h 40m
>  Remaining Estimate: 0h
>




--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Mime
View raw message