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

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_r201092099
 
 

 ##########
 File path: 
sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/POJOUtils.java
 ##########
 @@ -0,0 +1,298 @@
+/*
+ * 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.Maps;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+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.field.FieldDescription.ForLoadedField;
+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.FieldAccess;
+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.TypeInformation;
+import org.apache.beam.sdk.values.TypeDescriptor;
+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 POJOs. */
+@Experimental(Kind.SCHEMAS)
+public class POJOUtils {
+  public static Schema schemaFromPojoClass(Class<?> clazz) {
+    // We should cache the field order.
+    Function<Class, List<TypeInformation>> getTypesForClass =
+        c ->
+            ReflectUtils.getFields(c)
+                .stream()
+                .map(TypeInformation::new)
+                .collect(Collectors.toList());
+    return StaticSchemaInference.schemaFromClass(clazz, getTypesForClass);
+  }
+
+  // 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.
+  public static final Map<ClassWithSchema, List<FieldValueGetter>> 
CACHED_GETTERS =
+      Maps.newConcurrentMap();
+
+  public static List<FieldValueGetter> getGetters(Class<?> clazz, Schema 
schema) {
+    // Return the getters ordered by their position in the schema.
+    return CACHED_GETTERS.computeIfAbsent(
+        new ClassWithSchema(clazz, schema),
+        c -> {
+          Map<String, FieldValueGetter> getterMap =
+              ReflectUtils.getFields(clazz)
+                  .stream()
+                  .map(POJOUtils::createGetter)
+                  .collect(Collectors.toMap(FieldValueGetter::name, 
Function.identity()));
+          return schema
+              .getFields()
+              .stream()
+              .map(f -> getterMap.get(f.getName()))
+              .collect(Collectors.toList());
+        });
+  }
+
+  /**
+   * Generate the following {@link FieldValueSetter} class for the {@link 
Field}.
+   *
+   * <pre><code>
+   *   class Getter implements {@literal FieldValueGetter<POJO, FieldType>} {
+   *     {@literal @}Override public String name() { return field.getName(); }
+   *     {@literal @}Override public Class type() { return field.getType(); }
+   *      {@literal @}Override public FieldType get(POJO pojo) {
+   *        return convert(pojo.field);
+   *      }
+   *   }
+   * </code></pre>
+   */
+  @SuppressWarnings("unchecked")
+  static <ObjectT, ValueT> FieldValueGetter<ObjectT, ValueT> 
createGetter(Field field) {
+    DynamicType.Builder<FieldValueGetter> builder =
+        ByteBuddyUtils.subclassGetterInterface(
+            BYTE_BUDDY,
+            field.getDeclaringClass(),
+            new ConvertType().convert(TypeDescriptor.of(field.getType())));
+    builder = implementGetterMethods(builder, field);
+    try {
+      return builder
+          .make()
+          .load(POJOUtils.class.getClassLoader(), 
ClassLoadingStrategy.Default.INJECTION)
 
 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:
us...@infra.apache.org


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

    Worklog Id:     (was: 120930)
    Time Spent: 7h 20m  (was: 7h 10m)

> 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 20m
>  Remaining Estimate: 0h
>




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

Reply via email to