dawidwys commented on a change in pull request #8050: [FLINK-11067][table] 
Convert TableEnvironments to interfaces
URL: https://github.com/apache/flink/pull/8050#discussion_r276182707
 
 

 ##########
 File path: 
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/factories/TableFactoryService.java
 ##########
 @@ -0,0 +1,363 @@
+/*
+ * 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.flink.table.factories;
+
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.table.api.AmbiguousTableFactoryException;
+import org.apache.flink.table.api.NoMatchingTableFactoryException;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.descriptors.Descriptor;
+import org.apache.flink.table.descriptors.FormatDescriptorValidator;
+import org.apache.flink.table.descriptors.Schema;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static 
org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_PROPERTY_VERSION;
+import static 
org.apache.flink.table.descriptors.ExternalCatalogDescriptorValidator.CATALOG_PROPERTY_VERSION;
+import static 
org.apache.flink.table.descriptors.FormatDescriptorValidator.FORMAT_PROPERTY_VERSION;
+import static 
org.apache.flink.table.descriptors.MetadataValidator.METADATA_PROPERTY_VERSION;
+import static 
org.apache.flink.table.descriptors.StatisticsValidator.STATISTICS_PROPERTY_VERSION;
+
+/**
+ * Unified class to search for a {@link TableFactory} of provided type and 
properties.
+ */
+public class TableFactoryService {
+
+       private static final ServiceLoader<TableFactory> defaultLoader = 
ServiceLoader.load(TableFactory.class);
+       private static final transient Logger LOG = 
LoggerFactory.getLogger(TableFactoryService.class);
+
+       /**
+        * Finds a table factory of the given class and descriptor.
+        *
+        * @param factoryClass desired factory class
+        * @param descriptor descriptor describing the factory configuration
+        * @param <T> factory class type
+        * @return the matching factory
+        */
+       public static <T> T find(Class<T> factoryClass, Descriptor descriptor) {
+               Preconditions.checkNotNull(descriptor);
+               return findInternal(factoryClass, descriptor.toProperties(), 
Optional.empty());
+       }
+
+       /**
+        * Finds a table factory of the given class, descriptor, and 
classloader.
+        *
+        * @param factoryClass desired factory class
+        * @param descriptor descriptor describing the factory configuration
+        * @param classLoader classloader for service loading
+        * @param <T> factory class type
+        * @return the matching factory
+        */
+       public static <T> T find(Class<T> factoryClass, Descriptor descriptor, 
ClassLoader classLoader) {
+               Preconditions.checkNotNull(descriptor);
+               Preconditions.checkNotNull(classLoader);
+               return findInternal(factoryClass, descriptor.toProperties(), 
Optional.of(classLoader));
+       }
+
+       /**
+        * Finds a table factory of the given class and property map.
+        *
+        * @param factoryClass desired factory class
+        * @param propertyMap properties that describe the factory configuration
+        * @param <T> factory class type
+        * @return the matching factory
+        */
+       public static <T> T find(Class<T> factoryClass, Map<String, String> 
propertyMap) {
+               return findInternal(factoryClass, propertyMap, 
Optional.empty());
+       }
+
+       /**
+        * Finds a table factory of the given class, property map, and 
classloader.
+        *
+        * @param factoryClass desired factory class
+        * @param propertyMap properties that describe the factory configuration
+        * @param classLoader classloader for service loading
+        * @param <T> factory class type
+        * @return the matching factory
+        */
+       public static <T> T find(Class<T> factoryClass, Map<String, String> 
propertyMap, ClassLoader classLoader) {
+               Preconditions.checkNotNull(classLoader);
+               return findInternal(factoryClass, propertyMap, 
Optional.of(classLoader));
+       }
+
+       /**
+        * Finds a table factory of the given class, property map, and 
classloader.
+        *
+        * @param factoryClass desired factory class
+        * @param properties properties that describe the factory configuration
+        * @param classLoader classloader for service loading
+        * @param <T> factory class type
+        * @return the matching factory
+        */
+       public static <T> T findInternal(Class<T> factoryClass, Map<String, 
String> properties, Optional<ClassLoader> classLoader) {
+
+               Preconditions.checkNotNull(factoryClass);
+               Preconditions.checkNotNull(properties);
+
+               List<TableFactory> foundFactories = 
discoverFactories(classLoader);
+
+               List<TableFactory> classFactories = filterByFactoryClass(
+                       factoryClass,
+                       properties,
+                       foundFactories);
+
+               List<TableFactory> contextFactories = filterByContext(
+                       factoryClass,
+                       properties,
+                       foundFactories,
+                       classFactories);
+
+               return filterBySupportedProperties(
+                       factoryClass,
+                       properties,
+                       foundFactories,
+                       contextFactories);
+       }
+
+       /**
+        * Searches for factories using Java service providers.
+        *
+        * @return all factories in the classpath
+        */
+       private static List<TableFactory> 
discoverFactories(Optional<ClassLoader> classLoader) {
+               try {
+                       List<TableFactory> result = new LinkedList<>();
+                       if (classLoader.isPresent()) {
+                               ServiceLoader
+                                       .load(TableFactory.class, 
classLoader.get())
+                                       .iterator()
+                                       .forEachRemaining(result::add);
+                       } else {
+                               
defaultLoader.iterator().forEachRemaining(result::add);
+                       }
+                       return result;
+               } catch (ServiceConfigurationError e) {
+                       LOG.error("Could not load service provider for table 
factories.", e);
+                       throw new TableException("Could not load service 
provider for table factories.", e);
+               }
+
+       }
+
+       /**
+        * Filters factories with matching context by factory class.
+        */
+       private static <T> List<TableFactory> filterByFactoryClass(
+               Class<T> factoryClass,
+               Map<String, String> properties,
+               List<TableFactory> foundFactories) {
+
+               List<TableFactory> classFactories = foundFactories.stream()
+                       .filter(p -> 
factoryClass.isAssignableFrom(p.getClass()))
+                       .collect(Collectors.toList());
+
+               if (classFactories.isEmpty()) {
+                       throw new NoMatchingTableFactoryException(
+                               String.format("No factory implements '%s'.", 
factoryClass.getCanonicalName()),
+                               factoryClass,
+                               foundFactories,
+                               properties);
+               }
+
+               return classFactories;
+       }
+
+       /**
+        * Filters for factories with matching context.
+        *
+        * @return all matching factories
+        */
+       private static <T> List<TableFactory> filterByContext(
+               Class<T> factoryClass,
+               Map<String, String> properties,
+               List<TableFactory> foundFactories,
+               List<TableFactory> classFactories) {
+
+               List<TableFactory> matchingFactories = 
classFactories.stream().filter(factory -> {
+                       Map<String, String> requestedContext = 
normalizeContext(factory);
+
+                       Map<String, String> plainContext = new 
HashMap<>(requestedContext);
+                       // we remove the version for now until we have the 
first backwards compatibility case
+                       // with the version we can provide mappings in case the 
format changes
+                       plainContext.remove(CONNECTOR_PROPERTY_VERSION);
+                       plainContext.remove(FORMAT_PROPERTY_VERSION);
+                       plainContext.remove(METADATA_PROPERTY_VERSION);
+                       plainContext.remove(STATISTICS_PROPERTY_VERSION);
+                       plainContext.remove(CATALOG_PROPERTY_VERSION);
+
+                       // check if required context is met
+                       return plainContext.keySet().stream().allMatch(e -> 
properties.containsKey(e) && properties.get(e).equals(plainContext.get(e)));
+               }).collect(Collectors.toList());
+
+               if (matchingFactories.isEmpty()) {
+                       throw new NoMatchingTableFactoryException(
+                               "No context matches.",
+                               factoryClass,
+                               foundFactories,
+                               properties);
+               }
+
+               return matchingFactories;
+       }
+
+       /**
+        * Prepares the properties of a context to be used for match operations.
+        */
+       private static Map<String, String> normalizeContext(TableFactory 
factory) {
+               Map<String, String> requiredContext = factory.requiredContext();
+               if (requiredContext == null) {
+                       throw new TableException(
+                               String.format("Required context of factory '%s' 
must not be null.", factory.getClass().getName()));
+               }
+               return requiredContext.keySet().stream()
+                       .collect(Collectors.toMap(key -> key.toLowerCase(), key 
-> requiredContext.get(key)));
+       }
+
+       /**
+        * Filters the matching class factories by supported properties.
+        */
+       private static <T> T filterBySupportedProperties(
+               Class<T> factoryClass,
+               Map<String, String> properties,
+               List<TableFactory> foundFactories,
+               List<TableFactory> classFactories) {
+
+               final List<String> plainGivenKeys = new LinkedList<>();
+               properties.keySet().forEach(k -> {
+                       // replace arrays with wildcard
+                       String key = k.replaceAll(".\\d+", ".#");
+                       // ignore duplicates
+                       if (!plainGivenKeys.contains(key)) {
+                               plainGivenKeys.add(key);
+                       }
+               });
+
+               AtomicReference<Optional<String>> lastKey = new 
AtomicReference<>(Optional.empty());
+               List<TableFactory> supportedFactories = 
classFactories.stream().filter(factory -> {
+                       Set<String> requiredContextKeys = 
normalizeContext(factory).keySet();
+                       Tuple2<List<String>, List<String>> tuple2 = 
normalizeSupportedProperties(factory);
+                       // ignore context keys
+                       Stream<String> givenContextFreeKeys = 
plainGivenKeys.stream().filter(p -> !requiredContextKeys.contains(p));
+                       Stream<String> givenFilteredKeys = 
filterSupportedPropertiesFactorySpecific(
+                               factory,
+                               givenContextFreeKeys);
+
+                       return givenFilteredKeys.allMatch(k -> {
+                               lastKey.set(Optional.of(k));
+                               return tuple2.f0.contains(k) || 
tuple2.f1.stream().anyMatch(p -> k.startsWith(p));
+                       });
+               }).collect(Collectors.toList());
+
+               if (supportedFactories.isEmpty() && classFactories.size() == 1 
&& lastKey.get().isPresent()) {
+                       // special case: when there is only one matching 
factory but the last property key
+                       // was incorrect
+                       TableFactory factory = classFactories.get(0);
+                       Tuple2<List<String>, List<String>> tuple2 = 
normalizeSupportedProperties(factory);
+
+                       String errorMessage = "The matching factory '" + 
factory.getClass().getName() + "' doesn't support '" + lastKey.get().get() + 
"'.\n" +
 
 Review comment:
   Use `String.format()`

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to