code
stringlengths 227
324k
| indentifier
stringlengths 171
323k
| lang
stringclasses 2
values |
---|---|---|
for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.server; import com.facebook.airlift.log.Logger; import com.facebook.presto.metadata.FunctionAndTypeManager; import com.facebook.presto.spi.CoordinatorPlugin; import com.facebook.presto.spi.Plugin; import com.facebook.presto.spi.classloader.ThreadContextClassLoader; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; import io.airlift.resolver.ArtifactResolver; import io.airlift.resolver.DefaultArtifact; import org.sonatype.aether.artifact.Artifact; import javax.annotation.concurrent.ThreadSafe; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static com.facebook.presto.metadata.FunctionExtractor.extractFunctions; import static com.facebook.presto.server.PluginDiscovery.discoverPlugins; import static com.facebook.presto.server.PluginDiscovery.writePluginServices; import static java.util.Objects.requireNonNull; @ThreadSafe public class FunctionPluginManager { // When generating code the AfterBurner module loads classes with *some* classloader. // When the AfterBurner module is configured not to use the value classloader // (e.g., AfterBurner().setUseValueClassLoader(false)) AppClassLoader is used for loading those // classes. Otherwise, the PluginClassLoader is used, which is the default behavior. // Therefore, in the former case Afterburner won't be able to load the connector classes // as AppClassLoader doesn't see them, and in the latter case the PluginClassLoader won't be // able to load the AfterBurner classes themselves. So, our solution is to use the PluginClassLoader // and whitelist the AfterBurner classes here, so that the PluginClassLoader can load the // AfterBurner classes. private static final ImmutableList<String> SPI_PACKAGES = ImmutableList.<String>builder() .add("com.facebook.presto.spi.") .add("com.fasterxml.jackson.annotation.") .add("com.fasterxml.jackson.module.afterburner.") .add("io.airlift.slice.") .add("io.airlift.units.") .add("org.openjdk.jol.") .add("com.facebook.presto.common") .add("com.facebook.drift.annotations.") .add("com.facebook.drift.TException") .add("com.facebook.drift.TApplicationException") .build(); // TODO: Add plugins based on FunctionPlugin interface. Currently loading the plugins implemented on Plugin interface to the Function Server for now. private static final String PLUGIN_SERVICES_FILE = "META-INF/services/" + Plugin.class.getName(); private static final Logger log = Logger.get(FunctionPluginManager.class); private final ArtifactResolver resolver; private final File <mask> <mask> <mask> <mask> <mask> <mask> ; private final List<String> plugins; private final AtomicBoolean pluginsLoading = new AtomicBoolean(); private final AtomicBoolean pluginsLoaded = new AtomicBoolean(); private final FunctionAndTypeManager functionAndTypeManager; @Inject public FunctionPluginManager( PluginManagerConfig config, FunctionAndTypeManager functionAndTypeManager) { requireNonNull(config, "config is null"); requireNonNull(functionAndTypeManager, "functionAndTypeManager is null"); this.functionAndTypeManager = functionAndTypeManager; <mask> <mask> <mask> <mask> <mask> <mask> = config.getInstalledPluginsDir(); if (config.getPlugins() == null) { this.plugins = ImmutableList.of(); } else { this.plugins = ImmutableList.copyOf(config.getPlugins()); } this.resolver = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository()); } public void loadPlugins() throws Exception { if (!pluginsLoading.compareAndSet(false, true)) { return; } for (File file : listFiles( <mask> <mask> <mask> <mask> <mask> <mask> )) { if (file.isDirectory()) { loadPlugin(file.getAbsolutePath()); } } for (String plugin : plugins) { loadPlugin(plugin); } pluginsLoaded.set(true); } private void loadPlugin(String plugin) throws Exception { log.info("-- Loading plugin %s --", plugin); URLClassLoader pluginClassLoader = buildClassLoader(plugin); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(pluginClassLoader)) { loadPlugin(pluginClassLoader, Plugin.class); } log.info("-- Finished loading plugin %s --", plugin); } private void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts | for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.server; import com.facebook.airlift.log.Logger; import com.facebook.presto.metadata.FunctionAndTypeManager; import com.facebook.presto.spi.CoordinatorPlugin; import com.facebook.presto.spi.Plugin; import com.facebook.presto.spi.classloader.ThreadContextClassLoader; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; import io.airlift.resolver.ArtifactResolver; import io.airlift.resolver.DefaultArtifact; import org.sonatype.aether.artifact.Artifact; import javax.annotation.concurrent.ThreadSafe; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static com.facebook.presto.metadata.FunctionExtractor.extractFunctions; import static com.facebook.presto.server.PluginDiscovery.discoverPlugins; import static com.facebook.presto.server.PluginDiscovery.writePluginServices; import static java.util.Objects.requireNonNull; @ThreadSafe public class FunctionPluginManager { // When generating code the AfterBurner module loads classes with *some* classloader. // When the AfterBurner module is configured not to use the value classloader // (e.g., AfterBurner().setUseValueClassLoader(false)) AppClassLoader is used for loading those // classes. Otherwise, the PluginClassLoader is used, which is the default behavior. // Therefore, in the former case Afterburner won't be able to load the connector classes // as AppClassLoader doesn't see them, and in the latter case the PluginClassLoader won't be // able to load the AfterBurner classes themselves. So, our solution is to use the PluginClassLoader // and whitelist the AfterBurner classes here, so that the PluginClassLoader can load the // AfterBurner classes. private static final ImmutableList<String> SPI_PACKAGES = ImmutableList.<String>builder() .add("com.facebook.presto.spi.") .add("com.fasterxml.jackson.annotation.") .add("com.fasterxml.jackson.module.afterburner.") .add("io.airlift.slice.") .add("io.airlift.units.") .add("org.openjdk.jol.") .add("com.facebook.presto.common") .add("com.facebook.drift.annotations.") .add("com.facebook.drift.TException") .add("com.facebook.drift.TApplicationException") .build(); // TODO: Add plugins based on FunctionPlugin interface. Currently loading the plugins implemented on Plugin interface to the Function Server for now. private static final String PLUGIN_SERVICES_FILE = "META-INF/services/" + Plugin.class.getName(); private static final Logger log = Logger.get(FunctionPluginManager.class); private final ArtifactResolver resolver; private final File installedPluginsDir ; private final List<String> plugins; private final AtomicBoolean pluginsLoading = new AtomicBoolean(); private final AtomicBoolean pluginsLoaded = new AtomicBoolean(); private final FunctionAndTypeManager functionAndTypeManager; @Inject public FunctionPluginManager( PluginManagerConfig config, FunctionAndTypeManager functionAndTypeManager) { requireNonNull(config, "config is null"); requireNonNull(functionAndTypeManager, "functionAndTypeManager is null"); this.functionAndTypeManager = functionAndTypeManager; installedPluginsDir = config.getInstalledPluginsDir(); if (config.getPlugins() == null) { this.plugins = ImmutableList.of(); } else { this.plugins = ImmutableList.copyOf(config.getPlugins()); } this.resolver = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository()); } public void loadPlugins() throws Exception { if (!pluginsLoading.compareAndSet(false, true)) { return; } for (File file : listFiles( installedPluginsDir )) { if (file.isDirectory()) { loadPlugin(file.getAbsolutePath()); } } for (String plugin : plugins) { loadPlugin(plugin); } pluginsLoaded.set(true); } private void loadPlugin(String plugin) throws Exception { log.info("-- Loading plugin %s --", plugin); URLClassLoader pluginClassLoader = buildClassLoader(plugin); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(pluginClassLoader)) { loadPlugin(pluginClassLoader, Plugin.class); } log.info("-- Finished loading plugin %s --", plugin); } private void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts | java |
import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static com.facebook.presto.metadata.FunctionExtractor.extractFunctions; import static com.facebook.presto.server.PluginDiscovery.discoverPlugins; import static com.facebook.presto.server.PluginDiscovery.writePluginServices; import static java.util.Objects.requireNonNull; @ThreadSafe public class FunctionPluginManager { // When generating code the AfterBurner module loads classes with *some* classloader. // When the AfterBurner module is configured not to use the value classloader // (e.g., AfterBurner().setUseValueClassLoader(false)) AppClassLoader is used for loading those // classes. Otherwise, the PluginClassLoader is used, which is the default behavior. // Therefore, in the former case Afterburner won't be able to load the connector classes // as AppClassLoader doesn't see them, and in the latter case the PluginClassLoader won't be // able to load the AfterBurner classes themselves. So, our solution is to use the PluginClassLoader // and whitelist the AfterBurner classes here, so that the PluginClassLoader can load the // AfterBurner classes. private static final ImmutableList<String> SPI_PACKAGES = ImmutableList.<String>builder() .add("com.facebook.presto.spi.") .add("com.fasterxml.jackson.annotation.") .add("com.fasterxml.jackson.module.afterburner.") .add("io.airlift.slice.") .add("io.airlift.units.") .add("org.openjdk.jol.") .add("com.facebook.presto.common") .add("com.facebook.drift.annotations.") .add("com.facebook.drift.TException") .add("com.facebook.drift.TApplicationException") .build(); // TODO: Add plugins based on FunctionPlugin interface. Currently loading the plugins implemented on Plugin interface to the Function Server for now. private static final String PLUGIN_SERVICES_FILE = "META-INF/services/" + Plugin.class.getName(); private static final Logger log = Logger.get(FunctionPluginManager.class); private final ArtifactResolver resolver; private final File <mask> <mask> <mask> <mask> <mask> <mask> ; private final List<String> plugins; private final AtomicBoolean pluginsLoading = new AtomicBoolean(); private final AtomicBoolean pluginsLoaded = new AtomicBoolean(); private final FunctionAndTypeManager functionAndTypeManager; @Inject public FunctionPluginManager( PluginManagerConfig config, FunctionAndTypeManager functionAndTypeManager) { requireNonNull(config, "config is null"); requireNonNull(functionAndTypeManager, "functionAndTypeManager is null"); this.functionAndTypeManager = functionAndTypeManager; <mask> <mask> <mask> <mask> <mask> <mask> = config.getInstalledPluginsDir(); if (config.getPlugins() == null) { this.plugins = ImmutableList.of(); } else { this.plugins = ImmutableList.copyOf(config.getPlugins()); } this.resolver = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository()); } public void loadPlugins() throws Exception { if (!pluginsLoading.compareAndSet(false, true)) { return; } for (File file : listFiles( <mask> <mask> <mask> <mask> <mask> <mask> )) { if (file.isDirectory()) { loadPlugin(file.getAbsolutePath()); } } for (String plugin : plugins) { loadPlugin(plugin); } pluginsLoaded.set(true); } private void loadPlugin(String plugin) throws Exception { log.info("-- Loading plugin %s --", plugin); URLClassLoader pluginClassLoader = buildClassLoader(plugin); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(pluginClassLoader)) { loadPlugin(pluginClassLoader, Plugin.class); } log.info("-- Finished loading plugin %s --", plugin); } private void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); | import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static com.facebook.presto.metadata.FunctionExtractor.extractFunctions; import static com.facebook.presto.server.PluginDiscovery.discoverPlugins; import static com.facebook.presto.server.PluginDiscovery.writePluginServices; import static java.util.Objects.requireNonNull; @ThreadSafe public class FunctionPluginManager { // When generating code the AfterBurner module loads classes with *some* classloader. // When the AfterBurner module is configured not to use the value classloader // (e.g., AfterBurner().setUseValueClassLoader(false)) AppClassLoader is used for loading those // classes. Otherwise, the PluginClassLoader is used, which is the default behavior. // Therefore, in the former case Afterburner won't be able to load the connector classes // as AppClassLoader doesn't see them, and in the latter case the PluginClassLoader won't be // able to load the AfterBurner classes themselves. So, our solution is to use the PluginClassLoader // and whitelist the AfterBurner classes here, so that the PluginClassLoader can load the // AfterBurner classes. private static final ImmutableList<String> SPI_PACKAGES = ImmutableList.<String>builder() .add("com.facebook.presto.spi.") .add("com.fasterxml.jackson.annotation.") .add("com.fasterxml.jackson.module.afterburner.") .add("io.airlift.slice.") .add("io.airlift.units.") .add("org.openjdk.jol.") .add("com.facebook.presto.common") .add("com.facebook.drift.annotations.") .add("com.facebook.drift.TException") .add("com.facebook.drift.TApplicationException") .build(); // TODO: Add plugins based on FunctionPlugin interface. Currently loading the plugins implemented on Plugin interface to the Function Server for now. private static final String PLUGIN_SERVICES_FILE = "META-INF/services/" + Plugin.class.getName(); private static final Logger log = Logger.get(FunctionPluginManager.class); private final ArtifactResolver resolver; private final File installedPluginsDir ; private final List<String> plugins; private final AtomicBoolean pluginsLoading = new AtomicBoolean(); private final AtomicBoolean pluginsLoaded = new AtomicBoolean(); private final FunctionAndTypeManager functionAndTypeManager; @Inject public FunctionPluginManager( PluginManagerConfig config, FunctionAndTypeManager functionAndTypeManager) { requireNonNull(config, "config is null"); requireNonNull(functionAndTypeManager, "functionAndTypeManager is null"); this.functionAndTypeManager = functionAndTypeManager; installedPluginsDir = config.getInstalledPluginsDir(); if (config.getPlugins() == null) { this.plugins = ImmutableList.of(); } else { this.plugins = ImmutableList.copyOf(config.getPlugins()); } this.resolver = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository()); } public void loadPlugins() throws Exception { if (!pluginsLoading.compareAndSet(false, true)) { return; } for (File file : listFiles( installedPluginsDir )) { if (file.isDirectory()) { loadPlugin(file.getAbsolutePath()); } } for (String plugin : plugins) { loadPlugin(plugin); } pluginsLoaded.set(true); } private void loadPlugin(String plugin) throws Exception { log.info("-- Loading plugin %s --", plugin); URLClassLoader pluginClassLoader = buildClassLoader(plugin); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(pluginClassLoader)) { loadPlugin(pluginClassLoader, Plugin.class); } log.info("-- Finished loading plugin %s --", plugin); } private void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); | java |
module loads classes with *some* classloader. // When the AfterBurner module is configured not to use the value classloader // (e.g., AfterBurner().setUseValueClassLoader(false)) AppClassLoader is used for loading those // classes. Otherwise, the PluginClassLoader is used, which is the default behavior. // Therefore, in the former case Afterburner won't be able to load the connector classes // as AppClassLoader doesn't see them, and in the latter case the PluginClassLoader won't be // able to load the AfterBurner classes themselves. So, our solution is to use the PluginClassLoader // and whitelist the AfterBurner classes here, so that the PluginClassLoader can load the // AfterBurner classes. private static final ImmutableList<String> SPI_PACKAGES = ImmutableList.<String>builder() .add("com.facebook.presto.spi.") .add("com.fasterxml.jackson.annotation.") .add("com.fasterxml.jackson.module.afterburner.") .add("io.airlift.slice.") .add("io.airlift.units.") .add("org.openjdk.jol.") .add("com.facebook.presto.common") .add("com.facebook.drift.annotations.") .add("com.facebook.drift.TException") .add("com.facebook.drift.TApplicationException") .build(); // TODO: Add plugins based on FunctionPlugin interface. Currently loading the plugins implemented on Plugin interface to the Function Server for now. private static final String PLUGIN_SERVICES_FILE = "META-INF/services/" + Plugin.class.getName(); private static final Logger log = Logger.get(FunctionPluginManager.class); private final ArtifactResolver resolver; private final File <mask> <mask> <mask> <mask> <mask> <mask> ; private final List<String> plugins; private final AtomicBoolean pluginsLoading = new AtomicBoolean(); private final AtomicBoolean pluginsLoaded = new AtomicBoolean(); private final FunctionAndTypeManager functionAndTypeManager; @Inject public FunctionPluginManager( PluginManagerConfig config, FunctionAndTypeManager functionAndTypeManager) { requireNonNull(config, "config is null"); requireNonNull(functionAndTypeManager, "functionAndTypeManager is null"); this.functionAndTypeManager = functionAndTypeManager; <mask> <mask> <mask> <mask> <mask> <mask> = config.getInstalledPluginsDir(); if (config.getPlugins() == null) { this.plugins = ImmutableList.of(); } else { this.plugins = ImmutableList.copyOf(config.getPlugins()); } this.resolver = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository()); } public void loadPlugins() throws Exception { if (!pluginsLoading.compareAndSet(false, true)) { return; } for (File file : listFiles( <mask> <mask> <mask> <mask> <mask> <mask> )) { if (file.isDirectory()) { loadPlugin(file.getAbsolutePath()); } } for (String plugin : plugins) { loadPlugin(plugin); } pluginsLoaded.set(true); } private void loadPlugin(String plugin) throws Exception { log.info("-- Loading plugin %s --", plugin); URLClassLoader pluginClassLoader = buildClassLoader(plugin); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(pluginClassLoader)) { loadPlugin(pluginClassLoader, Plugin.class); } log.info("-- Finished loading plugin %s --", plugin); } private void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = | module loads classes with *some* classloader. // When the AfterBurner module is configured not to use the value classloader // (e.g., AfterBurner().setUseValueClassLoader(false)) AppClassLoader is used for loading those // classes. Otherwise, the PluginClassLoader is used, which is the default behavior. // Therefore, in the former case Afterburner won't be able to load the connector classes // as AppClassLoader doesn't see them, and in the latter case the PluginClassLoader won't be // able to load the AfterBurner classes themselves. So, our solution is to use the PluginClassLoader // and whitelist the AfterBurner classes here, so that the PluginClassLoader can load the // AfterBurner classes. private static final ImmutableList<String> SPI_PACKAGES = ImmutableList.<String>builder() .add("com.facebook.presto.spi.") .add("com.fasterxml.jackson.annotation.") .add("com.fasterxml.jackson.module.afterburner.") .add("io.airlift.slice.") .add("io.airlift.units.") .add("org.openjdk.jol.") .add("com.facebook.presto.common") .add("com.facebook.drift.annotations.") .add("com.facebook.drift.TException") .add("com.facebook.drift.TApplicationException") .build(); // TODO: Add plugins based on FunctionPlugin interface. Currently loading the plugins implemented on Plugin interface to the Function Server for now. private static final String PLUGIN_SERVICES_FILE = "META-INF/services/" + Plugin.class.getName(); private static final Logger log = Logger.get(FunctionPluginManager.class); private final ArtifactResolver resolver; private final File installedPluginsDir ; private final List<String> plugins; private final AtomicBoolean pluginsLoading = new AtomicBoolean(); private final AtomicBoolean pluginsLoaded = new AtomicBoolean(); private final FunctionAndTypeManager functionAndTypeManager; @Inject public FunctionPluginManager( PluginManagerConfig config, FunctionAndTypeManager functionAndTypeManager) { requireNonNull(config, "config is null"); requireNonNull(functionAndTypeManager, "functionAndTypeManager is null"); this.functionAndTypeManager = functionAndTypeManager; installedPluginsDir = config.getInstalledPluginsDir(); if (config.getPlugins() == null) { this.plugins = ImmutableList.of(); } else { this.plugins = ImmutableList.copyOf(config.getPlugins()); } this.resolver = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository()); } public void loadPlugins() throws Exception { if (!pluginsLoading.compareAndSet(false, true)) { return; } for (File file : listFiles( installedPluginsDir )) { if (file.isDirectory()) { loadPlugin(file.getAbsolutePath()); } } for (String plugin : plugins) { loadPlugin(plugin); } pluginsLoaded.set(true); } private void loadPlugin(String plugin) throws Exception { log.info("-- Loading plugin %s --", plugin); URLClassLoader pluginClassLoader = buildClassLoader(plugin); try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(pluginClassLoader)) { loadPlugin(pluginClassLoader, Plugin.class); } log.info("-- Finished loading plugin %s --", plugin); } private void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = | java |
void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File <mask> <mask> <mask> <mask> <mask> <mask> ) { if ( <mask> <mask> <mask> <mask> <mask> <mask> != null && <mask> <mask> <mask> <mask> <mask> <mask> .isDirectory()) { File[] files = <mask> <mask> <mask> <mask> <mask> <mask> .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | void loadPlugin(URLClassLoader pluginClassLoader, Class<?> clazz) { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File installedPluginsDir ) { if ( installedPluginsDir != null && installedPluginsDir .isDirectory()) { File[] files = installedPluginsDir .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | java |
{ ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File <mask> <mask> <mask> <mask> <mask> <mask> ) { if ( <mask> <mask> <mask> <mask> <mask> <mask> != null && <mask> <mask> <mask> <mask> <mask> <mask> .isDirectory()) { File[] files = <mask> <mask> <mask> <mask> <mask> <mask> .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | { ServiceLoader<?> serviceLoader = ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File installedPluginsDir ) { if ( installedPluginsDir != null && installedPluginsDir .isDirectory()) { File[] files = installedPluginsDir .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | java |
ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File <mask> <mask> <mask> <mask> <mask> <mask> ) { if ( <mask> <mask> <mask> <mask> <mask> <mask> != null && <mask> <mask> <mask> <mask> <mask> <mask> .isDirectory()) { File[] files = <mask> <mask> <mask> <mask> <mask> <mask> .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | ServiceLoader.load(clazz, pluginClassLoader); List<?> plugins = ImmutableList.copyOf(serviceLoader); if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File installedPluginsDir ) { if ( installedPluginsDir != null && installedPluginsDir .isDirectory()) { File[] files = installedPluginsDir .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | java |
if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File <mask> <mask> <mask> <mask> <mask> <mask> ) { if ( <mask> <mask> <mask> <mask> <mask> <mask> != null && <mask> <mask> <mask> <mask> <mask> <mask> .isDirectory()) { File[] files = <mask> <mask> <mask> <mask> <mask> <mask> .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | if (plugins.isEmpty()) { log.warn("No service providers of type %s", clazz.getName()); } for (Object plugin : plugins) { log.info("Installing %s", plugin.getClass().getName()); if (plugin instanceof Plugin) { installPlugin((Plugin) plugin); } else { log.warn("Unknown plugin type: %s", plugin.getClass().getName()); } } } public void installPlugin(Plugin plugin) { for (Class<?> functionClass : plugin.getFunctions()) { log.info("Registering functions from %s", functionClass.getName()); functionAndTypeManager.registerBuiltInFunctions(extractFunctions(functionClass)); } } private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); } private URLClassLoader buildClassLoaderFromPom(File pomFile) throws Exception { List<Artifact> artifacts = resolver.resolvePom(pomFile); URLClassLoader classLoader = createClassLoader(artifacts, pomFile.getPath()); Artifact artifact = artifacts.get(0); processPlugins(artifact, classLoader, PLUGIN_SERVICES_FILE, CoordinatorPlugin.class.getName()); return classLoader; } private URLClassLoader buildClassLoaderFromDirectory(File dir) throws Exception { log.debug("Classpath for %s:", dir.getName()); List<URL> urls = new ArrayList<>(); for (File file : listFiles(dir)) { log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader buildClassLoaderFromCoordinates(String coordinates) throws Exception { Artifact rootArtifact = new DefaultArtifact(coordinates); List<Artifact> artifacts = resolver.resolveArtifacts(rootArtifact); return createClassLoader(artifacts, rootArtifact.toString()); } private URLClassLoader createClassLoader(List<Artifact> artifacts, String name) throws IOException { log.debug("Classpath for %s:", name); List<URL> urls = new ArrayList<>(); for (Artifact artifact : sortedArtifacts(artifacts)) { if (artifact.getFile() == null) { throw new RuntimeException("Could not resolve artifact: " + artifact); } File file = artifact.getFile().getCanonicalFile(); log.debug(" %s", file); urls.add(file.toURI().toURL()); } return createClassLoader(urls); } private URLClassLoader createClassLoader(List<URL> urls) { ClassLoader parent = getClass().getClassLoader(); return new PluginClassLoader(urls, parent, SPI_PACKAGES); } private static List<File> listFiles(File installedPluginsDir ) { if ( installedPluginsDir != null && installedPluginsDir .isDirectory()) { File[] files = installedPluginsDir .listFiles(); if (files != null) { Arrays.sort(files); return ImmutableList.copyOf(files); } } return ImmutableList.of(); } private static List<Artifact> sortedArtifacts(List<Artifact> artifacts) { List<Artifact> list = new ArrayList<>(artifacts); Collections.sort(list, Ordering.natural().nullsLast().onResultOf(Artifact::getFile)); return list; } private void processPlugins(Artifact artifact, ClassLoader classLoader, String servicesFile, String className) throws IOException { Set<String> plugins = discoverPlugins(artifact, classLoader, servicesFile, className); if (!plugins.isEmpty()) { writePluginServices(plugins, artifact.getFile(), servicesFile); } } } | java |
package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader; import com.github.binarywang.wxpay.bean.payscore.*; import com.github.binarywang.wxpay.exception. <mask> <mask> <mask> <mask> <mask> <mask> ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", | package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader; import com.github.binarywang.wxpay.bean.payscore.*; import com.github.binarywang.wxpay.exception. WxPayException ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", | java |
package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader; import com.github.binarywang.wxpay.bean.payscore.*; import com.github.binarywang.wxpay.exception. <mask> <mask> <mask> <mask> <mask> <mask> ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> | package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader; import com.github.binarywang.wxpay.bean.payscore.*; import com.github.binarywang.wxpay.exception. WxPayException ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> | java |
package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader; import com.github.binarywang.wxpay.bean.payscore.*; import com.github.binarywang.wxpay.exception. <mask> <mask> <mask> <mask> <mask> <mask> ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * | package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader; import com.github.binarywang.wxpay.bean.payscore.*; import com.github.binarywang.wxpay.exception. WxPayException ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * | java |
com.github.binarywang.wxpay.exception. <mask> <mask> <mask> <mask> <mask> <mask> ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String | com.github.binarywang.wxpay.exception. WxPayException ; import com.github.binarywang.wxpay.service.PartnerPayScoreService; import com.github.binarywang.wxpay.service.PartnerPayScoreSignPlanService; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.v3.util.AesUtils; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; /** * @author UltramanNoa * @className PartnerPayScoreSignPlanServiceImpl * @description 微信支付分签约计划接口实现 * @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String | java |
@createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> | @createTime 2023/11/3 09:23 * * <pre> * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">微信支付分签约计划</a> * <br> * 文档更新时间:2023.10.13 * <br> * 微信支付分签约计划是不同模式的支付分接口(随着国家大力推广教培行业先享后付政策,微信支付也紧跟政策于2023.07.25上线第一版签约计划接口以适用教培行业先享后付。于2023.10.13文档推至官网文档中心) * <br> * 免确认/需确认 用服务商创单接口 {@link PartnerPayScoreService} 需要用户授权 * <br> * 签约计划,用单独创单接口 {@link PartnerPayScoreSignPlanService} 不需要用户授权 * </pre> **/ @RequiredArgsConstructor public class PartnerPayScoreSignPlanServiceImpl implements PartnerPayScoreSignPlanService { private static final Gson GSON = new GsonBuilder().create(); private final WxPayService payService ; /** * <p>description:创建支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> | java |
* <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result | * <p>create Time: 2023/11/3 11:58 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/create-partner-pay-score-plan.html">创建支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult createPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 查询支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result | java |
* <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * | * <p>create Time: 2023/11/3 14:03 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/query-partner-pay-score-plan.html">查询支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult queryPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s", payService.getPayBaseUrl(), merchantPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * | java |
} } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} | } } /** * <p>description: 停止支付分计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:24 </p> * <p>version: v.1.0 </p> * * @param merchantPlanNo 路径参数:支付分计划商户侧单号 * @param subMchid 子商户号 * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} | java |
@return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return | @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-pay-score-plan/stop-partner-pay-score-plan.html">停止支付分计划</a> **/ @Override public WxPartnerPayScoreSignPlanResult stopPlans(@NonNull String merchantPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/plan/partner/payscore-plans/merchant-plan-no/%s/stop", payService.getPayBaseUrl(), merchantPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划详情对应的服务订单 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 14:53 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return | java |
{@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-service-order/create-partner-service-order.html">创建用户的签约计划详情对应的服务订单</a> **/ @Override public WxPartnerPayScoreSignPlanResult signPlanServiceOrder(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/serviceorder", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreSignPlanResult.fromJson(result); } /** * <p>description: 创建用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 17:48 </p> * <p>version: v.1.0 </p> * * @param request {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new WxPayException ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | java |
{@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | {@link WxPartnerPayScoreSignPlanRequest} * * @return {@link WxPartnerPayScoreUserSignPlanResult} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/create-partner-user-sign-plan.html">创建用户的签约计划</a> **/ @Override public WxPartnerPayScoreUserSignPlanResult createUserSignPlans(WxPartnerPayScoreSignPlanRequest request) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans", payService.getPayBaseUrl()); if (StringUtils.isBlank(request.getAppid())) { request.setAppid(payService.getConfig().getAppId()); } if (StringUtils.isBlank((request.getServiceId()))) { request.setServiceId(payService.getConfig().getServiceId()); } String result = payService.postV3(url, request.toJson()); return WxPartnerPayScoreUserSignPlanResult.fromJson(result); } /** * <p>description: 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new WxPayException ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | java |
查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | 查询用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new WxPayException ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | java |
</p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 * @param subMchid 子商户号 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/query-partner-user-sign-plan.html">查询用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity queryUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s", payService.getPayBaseUrl(), merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new WxPayException ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | java |
merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | merchantSignPlanNo); try { URI uri = new URIBuilder(url) .setParameter("sub_mchid", subMchid) .build(); String result = payService.getV3(uri.toString()); return PartnerUserSignPlanEntity.fromJson(result); } catch (URISyntaxException e) { throw new WxPayException ("未知异常!", e); } } /** * <p>description: 取消用户的签约计划 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new WxPayException ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | java |
<p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws <mask> <mask> <mask> <mask> <mask> <mask> { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws <mask> <mask> <mask> <mask> <mask> <mask> { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws <mask> <mask> <mask> <mask> <mask> <mask> { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new <mask> <mask> <mask> <mask> <mask> <mask> ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | <p>create Time: 2023/11/3 18:01 </p> * <p>version: v.1.0 </p> * * @param merchantSignPlanNo 路径参数 商户签约计划号 subMchid – 子商户号 * @param subMchid 子商户号 * @param stopReason 停止签约计划原因 * * @return {@link PartnerUserSignPlanEntity} * @apiNote <a href="https://pay.weixin.qq.com/docs/partner/apis/partner-payscore-plan/partner-user-sign-plan/stop-partner-user-sign-plan.html">取消用户的签约计划</a> **/ @Override public PartnerUserSignPlanEntity stopUserSignPlans(@NonNull String merchantSignPlanNo, @NonNull String subMchid, @NonNull String stopReason) throws WxPayException { String url = String.format("%s/v3/payscore/sign-plan/partner/user-sign-plans/merchant-sign-plan-no/%s/stop", payService.getPayBaseUrl(), merchantSignPlanNo); Map<String, String> params = Maps.newHashMap(); params.put("sub_mchid", subMchid); params.put("stop_reason", stopReason); String result = payService.postV3(url, WxGsonBuilder.create().toJson(params)); return PartnerUserSignPlanEntity.fromJson(result); } /** * <p>description:回调通知 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:28 </p> * <p>version: v.1.0 </p> * * @param notifyData 回调参数 * @param header 签名 * * @return {@link PartnerUserSignPlanEntity} **/ @Override public PartnerUserSignPlanEntity parseSignPlanNotifyResult(String notifyData, SignatureHeader header) throws WxPayException { PayScoreNotifyData response = parseNotifyData(notifyData, header); return decryptNotifyDataResource(response); } /** * <p>description: 检验并解析通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:30 </p> * <p>version: v.1.0 </p> * @param data * @param header * @return {@link PayScoreNotifyData} **/ public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException { if (Objects.nonNull(header) && !verifyNotifySign(header, data)) { throw new WxPayException ("非法请求,头部信息验证失败"); } return GSON.fromJson(data, PayScoreNotifyData.class); } /** * <p>description: 解析回调通知参数 </p> * <p>author:UltramanNoa </p> * <p>create Time: 2023/11/3 18:27 </p> * <p>version: v.1.0 </p> * * @param data {@link PayScoreNotifyData} * * @return {@link PartnerUserSignPlanEntity} **/ public PartnerUserSignPlanEntity decryptNotifyDataResource(PayScoreNotifyData data) throws WxPayException { PayScoreNotifyData.Resource resource = data.getResource(); String cipherText = resource.getCipherText(); String associatedData = resource.getAssociatedData(); String nonce = resource.getNonce(); String apiV3Key = payService.getConfig().getApiV3Key(); try { return PartnerUserSignPlanEntity.fromJson(AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key)); } catch (GeneralSecurityException | IOException e) { throw new WxPayException ("解析报文异常!", e); } } /** * 校验通知签名 * * @param header 通知头信息 * @param data 通知数据 * * @return true:校验通过 false:校验不通过 */ private boolean verifyNotifySign(SignatureHeader header, String data) { String beforeSign = String.format("%s\n%s\n%s\n", header.getTimeStamp(), header.getNonce(), data); return this.payService.getConfig().getVerifier().verify( header.getSerialNo(), beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned() ); } } | java |
/* * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.Insets; import java.awt.Toolkit; import java.awt.Window; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref. <mask> <mask> <mask> <mask> ; import java.lang.ref.WeakReference; import javax.swing.ButtonModel; import javax.swing.DefaultButtonModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JRootPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.LayoutStyle; import javax.swing.LookAndFeel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicLookAndFeel; import javax.swing.text.DefaultEditorKit; import sun.awt.AppContext; import sun.awt.OSInfo; import sun.awt.SunToolkit; import sun.swing.DefaultLayoutStyle; import sun.swing.SwingAccessor; import sun.swing.SwingUtilities2; import static javax.swing.UIDefaults.LazyValue; /** * The Java Look and Feel, otherwise known as Metal. * <p> * Each of the {@code ComponentUI}s provided by {@code * MetalLookAndFeel} derives its behavior from the defaults * table. Unless otherwise noted each of the {@code ComponentUI} * implementations in this package document the set of defaults they * use. Unless otherwise noted the defaults are installed at the time * {@code installUI} is invoked, and follow the recommendations * outlined in {@code LookAndFeel} for installing defaults. * <p> * {@code MetalLookAndFeel} derives it's color palette and fonts from * {@code MetalTheme}. The default theme is {@code OceanTheme}. The theme * can be changed using the {@code setCurrentTheme} method, refer to it * for details on changing the theme. Prior to 1.5 the default * theme was {@code DefaultMetalTheme}. The system property * {@code "swing.metalTheme"} can be set to {@code "steel"} to indicate * the default should be {@code DefaultMetalTheme}. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between | /* * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.Insets; import java.awt.Toolkit; import java.awt.Window; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref. ReferenceQueue ; import java.lang.ref.WeakReference; import javax.swing.ButtonModel; import javax.swing.DefaultButtonModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JRootPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.LayoutStyle; import javax.swing.LookAndFeel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicLookAndFeel; import javax.swing.text.DefaultEditorKit; import sun.awt.AppContext; import sun.awt.OSInfo; import sun.awt.SunToolkit; import sun.swing.DefaultLayoutStyle; import sun.swing.SwingAccessor; import sun.swing.SwingUtilities2; import static javax.swing.UIDefaults.LazyValue; /** * The Java Look and Feel, otherwise known as Metal. * <p> * Each of the {@code ComponentUI}s provided by {@code * MetalLookAndFeel} derives its behavior from the defaults * table. Unless otherwise noted each of the {@code ComponentUI} * implementations in this package document the set of defaults they * use. Unless otherwise noted the defaults are installed at the time * {@code installUI} is invoked, and follow the recommendations * outlined in {@code LookAndFeel} for installing defaults. * <p> * {@code MetalLookAndFeel} derives it's color palette and fonts from * {@code MetalTheme}. The default theme is {@code OceanTheme}. The theme * can be changed using the {@code setCurrentTheme} method, refer to it * for details on changing the theme. Prior to 1.5 the default * theme was {@code DefaultMetalTheme}. The system property * {@code "swing.metalTheme"} can be set to {@code "steel"} to indicate * the default should be {@code DefaultMetalTheme}. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between | java |
the separator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getSeparatorForeground()}. * * @return the separator foreground color * * @see MetalTheme */ public static ColorUIResource getSeparatorForeground() { return getCurrentTheme().getSeparatorForeground(); } /** * Returns the accelerator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getAcceleratorForeground()}. * * @return the separator accelerator foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorForeground() { return getCurrentTheme().getAcceleratorForeground(); } /** * Returns the accelerator selected foreground color of the * current theme. This is a cover method for {@code * getCurrentTheme().getAcceleratorSelectedForeground()}. * * @return the accelerator selected foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorSelectedForeground() { return getCurrentTheme().getAcceleratorSelectedForeground(); } /** * Returns a {@code LayoutStyle} implementing the Java look and feel * design guidelines. * * @return LayoutStyle implementing the Java look and feel design * guidelines * @since 1.6 */ public LayoutStyle getLayoutStyle() { return MetalLayoutStyle.INSTANCE; } /** * FontActiveValue redirects to the appropriate metal theme method. */ private static class FontActiveValue implements UIDefaults.ActiveValue { private int type; private MetalTheme theme; FontActiveValue(MetalTheme theme, int type) { this.theme = theme; this.type = type; } public Object createValue(UIDefaults table) { Object value = null; switch (type) { case MetalTheme.CONTROL_TEXT_FONT: value = theme.getControlTextFont(); break; case MetalTheme.SYSTEM_TEXT_FONT: value = theme.getSystemTextFont(); break; case MetalTheme.USER_TEXT_FONT: value = theme.getUserTextFont(); break; case MetalTheme.MENU_TEXT_FONT: value = theme.getMenuTextFont(); break; case MetalTheme.WINDOW_TITLE_FONT: value = theme.getWindowTitleFont(); break; case MetalTheme.SUB_TEXT_FONT: value = theme.getSubTextFont(); break; } return value; } } static <mask> <mask> <mask> <mask> <LookAndFeel> queue = new <mask> <mask> <mask> <mask> <LookAndFeel>(); static void flushUnreferenced() { AATextListener aatl; while ((aatl = (AATextListener)queue.poll()) != null) { aatl.dispose(); } } static class AATextListener extends WeakReference<LookAndFeel> implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; AATextListener(LookAndFeel laf) { super(laf, queue); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addPropertyChangeListener(key, this); } public void propertyChange(PropertyChangeEvent pce) { LookAndFeel laf = get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; } UIDefaults defaults = UIManager.getLookAndFeelDefaults(); boolean lafCond = SwingUtilities2.isLocalDisplay(); SwingUtilities2.putAATextInfo(lafCond, defaults); updateUI(); } void dispose() { Toolkit tk = Toolkit.getDefaultToolkit(); tk.removePropertyChangeListener(key, this); } /** * Updates the UI of the passed in window and all its children. */ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window[] ownedWins = window.getOwnedWindows(); for (Window w : ownedWins) { updateWindowUI(w); } } /** * Updates the UIs of all the known Frames. */ private static void updateAllUIs() { Frame[] appFrames = Frame.getFrames(); for (Frame frame : appFrames) { updateWindowUI(frame); } } /** * Indicates if an updateUI call is pending. */ private static boolean updatePending; /** * Sets whether or not an updateUI call is pending. */ private static synchronized void setUpdatePending(boolean update) { updatePending = update; } /** * Returns true if a UI update is pending. */ private static synchronized boolean isUpdatePending() { return updatePending; } protected void updateUI() { if (!isUpdatePending()) { setUpdatePending(true); Runnable uiUpdater = new Runnable() { public void run() { updateAllUIs(); setUpdatePending(false); } }; SwingUtilities.invokeLater(uiUpdater); } } } // From the JLF Design Guidelines: // http://www.oracle.com/technetwork/java/jlf-135985.html @SuppressWarnings("fallthrough") private static class MetalLayoutStyle | the separator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getSeparatorForeground()}. * * @return the separator foreground color * * @see MetalTheme */ public static ColorUIResource getSeparatorForeground() { return getCurrentTheme().getSeparatorForeground(); } /** * Returns the accelerator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getAcceleratorForeground()}. * * @return the separator accelerator foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorForeground() { return getCurrentTheme().getAcceleratorForeground(); } /** * Returns the accelerator selected foreground color of the * current theme. This is a cover method for {@code * getCurrentTheme().getAcceleratorSelectedForeground()}. * * @return the accelerator selected foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorSelectedForeground() { return getCurrentTheme().getAcceleratorSelectedForeground(); } /** * Returns a {@code LayoutStyle} implementing the Java look and feel * design guidelines. * * @return LayoutStyle implementing the Java look and feel design * guidelines * @since 1.6 */ public LayoutStyle getLayoutStyle() { return MetalLayoutStyle.INSTANCE; } /** * FontActiveValue redirects to the appropriate metal theme method. */ private static class FontActiveValue implements UIDefaults.ActiveValue { private int type; private MetalTheme theme; FontActiveValue(MetalTheme theme, int type) { this.theme = theme; this.type = type; } public Object createValue(UIDefaults table) { Object value = null; switch (type) { case MetalTheme.CONTROL_TEXT_FONT: value = theme.getControlTextFont(); break; case MetalTheme.SYSTEM_TEXT_FONT: value = theme.getSystemTextFont(); break; case MetalTheme.USER_TEXT_FONT: value = theme.getUserTextFont(); break; case MetalTheme.MENU_TEXT_FONT: value = theme.getMenuTextFont(); break; case MetalTheme.WINDOW_TITLE_FONT: value = theme.getWindowTitleFont(); break; case MetalTheme.SUB_TEXT_FONT: value = theme.getSubTextFont(); break; } return value; } } static ReferenceQueue <LookAndFeel> queue = new ReferenceQueue <LookAndFeel>(); static void flushUnreferenced() { AATextListener aatl; while ((aatl = (AATextListener)queue.poll()) != null) { aatl.dispose(); } } static class AATextListener extends WeakReference<LookAndFeel> implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; AATextListener(LookAndFeel laf) { super(laf, queue); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addPropertyChangeListener(key, this); } public void propertyChange(PropertyChangeEvent pce) { LookAndFeel laf = get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; } UIDefaults defaults = UIManager.getLookAndFeelDefaults(); boolean lafCond = SwingUtilities2.isLocalDisplay(); SwingUtilities2.putAATextInfo(lafCond, defaults); updateUI(); } void dispose() { Toolkit tk = Toolkit.getDefaultToolkit(); tk.removePropertyChangeListener(key, this); } /** * Updates the UI of the passed in window and all its children. */ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window[] ownedWins = window.getOwnedWindows(); for (Window w : ownedWins) { updateWindowUI(w); } } /** * Updates the UIs of all the known Frames. */ private static void updateAllUIs() { Frame[] appFrames = Frame.getFrames(); for (Frame frame : appFrames) { updateWindowUI(frame); } } /** * Indicates if an updateUI call is pending. */ private static boolean updatePending; /** * Sets whether or not an updateUI call is pending. */ private static synchronized void setUpdatePending(boolean update) { updatePending = update; } /** * Returns true if a UI update is pending. */ private static synchronized boolean isUpdatePending() { return updatePending; } protected void updateUI() { if (!isUpdatePending()) { setUpdatePending(true); Runnable uiUpdater = new Runnable() { public void run() { updateAllUIs(); setUpdatePending(false); } }; SwingUtilities.invokeLater(uiUpdater); } } } // From the JLF Design Guidelines: // http://www.oracle.com/technetwork/java/jlf-135985.html @SuppressWarnings("fallthrough") private static class MetalLayoutStyle | java |
the current theme. This is * a cover method for {@code getCurrentTheme().getSeparatorForeground()}. * * @return the separator foreground color * * @see MetalTheme */ public static ColorUIResource getSeparatorForeground() { return getCurrentTheme().getSeparatorForeground(); } /** * Returns the accelerator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getAcceleratorForeground()}. * * @return the separator accelerator foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorForeground() { return getCurrentTheme().getAcceleratorForeground(); } /** * Returns the accelerator selected foreground color of the * current theme. This is a cover method for {@code * getCurrentTheme().getAcceleratorSelectedForeground()}. * * @return the accelerator selected foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorSelectedForeground() { return getCurrentTheme().getAcceleratorSelectedForeground(); } /** * Returns a {@code LayoutStyle} implementing the Java look and feel * design guidelines. * * @return LayoutStyle implementing the Java look and feel design * guidelines * @since 1.6 */ public LayoutStyle getLayoutStyle() { return MetalLayoutStyle.INSTANCE; } /** * FontActiveValue redirects to the appropriate metal theme method. */ private static class FontActiveValue implements UIDefaults.ActiveValue { private int type; private MetalTheme theme; FontActiveValue(MetalTheme theme, int type) { this.theme = theme; this.type = type; } public Object createValue(UIDefaults table) { Object value = null; switch (type) { case MetalTheme.CONTROL_TEXT_FONT: value = theme.getControlTextFont(); break; case MetalTheme.SYSTEM_TEXT_FONT: value = theme.getSystemTextFont(); break; case MetalTheme.USER_TEXT_FONT: value = theme.getUserTextFont(); break; case MetalTheme.MENU_TEXT_FONT: value = theme.getMenuTextFont(); break; case MetalTheme.WINDOW_TITLE_FONT: value = theme.getWindowTitleFont(); break; case MetalTheme.SUB_TEXT_FONT: value = theme.getSubTextFont(); break; } return value; } } static <mask> <mask> <mask> <mask> <LookAndFeel> queue = new <mask> <mask> <mask> <mask> <LookAndFeel>(); static void flushUnreferenced() { AATextListener aatl; while ((aatl = (AATextListener)queue.poll()) != null) { aatl.dispose(); } } static class AATextListener extends WeakReference<LookAndFeel> implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; AATextListener(LookAndFeel laf) { super(laf, queue); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addPropertyChangeListener(key, this); } public void propertyChange(PropertyChangeEvent pce) { LookAndFeel laf = get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; } UIDefaults defaults = UIManager.getLookAndFeelDefaults(); boolean lafCond = SwingUtilities2.isLocalDisplay(); SwingUtilities2.putAATextInfo(lafCond, defaults); updateUI(); } void dispose() { Toolkit tk = Toolkit.getDefaultToolkit(); tk.removePropertyChangeListener(key, this); } /** * Updates the UI of the passed in window and all its children. */ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window[] ownedWins = window.getOwnedWindows(); for (Window w : ownedWins) { updateWindowUI(w); } } /** * Updates the UIs of all the known Frames. */ private static void updateAllUIs() { Frame[] appFrames = Frame.getFrames(); for (Frame frame : appFrames) { updateWindowUI(frame); } } /** * Indicates if an updateUI call is pending. */ private static boolean updatePending; /** * Sets whether or not an updateUI call is pending. */ private static synchronized void setUpdatePending(boolean update) { updatePending = update; } /** * Returns true if a UI update is pending. */ private static synchronized boolean isUpdatePending() { return updatePending; } protected void updateUI() { if (!isUpdatePending()) { setUpdatePending(true); Runnable uiUpdater = new Runnable() { public void run() { updateAllUIs(); setUpdatePending(false); } }; SwingUtilities.invokeLater(uiUpdater); } } } // From the JLF Design Guidelines: // http://www.oracle.com/technetwork/java/jlf-135985.html @SuppressWarnings("fallthrough") private static class MetalLayoutStyle extends DefaultLayoutStyle { private static | the current theme. This is * a cover method for {@code getCurrentTheme().getSeparatorForeground()}. * * @return the separator foreground color * * @see MetalTheme */ public static ColorUIResource getSeparatorForeground() { return getCurrentTheme().getSeparatorForeground(); } /** * Returns the accelerator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getAcceleratorForeground()}. * * @return the separator accelerator foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorForeground() { return getCurrentTheme().getAcceleratorForeground(); } /** * Returns the accelerator selected foreground color of the * current theme. This is a cover method for {@code * getCurrentTheme().getAcceleratorSelectedForeground()}. * * @return the accelerator selected foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorSelectedForeground() { return getCurrentTheme().getAcceleratorSelectedForeground(); } /** * Returns a {@code LayoutStyle} implementing the Java look and feel * design guidelines. * * @return LayoutStyle implementing the Java look and feel design * guidelines * @since 1.6 */ public LayoutStyle getLayoutStyle() { return MetalLayoutStyle.INSTANCE; } /** * FontActiveValue redirects to the appropriate metal theme method. */ private static class FontActiveValue implements UIDefaults.ActiveValue { private int type; private MetalTheme theme; FontActiveValue(MetalTheme theme, int type) { this.theme = theme; this.type = type; } public Object createValue(UIDefaults table) { Object value = null; switch (type) { case MetalTheme.CONTROL_TEXT_FONT: value = theme.getControlTextFont(); break; case MetalTheme.SYSTEM_TEXT_FONT: value = theme.getSystemTextFont(); break; case MetalTheme.USER_TEXT_FONT: value = theme.getUserTextFont(); break; case MetalTheme.MENU_TEXT_FONT: value = theme.getMenuTextFont(); break; case MetalTheme.WINDOW_TITLE_FONT: value = theme.getWindowTitleFont(); break; case MetalTheme.SUB_TEXT_FONT: value = theme.getSubTextFont(); break; } return value; } } static ReferenceQueue <LookAndFeel> queue = new ReferenceQueue <LookAndFeel>(); static void flushUnreferenced() { AATextListener aatl; while ((aatl = (AATextListener)queue.poll()) != null) { aatl.dispose(); } } static class AATextListener extends WeakReference<LookAndFeel> implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; AATextListener(LookAndFeel laf) { super(laf, queue); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addPropertyChangeListener(key, this); } public void propertyChange(PropertyChangeEvent pce) { LookAndFeel laf = get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; } UIDefaults defaults = UIManager.getLookAndFeelDefaults(); boolean lafCond = SwingUtilities2.isLocalDisplay(); SwingUtilities2.putAATextInfo(lafCond, defaults); updateUI(); } void dispose() { Toolkit tk = Toolkit.getDefaultToolkit(); tk.removePropertyChangeListener(key, this); } /** * Updates the UI of the passed in window and all its children. */ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window[] ownedWins = window.getOwnedWindows(); for (Window w : ownedWins) { updateWindowUI(w); } } /** * Updates the UIs of all the known Frames. */ private static void updateAllUIs() { Frame[] appFrames = Frame.getFrames(); for (Frame frame : appFrames) { updateWindowUI(frame); } } /** * Indicates if an updateUI call is pending. */ private static boolean updatePending; /** * Sets whether or not an updateUI call is pending. */ private static synchronized void setUpdatePending(boolean update) { updatePending = update; } /** * Returns true if a UI update is pending. */ private static synchronized boolean isUpdatePending() { return updatePending; } protected void updateUI() { if (!isUpdatePending()) { setUpdatePending(true); Runnable uiUpdater = new Runnable() { public void run() { updateAllUIs(); setUpdatePending(false); } }; SwingUtilities.invokeLater(uiUpdater); } } } // From the JLF Design Guidelines: // http://www.oracle.com/technetwork/java/jlf-135985.html @SuppressWarnings("fallthrough") private static class MetalLayoutStyle extends DefaultLayoutStyle { private static | java |
/* * 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.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. <mask> <mask> <mask> <mask> ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find | /* * 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.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. OptionalInt ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find | java |
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.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. <mask> <mask> <mask> <mask> ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new | 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.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. OptionalInt ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new | java |
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.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. <mask> <mask> <mask> <mask> ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), | 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.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. OptionalInt ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), | java |
or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. <mask> <mask> <mask> <mask> ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply | or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. OptionalInt ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply | java |
the License. */ package org.apache.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. <mask> <mask> <mask> <mask> ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void | the License. */ package org.apache.kafka.metadata.storage; import org.apache.kafka.common.metadata.UserScramCredentialRecord; import org.apache.kafka.common.security.scram.internals.ScramFormatter; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.metadata.storage.ScramParser.PerMechanismData; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.AbstractMap; import java.util.Optional; import java.util. OptionalInt ; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @Timeout(value = 40) public class ScramParserTest { static final byte[] TEST_SALT = new byte[] { 49, 108, 118, 52, 112, 100, 110, 119, 52, 102, 119, 113, 55, 110, 111, 116, 99, 120, 109, 48, 121, 121, 49, 107, 55, 113 }; static final byte[] TEST_SALTED_PASSWORD = new byte[] { -103, 61, 50, -55, 69, 49, -98, 82, 90, 11, -33, 71, 94, 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void | java |
4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | 4, 83, 73, -119, 91, -70, -90, -72, 21, 33, -83, 36, 34, 95, 76, -53, -29, 96, 33 }; @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=foo")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedFoo() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", "foo"), ScramParser.splitTrimmedConfigStringComponent("name=\"foo\"")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=")); } @Test public void testSplitTrimmedConfigStringComponentOnNameEqualsQuotedEmpty() { assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""), ScramParser.splitTrimmedConfigStringComponent("name=\"\"")); } @Test public void testSplitTrimmedConfigStringComponentWithNoEquals() { assertEquals("No equals sign found in SCRAM component: name", assertThrows(FormatterException.class, () -> ScramParser.splitTrimmedConfigStringComponent("name")).getMessage()); } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | java |
} @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | } @Test public void testRandomSalt() throws Exception { PerMechanismData data = new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | java |
Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | Optional.empty()); TestUtils.retryOnExceptionWithTimeout(10_000, () -> assertNotEquals(data.salt().toString(), data.salt().toString()) ); } @Test public void testConfiguredSalt() throws Exception { assertArrayEquals(TEST_SALT, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | java |
Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).salt()); } @Test public void testDefaultIterations() { assertEquals(4096, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testConfiguredIterations() { assertEquals(8192, new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()).iterations()); } @Test public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | java |
public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | public void testParsePerMechanismArgument() { assertEquals(new AbstractMap.SimpleImmutableEntry<>( ScramMechanism.SCRAM_SHA_512, "name=scram-admin,password=scram-user-secret"), ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512=[name=scram-admin,password=scram-user-secret]")); } @Test public void testParsePerMechanismArgumentWithoutEqualsSign() { assertEquals("Failed to find equals sign in SCRAM argument 'SCRAM-SHA-512'", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-512")).getMessage()); } @Test public void testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | java |
testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), <mask> <mask> <mask> <mask> .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | testParsePerMechanismArgumentWithUnsupportedScramMethod() { assertEquals("The add-scram mechanism SCRAM-SHA-UNSUPPORTED is not supported.", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-UNSUPPORTED=[name=scram-admin,password=scram-user-secret]")). getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutBraces() { assertEquals("Expected configuration string to start with [", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,password=scram-user-secret")).getMessage()); } @Test public void testParsePerMechanismData() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .empty(), Optional.of("mypass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass")); } @Test public void testParsePerMechanismDataFailsWithoutName() { assertEquals("You must supply 'name' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "password=mypass")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithoutPassword() { assertEquals("You must supply one of 'password' or 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bar")). getMessage()); } @Test public void testParsePerMechanismDataFailsWithExtraArguments() { assertEquals("Unknown SCRAM configurations: unknown, unknown2", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=mypass,unknown=something,unknown2=somethingelse")). getMessage()); } @Test public void testParsePerMechanismDataWithIterations() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.empty(), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192")); } @Test public void testParsePerMechanismDataWithConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "bob", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "name=bob,password=my pass,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithIterationsAndConfiguredSalt() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "bob", Optional.of(TEST_SALT), OptionalInt .of(8192), Optional.of("my pass"), Optional.empty()), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=bob,password=my pass,iterations=8192,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"")); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPasswordFailsWithoutSalt() { assertEquals("You must supply 'salt' with 'saltedpassword' to add-scram", assertThrows(FormatterException.class, () -> new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")). getMessage()); } @Test public void testParsePerMechanismDataWithConfiguredSaltedPassword() { assertEquals(new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)), new PerMechanismData(ScramMechanism.SCRAM_SHA_256, "name=alice,salt=\"MWx2NHBkbnc0ZndxN25vdGN4bTB5eTFrN3E=\"," + "saltedpassword=\"mT0yyUUxnlJaC99HXgRTSYlbuqa4FSGtJCJfTMvjYCE=\"")); } @Test public void testPerMechanismDataToRecord() throws Exception { ScramFormatter formatter = new ScramFormatter(ScramMechanism.SCRAM_SHA_512); assertEquals(new UserScramCredentialRecord(). setName("alice"). setMechanism(ScramMechanism.SCRAM_SHA_512.type()). setSalt(TEST_SALT). setStoredKey(formatter.storedKey(formatter.clientKey(TEST_SALTED_PASSWORD))). setServerKey(formatter.serverKey(TEST_SALTED_PASSWORD)). setIterations(4096), new PerMechanismData(ScramMechanism.SCRAM_SHA_512, "alice", Optional.of(TEST_SALT), OptionalInt .empty(), Optional.empty(), Optional.of(TEST_SALTED_PASSWORD)).toRecord()); } } | java |
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( <mask> <mask> <mask> , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( <mask> <mask> <mask> , options))); } } | /* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor monitor , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( monitor , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor monitor , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( monitor , options))); } } | java |
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( <mask> <mask> <mask> , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( <mask> <mask> <mask> , options))); } } | /* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor monitor , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( monitor , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor monitor , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( monitor , options))); } } | java |
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( <mask> <mask> <mask> , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( <mask> <mask> <mask> , options))); } } | /* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor monitor , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( monitor , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor monitor , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( monitor , options))); } } | java |
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( <mask> <mask> <mask> , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor <mask> <mask> <mask> , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( <mask> <mask> <mask> , options))); } } | /* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed 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.jkiss.dbeaver.ext.duckdb.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ext.duckdb.model.DuckDBSequence; import org.jkiss.dbeaver.ext.generic.edit.GenericSequenceManager; import org.jkiss.dbeaver.ext.generic.model.GenericSequence; import org.jkiss.dbeaver.ext.generic.model.GenericStructContainer; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.util.List; import java.util.Locale; import java.util.Map; public class DuckDBSequenceManager extends GenericSequenceManager { @Override public boolean canCreateObject(@NotNull Object container) { // TODO: We need to add treeInjection in the plugin.xml to work with this //return DBWorkbench.getPlatform().getWorkspace().hasRealmPermission(RMConstants.PERMISSION_METADATA_EDITOR); return false; } @Override protected GenericSequence createDatabaseObject( @NotNull DBRProgressMonitor monitor , @NotNull DBECommandContext context, Object container, Object copyFrom, @NotNull Map<String, Object> options ) { GenericStructContainer structContainer = (GenericStructContainer) container; DuckDBSequence sequence = new DuckDBSequence(structContainer, getBaseObjectName().toLowerCase(Locale.ROOT)); setNewObjectName( monitor , structContainer, sequence); return sequence; } @Override protected void addObjectCreateActions( @NotNull DBRProgressMonitor monitor , @NotNull DBCExecutionContext executionContext, @NotNull List<DBEPersistAction> actions, @NotNull SQLObjectEditor<GenericSequence, GenericStructContainer>.ObjectCreateCommand command, @NotNull Map<String, Object> options ) { DuckDBSequence sequence = (DuckDBSequence) command.getObject(); actions.add(new SQLDatabasePersistAction("Create sequence", sequence.getObjectDefinitionText( monitor , options))); } } | java |
jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.Servlet; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.jspecify.annotations.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Mock implementation of the {@link jakarta.servlet.FilterChain} interface. * * <p>A {@code MockFilterChain} can be configured with one or more filters and a * Servlet to invoke. The first time the chain is called, it invokes all filters * and the Servlet, and saves the request and response. Subsequent invocations * raise an {@link IllegalStateException} unless {@link #reset()} is called. * * @author Juergen Hoeller * @author Rob Winch * @author Rossen Stoyanchev * @since 2.0.3 * @see MockFilterConfig * @see PassThroughFilterChain */ public class MockFilterChain implements FilterChain { private @Nullable ServletRequest request; private @Nullable ServletResponse response; private final List<Filter> filters; private @Nullable Iterator<Filter> iterator; /** * Create an empty {@code MockFilterChain} without any {@linkplain Filter filters}. */ public MockFilterChain() { this.filters = Collections.emptyList(); } /** * Create a {@code MockFilterChain} with a {@link Servlet}. * @param servlet the {@code Servlet} to invoke * @since 3.2 */ public MockFilterChain(Servlet servlet) { this.filters = initFilterList(servlet); } /** * Create a {@code MockFilterChain} with a {@link Servlet} and {@linkplain Filter * filters}. * @param servlet the {@code Servlet} to invoke in this {@code MockFilterChain} * @param filters the filters to invoke in this {@code MockFilterChain} * @since 3.2 */ public MockFilterChain(Servlet servlet, Filter... filters) { Assert.notNull(filters, "filters cannot be null"); Assert.noNullElements(filters, "filters cannot contain null values"); this.filters = initFilterList(servlet, filters); } private static List<Filter> initFilterList(Servlet servlet, Filter... filters) { Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new <mask> <mask> <mask> <mask> <mask> <mask> (servlet)); return List.of(allFilters); } /** * Return the request that {@link #doFilter} has been called with. */ public @Nullable ServletRequest getRequest() { return this.request; } /** * Return the response that {@link #doFilter} has been called with. */ public @Nullable ServletResponse getResponse() { return this.response; } /** * Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving the * request and response. */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(this.request == null, "This FilterChain has already been called!"); if (this.iterator == null) { this.iterator = this.filters.iterator(); } if (this.iterator.hasNext()) { Filter nextFilter = this.iterator.next(); nextFilter.doFilter(request, response, this); } this.request = request; this.response = response; } /** * Reset this {@code MockFilterChain} allowing it to be invoked again. */ public void reset() { this.request = null; this.response = null; this.iterator = null; } /** * A filter that simply delegates to a Servlet. */ private static final class <mask> <mask> <mask> <mask> <mask> <mask> implements Filter { private final Servlet delegateServlet; private <mask> <mask> <mask> <mask> <mask> <mask> (Servlet servlet) { Assert.notNull(servlet, "servlet cannot be null"); this.delegateServlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegateServlet.service(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public String toString() { return this.delegateServlet.toString(); } } } | jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.Servlet; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.jspecify.annotations.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Mock implementation of the {@link jakarta.servlet.FilterChain} interface. * * <p>A {@code MockFilterChain} can be configured with one or more filters and a * Servlet to invoke. The first time the chain is called, it invokes all filters * and the Servlet, and saves the request and response. Subsequent invocations * raise an {@link IllegalStateException} unless {@link #reset()} is called. * * @author Juergen Hoeller * @author Rob Winch * @author Rossen Stoyanchev * @since 2.0.3 * @see MockFilterConfig * @see PassThroughFilterChain */ public class MockFilterChain implements FilterChain { private @Nullable ServletRequest request; private @Nullable ServletResponse response; private final List<Filter> filters; private @Nullable Iterator<Filter> iterator; /** * Create an empty {@code MockFilterChain} without any {@linkplain Filter filters}. */ public MockFilterChain() { this.filters = Collections.emptyList(); } /** * Create a {@code MockFilterChain} with a {@link Servlet}. * @param servlet the {@code Servlet} to invoke * @since 3.2 */ public MockFilterChain(Servlet servlet) { this.filters = initFilterList(servlet); } /** * Create a {@code MockFilterChain} with a {@link Servlet} and {@linkplain Filter * filters}. * @param servlet the {@code Servlet} to invoke in this {@code MockFilterChain} * @param filters the filters to invoke in this {@code MockFilterChain} * @since 3.2 */ public MockFilterChain(Servlet servlet, Filter... filters) { Assert.notNull(filters, "filters cannot be null"); Assert.noNullElements(filters, "filters cannot contain null values"); this.filters = initFilterList(servlet, filters); } private static List<Filter> initFilterList(Servlet servlet, Filter... filters) { Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new ServletFilterProxy (servlet)); return List.of(allFilters); } /** * Return the request that {@link #doFilter} has been called with. */ public @Nullable ServletRequest getRequest() { return this.request; } /** * Return the response that {@link #doFilter} has been called with. */ public @Nullable ServletResponse getResponse() { return this.response; } /** * Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving the * request and response. */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(this.request == null, "This FilterChain has already been called!"); if (this.iterator == null) { this.iterator = this.filters.iterator(); } if (this.iterator.hasNext()) { Filter nextFilter = this.iterator.next(); nextFilter.doFilter(request, response, this); } this.request = request; this.response = response; } /** * Reset this {@code MockFilterChain} allowing it to be invoked again. */ public void reset() { this.request = null; this.response = null; this.iterator = null; } /** * A filter that simply delegates to a Servlet. */ private static final class ServletFilterProxy implements Filter { private final Servlet delegateServlet; private ServletFilterProxy (Servlet servlet) { Assert.notNull(servlet, "servlet cannot be null"); this.delegateServlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegateServlet.service(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public String toString() { return this.delegateServlet.toString(); } } } | java |
MockFilterChain(Servlet servlet) { this.filters = initFilterList(servlet); } /** * Create a {@code MockFilterChain} with a {@link Servlet} and {@linkplain Filter * filters}. * @param servlet the {@code Servlet} to invoke in this {@code MockFilterChain} * @param filters the filters to invoke in this {@code MockFilterChain} * @since 3.2 */ public MockFilterChain(Servlet servlet, Filter... filters) { Assert.notNull(filters, "filters cannot be null"); Assert.noNullElements(filters, "filters cannot contain null values"); this.filters = initFilterList(servlet, filters); } private static List<Filter> initFilterList(Servlet servlet, Filter... filters) { Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new <mask> <mask> <mask> <mask> <mask> <mask> (servlet)); return List.of(allFilters); } /** * Return the request that {@link #doFilter} has been called with. */ public @Nullable ServletRequest getRequest() { return this.request; } /** * Return the response that {@link #doFilter} has been called with. */ public @Nullable ServletResponse getResponse() { return this.response; } /** * Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving the * request and response. */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(this.request == null, "This FilterChain has already been called!"); if (this.iterator == null) { this.iterator = this.filters.iterator(); } if (this.iterator.hasNext()) { Filter nextFilter = this.iterator.next(); nextFilter.doFilter(request, response, this); } this.request = request; this.response = response; } /** * Reset this {@code MockFilterChain} allowing it to be invoked again. */ public void reset() { this.request = null; this.response = null; this.iterator = null; } /** * A filter that simply delegates to a Servlet. */ private static final class <mask> <mask> <mask> <mask> <mask> <mask> implements Filter { private final Servlet delegateServlet; private <mask> <mask> <mask> <mask> <mask> <mask> (Servlet servlet) { Assert.notNull(servlet, "servlet cannot be null"); this.delegateServlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegateServlet.service(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public String toString() { return this.delegateServlet.toString(); } } } | MockFilterChain(Servlet servlet) { this.filters = initFilterList(servlet); } /** * Create a {@code MockFilterChain} with a {@link Servlet} and {@linkplain Filter * filters}. * @param servlet the {@code Servlet} to invoke in this {@code MockFilterChain} * @param filters the filters to invoke in this {@code MockFilterChain} * @since 3.2 */ public MockFilterChain(Servlet servlet, Filter... filters) { Assert.notNull(filters, "filters cannot be null"); Assert.noNullElements(filters, "filters cannot contain null values"); this.filters = initFilterList(servlet, filters); } private static List<Filter> initFilterList(Servlet servlet, Filter... filters) { Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new ServletFilterProxy (servlet)); return List.of(allFilters); } /** * Return the request that {@link #doFilter} has been called with. */ public @Nullable ServletRequest getRequest() { return this.request; } /** * Return the response that {@link #doFilter} has been called with. */ public @Nullable ServletResponse getResponse() { return this.response; } /** * Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving the * request and response. */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(this.request == null, "This FilterChain has already been called!"); if (this.iterator == null) { this.iterator = this.filters.iterator(); } if (this.iterator.hasNext()) { Filter nextFilter = this.iterator.next(); nextFilter.doFilter(request, response, this); } this.request = request; this.response = response; } /** * Reset this {@code MockFilterChain} allowing it to be invoked again. */ public void reset() { this.request = null; this.response = null; this.iterator = null; } /** * A filter that simply delegates to a Servlet. */ private static final class ServletFilterProxy implements Filter { private final Servlet delegateServlet; private ServletFilterProxy (Servlet servlet) { Assert.notNull(servlet, "servlet cannot be null"); this.delegateServlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegateServlet.service(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public String toString() { return this.delegateServlet.toString(); } } } | java |
Create a {@code MockFilterChain} with a {@link Servlet} and {@linkplain Filter * filters}. * @param servlet the {@code Servlet} to invoke in this {@code MockFilterChain} * @param filters the filters to invoke in this {@code MockFilterChain} * @since 3.2 */ public MockFilterChain(Servlet servlet, Filter... filters) { Assert.notNull(filters, "filters cannot be null"); Assert.noNullElements(filters, "filters cannot contain null values"); this.filters = initFilterList(servlet, filters); } private static List<Filter> initFilterList(Servlet servlet, Filter... filters) { Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new <mask> <mask> <mask> <mask> <mask> <mask> (servlet)); return List.of(allFilters); } /** * Return the request that {@link #doFilter} has been called with. */ public @Nullable ServletRequest getRequest() { return this.request; } /** * Return the response that {@link #doFilter} has been called with. */ public @Nullable ServletResponse getResponse() { return this.response; } /** * Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving the * request and response. */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(this.request == null, "This FilterChain has already been called!"); if (this.iterator == null) { this.iterator = this.filters.iterator(); } if (this.iterator.hasNext()) { Filter nextFilter = this.iterator.next(); nextFilter.doFilter(request, response, this); } this.request = request; this.response = response; } /** * Reset this {@code MockFilterChain} allowing it to be invoked again. */ public void reset() { this.request = null; this.response = null; this.iterator = null; } /** * A filter that simply delegates to a Servlet. */ private static final class <mask> <mask> <mask> <mask> <mask> <mask> implements Filter { private final Servlet delegateServlet; private <mask> <mask> <mask> <mask> <mask> <mask> (Servlet servlet) { Assert.notNull(servlet, "servlet cannot be null"); this.delegateServlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegateServlet.service(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public String toString() { return this.delegateServlet.toString(); } } } | Create a {@code MockFilterChain} with a {@link Servlet} and {@linkplain Filter * filters}. * @param servlet the {@code Servlet} to invoke in this {@code MockFilterChain} * @param filters the filters to invoke in this {@code MockFilterChain} * @since 3.2 */ public MockFilterChain(Servlet servlet, Filter... filters) { Assert.notNull(filters, "filters cannot be null"); Assert.noNullElements(filters, "filters cannot contain null values"); this.filters = initFilterList(servlet, filters); } private static List<Filter> initFilterList(Servlet servlet, Filter... filters) { Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new ServletFilterProxy (servlet)); return List.of(allFilters); } /** * Return the request that {@link #doFilter} has been called with. */ public @Nullable ServletRequest getRequest() { return this.request; } /** * Return the response that {@link #doFilter} has been called with. */ public @Nullable ServletResponse getResponse() { return this.response; } /** * Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving the * request and response. */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(this.request == null, "This FilterChain has already been called!"); if (this.iterator == null) { this.iterator = this.filters.iterator(); } if (this.iterator.hasNext()) { Filter nextFilter = this.iterator.next(); nextFilter.doFilter(request, response, this); } this.request = request; this.response = response; } /** * Reset this {@code MockFilterChain} allowing it to be invoked again. */ public void reset() { this.request = null; this.response = null; this.iterator = null; } /** * A filter that simply delegates to a Servlet. */ private static final class ServletFilterProxy implements Filter { private final Servlet delegateServlet; private ServletFilterProxy (Servlet servlet) { Assert.notNull(servlet, "servlet cannot be null"); this.delegateServlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegateServlet.service(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public String toString() { return this.delegateServlet.toString(); } } } | java |
package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = | package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. common .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. common .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. common .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = | java |
package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // | package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. common .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. common .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. common .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // | java |
package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // 情况四 TableField field = mock(TableField.class); | package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. common .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. common .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. common .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // 情况四 TableField field = mock(TableField.class); | java |
package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // 情况四 TableField field = mock(TableField.class); when(field.getName()).thenReturn("name"); when(tableInfo.getFields()).thenReturn(Collections.singletonList(field)); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), | package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. common .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. common .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. common .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // 情况四 TableField field = mock(TableField.class); when(field.getName()).thenReturn("name"); when(tableInfo.getFields()).thenReturn(Collections.singletonList(field)); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), | java |
package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. <mask> <mask> <mask> .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // 情况四 TableField field = mock(TableField.class); when(field.getName()).thenReturn("name"); when(tableInfo.getFields()).thenReturn(Collections.singletonList(field)); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_COLUMN_COMMENT_IS_NULL, field.getName()); } @Test public | package cn.iocoder.yudao.module.infra.service.codegen; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework. common .pojo.PageResult; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.CodegenUpdateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.column.CodegenColumnSaveReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.CodegenTablePageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.codegen.vo.table.DatabaseTableRespVO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenColumnDO; import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.CodegenTableDO; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenColumnMapper; import cn.iocoder.yudao.module.infra.dal.mysql.codegen.CodegenTableMapper; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenFrontTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenBuilder; import cn.iocoder.yudao.module.infra.service.codegen.inner.CodegenEngine; import cn.iocoder.yudao.module.infra.service.db.DatabaseTableService; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.baomidou.mybatisplus.generator.config.po.TableField; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework. common .pojo.CommonResult.success; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework. common .util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework. common .util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * {@link CodegenServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(CodegenServiceImpl.class) public class CodegenServiceImplTest extends BaseDbUnitTest { @Resource private CodegenServiceImpl codegenService; @Resource private CodegenTableMapper codegenTableMapper; @Resource private CodegenColumnMapper codegenColumnMapper; @MockBean private DatabaseTableService databaseTableService; @MockBean private AdminUserApi userApi; @MockBean private CodegenBuilder codegenBuilder; @MockBean private CodegenEngine codegenEngine; @MockBean private CodegenProperties codegenProperties; @Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) TableInfo tableInfo = mock(TableInfo.class); when(databaseTableService.getTable(eq(1L), eq("t_yunai"))) .thenReturn(tableInfo); when(tableInfo.getComment()).thenReturn("芋艿"); // mock 方法(TableInfo fields) TableField field01 = mock(TableField.class); when(field01.getComment()).thenReturn("主键"); TableField field02 = mock(TableField.class); when(field02.getComment()).thenReturn("名字"); List<TableField> fields = Arrays.asList(field01, field02); when(tableInfo.getFields()).thenReturn(fields); // mock 方法(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class); when(codegenBuilder.buildTable(same(tableInfo))).thenReturn(table); // mock 方法(AdminUserRespDTO) AdminUserRespDTO user = randomPojo(AdminUserRespDTO.class, o -> o.setNickname("芋头")); when(userApi.getUser(eq(userId))).thenReturn(success(user)); // mock 方法(CodegenColumnDO) List<CodegenColumnDO> columns = randomPojoList(CodegenColumnDO.class); when(codegenBuilder.buildColumns(eq(table.getId()), same(fields))) .thenReturn(columns); // mock 方法(CodegenProperties) when(codegenProperties.getFrontType()).thenReturn(CodegenFrontTypeEnum.VUE3.getType()); // 调用 List<Long> result = codegenService.createCodegenList(userId, reqVO); // 断言 assertEquals(1, result.size()); // 断言(CodegenTableDO) CodegenTableDO dbTable = codegenTableMapper.selectList().get(0); assertPojoEquals(table, dbTable); assertEquals(1L, dbTable.getDataSourceConfigId()); assertEquals(CodegenSceneEnum.ADMIN.getScene(), dbTable.getScene()); assertEquals(CodegenFrontTypeEnum.VUE3.getType(), dbTable.getFrontType()); assertEquals("芋头", dbTable.getAuthor()); // 断言(CodegenColumnDO) List<CodegenColumnDO> dbColumns = codegenColumnMapper.selectList(); assertEquals(columns.size(), dbColumns.size()); assertTrue(dbColumns.get(0).getPrimaryKey()); for (int i = 0; i < dbColumns.size(); i++) { assertPojoEquals(columns.get(i), dbColumns.get(i)); } } @Test public void testValidateTableInfo() { // 情况一 assertServiceException(() -> codegenService.validateTableInfo(null), CODEGEN_IMPORT_TABLE_NULL); // 情况二 TableInfo tableInfo = mock(TableInfo.class); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL); // 情况三 when(tableInfo.getComment()).thenReturn("芋艿"); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_IMPORT_COLUMNS_NULL); // 情况四 TableField field = mock(TableField.class); when(field.getName()).thenReturn("name"); when(tableInfo.getFields()).thenReturn(Collections.singletonList(field)); assertServiceException(() -> codegenService.validateTableInfo(tableInfo), CODEGEN_TABLE_INFO_COLUMN_COMMENT_IS_NULL, field.getName()); } @Test public | java |
NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.core.posix.linux; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_A_RELOCATABLE_POINTER; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_END; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_RELOCATABLE_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_RELOCATABLE_END; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_END; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_PATCHED_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_PATCHED_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_RELOCATABLE_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_RELOCATABLE_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_PATCHED_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_PATCHED_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.NEXT_SECTION; import static com.oracle.svm.core.posix.linux.ProcFSSupport. <mask> <mask> <mask> <mask> <mask> ; import static com.oracle.svm.core.util.PointerUtils.roundDown; import static com.oracle.svm.core.util.UnsignedUtils.isAMultiple; import static com.oracle.svm.core.util.UnsignedUtils.roundUp; import static jdk.graal.compiler.word.Word.signed; import java.util.concurrent.ThreadLocalRandom; import org.graalvm.nativeimage.StackValue; import org.graalvm.nativeimage.c.type.CCharPointer; import org.graalvm.nativeimage.c.type.WordPointer; import org.graalvm.word.ComparableWord; import org.graalvm.word.LocationIdentity; import org.graalvm.word.Pointer; import org.graalvm.word.PointerBase; import org.graalvm.word.SignedWord; import org.graalvm.word.UnsignedWord; import com.oracle.svm.core.SubstrateOptions; import com.oracle.svm.core.Uninterruptible; import com.oracle.svm.core.c.CGlobalData; import com.oracle.svm.core.c.CGlobalDataFactory; import com.oracle.svm.core.c.function.CEntryPointErrors; import com.oracle.svm.core.code.DynamicMethodAddressResolutionHeapSupport; import com.oracle.svm.core.config.ConfigurationValues; import com.oracle.svm.core.headers.LibC; import com.oracle.svm.core.heap.Heap; import com.oracle.svm.core.imagelayer.ImageLayerBuildingSupport; import com.oracle.svm.core.imagelayer.ImageLayerSection; import com.oracle.svm.core.os.AbstractImageHeapProvider; import com.oracle.svm.core.os.VirtualMemoryProvider; import com.oracle.svm.core.os.VirtualMemoryProvider.Access; import com.oracle.svm.core.posix.PosixUtils; import com.oracle.svm.core.posix.headers.Errno; import com.oracle.svm.core.posix.headers.Fcntl; import com.oracle.svm.core.posix.headers.Unistd; import com.oracle.svm.core.util.PointerUtils; import com.oracle.svm.core.util.UnsignedUtils; import com.oracle.svm.core.util.VMError; import jdk.graal.compiler.nodes.PauseNode; import jdk.graal.compiler.word.Word; /** * An optimal image heap provider for Linux which creates isolate image heaps that retain the * copy-on-write, lazy loading and reclamation semantics provided by the original heap's backing * resource. * * This is accomplished by discovering the backing executable or shared object file the kernel has * mmapped to the original heap image virtual address, as well as the location in the file storing * the original heap. A new memory map is created to a new virtual range pointing to this same * location. This allows the kernel to share the same physical pages between multiple heaps that * have not been modified, as well as lazily load them only when needed. * * The implementation avoids dirtying the pages of the original, and only referencing what is * strictly required. */ public class LinuxImageHeapProvider extends AbstractImageHeapProvider { /** Magic value to verify that a located image file matches our loaded image. */ public static final CGlobalData<Pointer> MAGIC = CGlobalDataFactory.createWord(Word.<Word> signed(ThreadLocalRandom.current().nextLong())); private static final CGlobalData<CCharPointer> PROC_SELF_MAPS = | NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.core.posix.linux; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_A_RELOCATABLE_POINTER; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_END; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_RELOCATABLE_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_RELOCATABLE_END; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_END; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_PATCHED_BEGIN; import static com.oracle.svm.core.Isolates.IMAGE_HEAP_WRITABLE_PATCHED_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_RELOCATABLE_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_RELOCATABLE_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_PATCHED_BEGIN; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.HEAP_WRITEABLE_PATCHED_END; import static com.oracle.svm.core.imagelayer.ImageLayerSection.SectionEntries.NEXT_SECTION; import static com.oracle.svm.core.posix.linux.ProcFSSupport. findMapping ; import static com.oracle.svm.core.util.PointerUtils.roundDown; import static com.oracle.svm.core.util.UnsignedUtils.isAMultiple; import static com.oracle.svm.core.util.UnsignedUtils.roundUp; import static jdk.graal.compiler.word.Word.signed; import java.util.concurrent.ThreadLocalRandom; import org.graalvm.nativeimage.StackValue; import org.graalvm.nativeimage.c.type.CCharPointer; import org.graalvm.nativeimage.c.type.WordPointer; import org.graalvm.word.ComparableWord; import org.graalvm.word.LocationIdentity; import org.graalvm.word.Pointer; import org.graalvm.word.PointerBase; import org.graalvm.word.SignedWord; import org.graalvm.word.UnsignedWord; import com.oracle.svm.core.SubstrateOptions; import com.oracle.svm.core.Uninterruptible; import com.oracle.svm.core.c.CGlobalData; import com.oracle.svm.core.c.CGlobalDataFactory; import com.oracle.svm.core.c.function.CEntryPointErrors; import com.oracle.svm.core.code.DynamicMethodAddressResolutionHeapSupport; import com.oracle.svm.core.config.ConfigurationValues; import com.oracle.svm.core.headers.LibC; import com.oracle.svm.core.heap.Heap; import com.oracle.svm.core.imagelayer.ImageLayerBuildingSupport; import com.oracle.svm.core.imagelayer.ImageLayerSection; import com.oracle.svm.core.os.AbstractImageHeapProvider; import com.oracle.svm.core.os.VirtualMemoryProvider; import com.oracle.svm.core.os.VirtualMemoryProvider.Access; import com.oracle.svm.core.posix.PosixUtils; import com.oracle.svm.core.posix.headers.Errno; import com.oracle.svm.core.posix.headers.Fcntl; import com.oracle.svm.core.posix.headers.Unistd; import com.oracle.svm.core.util.PointerUtils; import com.oracle.svm.core.util.UnsignedUtils; import com.oracle.svm.core.util.VMError; import jdk.graal.compiler.nodes.PauseNode; import jdk.graal.compiler.word.Word; /** * An optimal image heap provider for Linux which creates isolate image heaps that retain the * copy-on-write, lazy loading and reclamation semantics provided by the original heap's backing * resource. * * This is accomplished by discovering the backing executable or shared object file the kernel has * mmapped to the original heap image virtual address, as well as the location in the file storing * the original heap. A new memory map is created to a new virtual range pointing to this same * location. This allows the kernel to share the same physical pages between multiple heaps that * have not been modified, as well as lazily load them only when needed. * * The implementation avoids dirtying the pages of the original, and only referencing what is * strictly required. */ public class LinuxImageHeapProvider extends AbstractImageHeapProvider { /** Magic value to verify that a located image file matches our loaded image. */ public static final CGlobalData<Pointer> MAGIC = CGlobalDataFactory.createWord(Word.<Word> signed(ThreadLocalRandom.current().nextLong())); private static final CGlobalData<CCharPointer> PROC_SELF_MAPS = | java |
int unprotectWritablePages(Pointer imageHeap, UnsignedWord pageSize, Word heapBeginSym, Word heapWritableSym, Word heapWritableEndSym) { /* * The last page might be shared with the subsequent read-only huge objects partition, in * which case we make some of its data writable, which we consider acceptable. */ Pointer writableBegin = imageHeap.add(heapWritableSym.subtract(heapBeginSym)); UnsignedWord writableSize = heapWritableEndSym.subtract(heapWritableSym); UnsignedWord alignedWritableSize = roundUp(writableSize, pageSize); if (VirtualMemoryProvider.get().protect(writableBegin, alignedWritableSize, Access.READ | Access.WRITE) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } @Uninterruptible(reason = "Called during isolate initialization.") private static int initializeImageHeapByCopying(Pointer imageHeap, UnsignedWord imageHeapSize, UnsignedWord pageSize, Word heapBeginSym, Word heapWritableSym, Word heapWritableEndSym) { Pointer committedBegin = VirtualMemoryProvider.get().commit(imageHeap, imageHeapSize, Access.READ | Access.WRITE); if (committedBegin.isNull()) { return CEntryPointErrors.MAP_HEAP_FAILED; } LibC.memcpy(imageHeap, heapBeginSym, imageHeapSize); UnsignedWord readOnlyBytesAtBegin = heapWritableSym.subtract(heapBeginSym); readOnlyBytesAtBegin = UnsignedUtils.roundDown(readOnlyBytesAtBegin, pageSize); if (readOnlyBytesAtBegin.aboveThan(0) && VirtualMemoryProvider.get().protect(imageHeap, readOnlyBytesAtBegin, Access.READ) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } Pointer writableEnd = imageHeap.add(heapWritableEndSym.subtract(heapBeginSym)); writableEnd = PointerUtils.roundUp(writableEnd, pageSize); UnsignedWord readOnlyBytesAtEnd = imageHeap.add(imageHeapSize).subtract(writableEnd); readOnlyBytesAtEnd = roundUp(readOnlyBytesAtEnd, pageSize); if (readOnlyBytesAtEnd.aboveThan(0) && VirtualMemoryProvider.get().protect(writableEnd, readOnlyBytesAtEnd, Access.READ) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } /** * Locate our image file, containing the image heap. Unfortunately we must open it by its path. * We do not use /proc/self/exe because it breaks with some tools like Valgrind. */ @Uninterruptible(reason = "Called during isolate initialization.") private static int openImageFile(Word heapBeginSym, Pointer magicAddress, WordPointer cachedImageHeapOffsetInFile) { final int failfd = (int) CANNOT_OPEN_FD.rawValue(); int mapfd = Fcntl.NoTransitions.open(PROC_SELF_MAPS.get(), Fcntl.O_RDONLY(), 0); if (mapfd == -1) { return failfd; } final int bufferSize = MAX_PATHLEN; CCharPointer buffer = StackValue.get(bufferSize); WordPointer imageHeapMappingStart = StackValue.get(WordPointer.class); WordPointer imageHeapMappingFileOffset = StackValue.get(WordPointer.class); boolean found = <mask> <mask> <mask> <mask> <mask> (mapfd, buffer, bufferSize, heapBeginSym, heapBeginSym.add(1), imageHeapMappingStart, imageHeapMappingFileOffset, true); if (!found) { Unistd.NoTransitions.close(mapfd); return failfd; } int opened = Fcntl.NoTransitions.open(buffer, Fcntl.O_RDONLY(), 0); if (opened < 0) { Unistd.NoTransitions.close(mapfd); return failfd; } boolean valid = magicAddress.isNull() || checkImageFileMagic(mapfd, opened, buffer, bufferSize, magicAddress); Unistd.NoTransitions.close(mapfd); if (!valid) { Unistd.NoTransitions.close(opened); return failfd; } Word imageHeapOffsetInMapping = heapBeginSym.subtract(imageHeapMappingStart.read()); UnsignedWord imageHeapOffsetInFile = imageHeapOffsetInMapping.add(imageHeapMappingFileOffset.read()); cachedImageHeapOffsetInFile.write(imageHeapOffsetInFile); return opened; } @Uninterruptible(reason = "Called during isolate initialization.") private static boolean checkImageFileMagic(int mapfd, int imagefd, CCharPointer buffer, int bufferSize, Pointer magicAddress) { if (Unistd.NoTransitions.lseek(mapfd, signed(0), Unistd.SEEK_SET()).notEqual(0)) { return false; } // Find the offset of the magic word in the image file. We cannot reliably compute it // from the image heap offset below because it might be in a different file segment. int wordSize = ConfigurationValues.getTarget().wordSize; WordPointer magicMappingStart = StackValue.get(WordPointer.class); WordPointer magicMappingFileOffset = StackValue.get(WordPointer.class); boolean found = <mask> <mask> <mask> <mask> <mask> (mapfd, buffer, bufferSize, magicAddress, magicAddress.add(wordSize), magicMappingStart, magicMappingFileOffset, false); if (!found) { return false; } Word magicFileOffset = (Word) magicAddress.subtract(magicMappingStart.read()).add(magicMappingFileOffset.read()); // Compare the magic word in memory with the magic word read from the file if (Unistd.NoTransitions.lseek(imagefd, magicFileOffset, Unistd.SEEK_SET()).notEqual(magicFileOffset)) { return false; } if (PosixUtils.readUninterruptibly(imagefd, (Pointer) buffer, wordSize) != wordSize) { return false; } Word fileMagic = ((WordPointer) buffer).read(); return fileMagic.equal(magicAddress.readWord(0)); } @Override @Uninterruptible(reason = "Called during isolate tear-down.") public int freeImageHeap(PointerBase heapBase) { if (heapBase.isNull()) { // no memory allocated return CEntryPointErrors.NO_ERROR; } VMError.guarantee(heapBase.notEqual(IMAGE_HEAP_BEGIN.get()), "reusing the image heap is no longer supported"); Pointer addressSpaceStart = (Pointer) heapBase; if (DynamicMethodAddressResolutionHeapSupport.isEnabled()) { addressSpaceStart = addressSpaceStart.subtract(getPreHeapAlignedSizeForDynamicMethodAddressResolver()); } if (VirtualMemoryProvider.get().free(addressSpaceStart, getTotalRequiredAddressSpaceSize()) != 0) { return CEntryPointErrors.FREE_IMAGE_HEAP_FAILED; } | int unprotectWritablePages(Pointer imageHeap, UnsignedWord pageSize, Word heapBeginSym, Word heapWritableSym, Word heapWritableEndSym) { /* * The last page might be shared with the subsequent read-only huge objects partition, in * which case we make some of its data writable, which we consider acceptable. */ Pointer writableBegin = imageHeap.add(heapWritableSym.subtract(heapBeginSym)); UnsignedWord writableSize = heapWritableEndSym.subtract(heapWritableSym); UnsignedWord alignedWritableSize = roundUp(writableSize, pageSize); if (VirtualMemoryProvider.get().protect(writableBegin, alignedWritableSize, Access.READ | Access.WRITE) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } @Uninterruptible(reason = "Called during isolate initialization.") private static int initializeImageHeapByCopying(Pointer imageHeap, UnsignedWord imageHeapSize, UnsignedWord pageSize, Word heapBeginSym, Word heapWritableSym, Word heapWritableEndSym) { Pointer committedBegin = VirtualMemoryProvider.get().commit(imageHeap, imageHeapSize, Access.READ | Access.WRITE); if (committedBegin.isNull()) { return CEntryPointErrors.MAP_HEAP_FAILED; } LibC.memcpy(imageHeap, heapBeginSym, imageHeapSize); UnsignedWord readOnlyBytesAtBegin = heapWritableSym.subtract(heapBeginSym); readOnlyBytesAtBegin = UnsignedUtils.roundDown(readOnlyBytesAtBegin, pageSize); if (readOnlyBytesAtBegin.aboveThan(0) && VirtualMemoryProvider.get().protect(imageHeap, readOnlyBytesAtBegin, Access.READ) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } Pointer writableEnd = imageHeap.add(heapWritableEndSym.subtract(heapBeginSym)); writableEnd = PointerUtils.roundUp(writableEnd, pageSize); UnsignedWord readOnlyBytesAtEnd = imageHeap.add(imageHeapSize).subtract(writableEnd); readOnlyBytesAtEnd = roundUp(readOnlyBytesAtEnd, pageSize); if (readOnlyBytesAtEnd.aboveThan(0) && VirtualMemoryProvider.get().protect(writableEnd, readOnlyBytesAtEnd, Access.READ) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } /** * Locate our image file, containing the image heap. Unfortunately we must open it by its path. * We do not use /proc/self/exe because it breaks with some tools like Valgrind. */ @Uninterruptible(reason = "Called during isolate initialization.") private static int openImageFile(Word heapBeginSym, Pointer magicAddress, WordPointer cachedImageHeapOffsetInFile) { final int failfd = (int) CANNOT_OPEN_FD.rawValue(); int mapfd = Fcntl.NoTransitions.open(PROC_SELF_MAPS.get(), Fcntl.O_RDONLY(), 0); if (mapfd == -1) { return failfd; } final int bufferSize = MAX_PATHLEN; CCharPointer buffer = StackValue.get(bufferSize); WordPointer imageHeapMappingStart = StackValue.get(WordPointer.class); WordPointer imageHeapMappingFileOffset = StackValue.get(WordPointer.class); boolean found = findMapping (mapfd, buffer, bufferSize, heapBeginSym, heapBeginSym.add(1), imageHeapMappingStart, imageHeapMappingFileOffset, true); if (!found) { Unistd.NoTransitions.close(mapfd); return failfd; } int opened = Fcntl.NoTransitions.open(buffer, Fcntl.O_RDONLY(), 0); if (opened < 0) { Unistd.NoTransitions.close(mapfd); return failfd; } boolean valid = magicAddress.isNull() || checkImageFileMagic(mapfd, opened, buffer, bufferSize, magicAddress); Unistd.NoTransitions.close(mapfd); if (!valid) { Unistd.NoTransitions.close(opened); return failfd; } Word imageHeapOffsetInMapping = heapBeginSym.subtract(imageHeapMappingStart.read()); UnsignedWord imageHeapOffsetInFile = imageHeapOffsetInMapping.add(imageHeapMappingFileOffset.read()); cachedImageHeapOffsetInFile.write(imageHeapOffsetInFile); return opened; } @Uninterruptible(reason = "Called during isolate initialization.") private static boolean checkImageFileMagic(int mapfd, int imagefd, CCharPointer buffer, int bufferSize, Pointer magicAddress) { if (Unistd.NoTransitions.lseek(mapfd, signed(0), Unistd.SEEK_SET()).notEqual(0)) { return false; } // Find the offset of the magic word in the image file. We cannot reliably compute it // from the image heap offset below because it might be in a different file segment. int wordSize = ConfigurationValues.getTarget().wordSize; WordPointer magicMappingStart = StackValue.get(WordPointer.class); WordPointer magicMappingFileOffset = StackValue.get(WordPointer.class); boolean found = findMapping (mapfd, buffer, bufferSize, magicAddress, magicAddress.add(wordSize), magicMappingStart, magicMappingFileOffset, false); if (!found) { return false; } Word magicFileOffset = (Word) magicAddress.subtract(magicMappingStart.read()).add(magicMappingFileOffset.read()); // Compare the magic word in memory with the magic word read from the file if (Unistd.NoTransitions.lseek(imagefd, magicFileOffset, Unistd.SEEK_SET()).notEqual(magicFileOffset)) { return false; } if (PosixUtils.readUninterruptibly(imagefd, (Pointer) buffer, wordSize) != wordSize) { return false; } Word fileMagic = ((WordPointer) buffer).read(); return fileMagic.equal(magicAddress.readWord(0)); } @Override @Uninterruptible(reason = "Called during isolate tear-down.") public int freeImageHeap(PointerBase heapBase) { if (heapBase.isNull()) { // no memory allocated return CEntryPointErrors.NO_ERROR; } VMError.guarantee(heapBase.notEqual(IMAGE_HEAP_BEGIN.get()), "reusing the image heap is no longer supported"); Pointer addressSpaceStart = (Pointer) heapBase; if (DynamicMethodAddressResolutionHeapSupport.isEnabled()) { addressSpaceStart = addressSpaceStart.subtract(getPreHeapAlignedSizeForDynamicMethodAddressResolver()); } if (VirtualMemoryProvider.get().free(addressSpaceStart, getTotalRequiredAddressSpaceSize()) != 0) { return CEntryPointErrors.FREE_IMAGE_HEAP_FAILED; } | java |
pageSize); UnsignedWord readOnlyBytesAtEnd = imageHeap.add(imageHeapSize).subtract(writableEnd); readOnlyBytesAtEnd = roundUp(readOnlyBytesAtEnd, pageSize); if (readOnlyBytesAtEnd.aboveThan(0) && VirtualMemoryProvider.get().protect(writableEnd, readOnlyBytesAtEnd, Access.READ) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } /** * Locate our image file, containing the image heap. Unfortunately we must open it by its path. * We do not use /proc/self/exe because it breaks with some tools like Valgrind. */ @Uninterruptible(reason = "Called during isolate initialization.") private static int openImageFile(Word heapBeginSym, Pointer magicAddress, WordPointer cachedImageHeapOffsetInFile) { final int failfd = (int) CANNOT_OPEN_FD.rawValue(); int mapfd = Fcntl.NoTransitions.open(PROC_SELF_MAPS.get(), Fcntl.O_RDONLY(), 0); if (mapfd == -1) { return failfd; } final int bufferSize = MAX_PATHLEN; CCharPointer buffer = StackValue.get(bufferSize); WordPointer imageHeapMappingStart = StackValue.get(WordPointer.class); WordPointer imageHeapMappingFileOffset = StackValue.get(WordPointer.class); boolean found = <mask> <mask> <mask> <mask> <mask> (mapfd, buffer, bufferSize, heapBeginSym, heapBeginSym.add(1), imageHeapMappingStart, imageHeapMappingFileOffset, true); if (!found) { Unistd.NoTransitions.close(mapfd); return failfd; } int opened = Fcntl.NoTransitions.open(buffer, Fcntl.O_RDONLY(), 0); if (opened < 0) { Unistd.NoTransitions.close(mapfd); return failfd; } boolean valid = magicAddress.isNull() || checkImageFileMagic(mapfd, opened, buffer, bufferSize, magicAddress); Unistd.NoTransitions.close(mapfd); if (!valid) { Unistd.NoTransitions.close(opened); return failfd; } Word imageHeapOffsetInMapping = heapBeginSym.subtract(imageHeapMappingStart.read()); UnsignedWord imageHeapOffsetInFile = imageHeapOffsetInMapping.add(imageHeapMappingFileOffset.read()); cachedImageHeapOffsetInFile.write(imageHeapOffsetInFile); return opened; } @Uninterruptible(reason = "Called during isolate initialization.") private static boolean checkImageFileMagic(int mapfd, int imagefd, CCharPointer buffer, int bufferSize, Pointer magicAddress) { if (Unistd.NoTransitions.lseek(mapfd, signed(0), Unistd.SEEK_SET()).notEqual(0)) { return false; } // Find the offset of the magic word in the image file. We cannot reliably compute it // from the image heap offset below because it might be in a different file segment. int wordSize = ConfigurationValues.getTarget().wordSize; WordPointer magicMappingStart = StackValue.get(WordPointer.class); WordPointer magicMappingFileOffset = StackValue.get(WordPointer.class); boolean found = <mask> <mask> <mask> <mask> <mask> (mapfd, buffer, bufferSize, magicAddress, magicAddress.add(wordSize), magicMappingStart, magicMappingFileOffset, false); if (!found) { return false; } Word magicFileOffset = (Word) magicAddress.subtract(magicMappingStart.read()).add(magicMappingFileOffset.read()); // Compare the magic word in memory with the magic word read from the file if (Unistd.NoTransitions.lseek(imagefd, magicFileOffset, Unistd.SEEK_SET()).notEqual(magicFileOffset)) { return false; } if (PosixUtils.readUninterruptibly(imagefd, (Pointer) buffer, wordSize) != wordSize) { return false; } Word fileMagic = ((WordPointer) buffer).read(); return fileMagic.equal(magicAddress.readWord(0)); } @Override @Uninterruptible(reason = "Called during isolate tear-down.") public int freeImageHeap(PointerBase heapBase) { if (heapBase.isNull()) { // no memory allocated return CEntryPointErrors.NO_ERROR; } VMError.guarantee(heapBase.notEqual(IMAGE_HEAP_BEGIN.get()), "reusing the image heap is no longer supported"); Pointer addressSpaceStart = (Pointer) heapBase; if (DynamicMethodAddressResolutionHeapSupport.isEnabled()) { addressSpaceStart = addressSpaceStart.subtract(getPreHeapAlignedSizeForDynamicMethodAddressResolver()); } if (VirtualMemoryProvider.get().free(addressSpaceStart, getTotalRequiredAddressSpaceSize()) != 0) { return CEntryPointErrors.FREE_IMAGE_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } } | pageSize); UnsignedWord readOnlyBytesAtEnd = imageHeap.add(imageHeapSize).subtract(writableEnd); readOnlyBytesAtEnd = roundUp(readOnlyBytesAtEnd, pageSize); if (readOnlyBytesAtEnd.aboveThan(0) && VirtualMemoryProvider.get().protect(writableEnd, readOnlyBytesAtEnd, Access.READ) != 0) { return CEntryPointErrors.PROTECT_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } /** * Locate our image file, containing the image heap. Unfortunately we must open it by its path. * We do not use /proc/self/exe because it breaks with some tools like Valgrind. */ @Uninterruptible(reason = "Called during isolate initialization.") private static int openImageFile(Word heapBeginSym, Pointer magicAddress, WordPointer cachedImageHeapOffsetInFile) { final int failfd = (int) CANNOT_OPEN_FD.rawValue(); int mapfd = Fcntl.NoTransitions.open(PROC_SELF_MAPS.get(), Fcntl.O_RDONLY(), 0); if (mapfd == -1) { return failfd; } final int bufferSize = MAX_PATHLEN; CCharPointer buffer = StackValue.get(bufferSize); WordPointer imageHeapMappingStart = StackValue.get(WordPointer.class); WordPointer imageHeapMappingFileOffset = StackValue.get(WordPointer.class); boolean found = findMapping (mapfd, buffer, bufferSize, heapBeginSym, heapBeginSym.add(1), imageHeapMappingStart, imageHeapMappingFileOffset, true); if (!found) { Unistd.NoTransitions.close(mapfd); return failfd; } int opened = Fcntl.NoTransitions.open(buffer, Fcntl.O_RDONLY(), 0); if (opened < 0) { Unistd.NoTransitions.close(mapfd); return failfd; } boolean valid = magicAddress.isNull() || checkImageFileMagic(mapfd, opened, buffer, bufferSize, magicAddress); Unistd.NoTransitions.close(mapfd); if (!valid) { Unistd.NoTransitions.close(opened); return failfd; } Word imageHeapOffsetInMapping = heapBeginSym.subtract(imageHeapMappingStart.read()); UnsignedWord imageHeapOffsetInFile = imageHeapOffsetInMapping.add(imageHeapMappingFileOffset.read()); cachedImageHeapOffsetInFile.write(imageHeapOffsetInFile); return opened; } @Uninterruptible(reason = "Called during isolate initialization.") private static boolean checkImageFileMagic(int mapfd, int imagefd, CCharPointer buffer, int bufferSize, Pointer magicAddress) { if (Unistd.NoTransitions.lseek(mapfd, signed(0), Unistd.SEEK_SET()).notEqual(0)) { return false; } // Find the offset of the magic word in the image file. We cannot reliably compute it // from the image heap offset below because it might be in a different file segment. int wordSize = ConfigurationValues.getTarget().wordSize; WordPointer magicMappingStart = StackValue.get(WordPointer.class); WordPointer magicMappingFileOffset = StackValue.get(WordPointer.class); boolean found = findMapping (mapfd, buffer, bufferSize, magicAddress, magicAddress.add(wordSize), magicMappingStart, magicMappingFileOffset, false); if (!found) { return false; } Word magicFileOffset = (Word) magicAddress.subtract(magicMappingStart.read()).add(magicMappingFileOffset.read()); // Compare the magic word in memory with the magic word read from the file if (Unistd.NoTransitions.lseek(imagefd, magicFileOffset, Unistd.SEEK_SET()).notEqual(magicFileOffset)) { return false; } if (PosixUtils.readUninterruptibly(imagefd, (Pointer) buffer, wordSize) != wordSize) { return false; } Word fileMagic = ((WordPointer) buffer).read(); return fileMagic.equal(magicAddress.readWord(0)); } @Override @Uninterruptible(reason = "Called during isolate tear-down.") public int freeImageHeap(PointerBase heapBase) { if (heapBase.isNull()) { // no memory allocated return CEntryPointErrors.NO_ERROR; } VMError.guarantee(heapBase.notEqual(IMAGE_HEAP_BEGIN.get()), "reusing the image heap is no longer supported"); Pointer addressSpaceStart = (Pointer) heapBase; if (DynamicMethodAddressResolutionHeapSupport.isEnabled()) { addressSpaceStart = addressSpaceStart.subtract(getPreHeapAlignedSizeForDynamicMethodAddressResolver()); } if (VirtualMemoryProvider.get().free(addressSpaceStart, getTotalRequiredAddressSpaceSize()) != 0) { return CEntryPointErrors.FREE_IMAGE_HEAP_FAILED; } return CEntryPointErrors.NO_ERROR; } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
/* * 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. <mask> <mask> <mask> .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. <mask> <mask> <mask> .flink.connector.upserttest.sink; import org. <mask> <mask> <mask> .flink.api.common.serialization.DeserializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SerializationSchema; import org. <mask> <mask> <mask> .flink.api.common.serialization.SimpleStringSchema; import org. <mask> <mask> <mask> .flink.api.java.tuple.Tuple2; import org. <mask> <mask> <mask> .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. <mask> <mask> <mask> .flink.test.junit5.MiniClusterExtension; import org. <mask> <mask> <mask> .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | /* * 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.connector.upserttest.sink; import org. apache .flink.api.common.serialization.DeserializationSchema; import org. apache .flink.api.common.serialization.SerializationSchema; import org. apache .flink.api.common.serialization.SimpleStringSchema; import org. apache .flink.api.java.tuple.Tuple2; import org. apache .flink.runtime.testutils.MiniClusterResourceConfiguration; import org. apache .flink.test.junit5.MiniClusterExtension; import org. apache .flink.util.TestLoggerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link UpsertTestSinkWriter}. */ @ExtendWith(TestLoggerExtension.class) class UpsertTestSinkWriterITCase { @RegisterExtension public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(1) .build()); @TempDir private File tempDir; private File outputFile; private UpsertTestSinkWriter<Tuple2<String, String>> writer; private List<Tuple2<String, String>> expectedRecords; @BeforeEach void setup() { outputFile = tempDir.toPath().resolve(Paths.get("dir", "records.out")).toFile(); writer = createSinkWriter(outputFile); expectedRecords = writeTestData(writer); } @AfterEach void tearDown() throws Exception { writer.close(); } @Test void testWrite() throws Exception { writer.close(); testRecordPresence(outputFile, expectedRecords); } @Test void testWriteOnCheckpoint() throws Exception { writer.flush(false); testRecordPresence(outputFile, expectedRecords); } private UpsertTestSinkWriter<Tuple2<String, String>> createSinkWriter(File outputFile) { SerializationSchema<Tuple2<String, String>> keySerializationSchema = element -> element.f0.getBytes(); SerializationSchema<Tuple2<String, String>> valueSerializationSchema = element -> element.f1.getBytes(); return new UpsertTestSinkWriter<>( outputFile, keySerializationSchema, valueSerializationSchema); } private List<Tuple2<String, String>> writeTestData( UpsertTestSinkWriter<Tuple2<String, String>> writer) { final List<Tuple2<String, String>> expectedRecords = new ArrayList<>(); for (int i = 0; i < 10; i++) { Tuple2<String, String> record = Tuple2.of("Key #" + i, "Value #" + i); expectedRecords.add(record); writer.write(record, null); } return expectedRecords; } private void testRecordPresence(File outputFile, List<Tuple2<String, String>> expectedRecords) throws IOException { DeserializationSchema<String> keyDeserializationSchema = new SimpleStringSchema(); DeserializationSchema<String> valueDeserializationSchema = new SimpleStringSchema(); Map<String, String> resultMap = UpsertTestFileUtil.readRecords( outputFile, keyDeserializationSchema, valueDeserializationSchema); for (Tuple2<String, String> record : expectedRecords) { assertThat(resultMap).containsEntry(record.f0, record.f1); } } } | java |
(textLine.isDirectionLTR() == (hitCharIndex == -1)) { visIndex = 0; } else { visIndex = characterCount-1; } charIndex = textLine.visualToLogical(visIndex); if (textLine.isDirectionLTR() == (hitCharIndex == -1)) { // at left end leading = textLine.isCharLTR(charIndex); } else { // at right end leading = !textLine.isCharLTR(charIndex); } } else { int visIndex = textLine.logicalToVisual(hitCharIndex); boolean movedToRight; if (textLine.isCharLTR(hitCharIndex) == hit.isLeadingEdge()) { --visIndex; movedToRight = false; } else { ++visIndex; movedToRight = true; } if (visIndex > -1 && visIndex < characterCount) { charIndex = textLine.visualToLogical(visIndex); leading = movedToRight == textLine.isCharLTR(charIndex); } else { charIndex = (movedToRight == textLine.isDirectionLTR())? characterCount : -1; leading = charIndex == characterCount; } } return leading? TextHitInfo.leading(charIndex) : TextHitInfo.trailing(charIndex); } private double[] getCaretPath(TextHitInfo hit, Rectangle2D bounds) { float[] info = getCaretInfo(hit, bounds); return new double[] { info[2], info[3], info[4], info[5] }; } /** * Return an array of four floats corresponding the endpoints of the caret * x0, y0, x1, y1. * * This creates a line along the slope of the caret intersecting the * baseline at the caret * position, and extending from ascent above the baseline to descent below * it. */ private double[] getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds) { float[] info = getCaretInfo(caret, bounds, null); double pos = info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean <mask> <mask> <mask> <mask> = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { <mask> <mask> <mask> <mask> = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { <mask> <mask> <mask> <mask> = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { <mask> <mask> <mask> <mask> = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else | (textLine.isDirectionLTR() == (hitCharIndex == -1)) { visIndex = 0; } else { visIndex = characterCount-1; } charIndex = textLine.visualToLogical(visIndex); if (textLine.isDirectionLTR() == (hitCharIndex == -1)) { // at left end leading = textLine.isCharLTR(charIndex); } else { // at right end leading = !textLine.isCharLTR(charIndex); } } else { int visIndex = textLine.logicalToVisual(hitCharIndex); boolean movedToRight; if (textLine.isCharLTR(hitCharIndex) == hit.isLeadingEdge()) { --visIndex; movedToRight = false; } else { ++visIndex; movedToRight = true; } if (visIndex > -1 && visIndex < characterCount) { charIndex = textLine.visualToLogical(visIndex); leading = movedToRight == textLine.isCharLTR(charIndex); } else { charIndex = (movedToRight == textLine.isDirectionLTR())? characterCount : -1; leading = charIndex == characterCount; } } return leading? TextHitInfo.leading(charIndex) : TextHitInfo.trailing(charIndex); } private double[] getCaretPath(TextHitInfo hit, Rectangle2D bounds) { float[] info = getCaretInfo(hit, bounds); return new double[] { info[2], info[3], info[4], info[5] }; } /** * Return an array of four floats corresponding the endpoints of the caret * x0, y0, x1, y1. * * This creates a line along the slope of the caret intersecting the * baseline at the caret * position, and extending from ascent above the baseline to descent below * it. */ private double[] getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds) { float[] info = getCaretInfo(caret, bounds, null); double pos = info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean threePoints = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { threePoints = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { threePoints = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { threePoints = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else | java |
(visIndex > -1 && visIndex < characterCount) { charIndex = textLine.visualToLogical(visIndex); leading = movedToRight == textLine.isCharLTR(charIndex); } else { charIndex = (movedToRight == textLine.isDirectionLTR())? characterCount : -1; leading = charIndex == characterCount; } } return leading? TextHitInfo.leading(charIndex) : TextHitInfo.trailing(charIndex); } private double[] getCaretPath(TextHitInfo hit, Rectangle2D bounds) { float[] info = getCaretInfo(hit, bounds); return new double[] { info[2], info[3], info[4], info[5] }; } /** * Return an array of four floats corresponding the endpoints of the caret * x0, y0, x1, y1. * * This creates a line along the slope of the caret intersecting the * baseline at the caret * position, and extending from ascent above the baseline to descent below * it. */ private double[] getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds) { float[] info = getCaretInfo(caret, bounds, null); double pos = info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean <mask> <mask> <mask> <mask> = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { <mask> <mask> <mask> <mask> = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { <mask> <mask> <mask> <mask> = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { <mask> <mask> <mask> <mask> = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { <mask> <mask> <mask> <mask> = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return <mask> <mask> <mask> <mask> ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) | (visIndex > -1 && visIndex < characterCount) { charIndex = textLine.visualToLogical(visIndex); leading = movedToRight == textLine.isCharLTR(charIndex); } else { charIndex = (movedToRight == textLine.isDirectionLTR())? characterCount : -1; leading = charIndex == characterCount; } } return leading? TextHitInfo.leading(charIndex) : TextHitInfo.trailing(charIndex); } private double[] getCaretPath(TextHitInfo hit, Rectangle2D bounds) { float[] info = getCaretInfo(hit, bounds); return new double[] { info[2], info[3], info[4], info[5] }; } /** * Return an array of four floats corresponding the endpoints of the caret * x0, y0, x1, y1. * * This creates a line along the slope of the caret intersecting the * baseline at the caret * position, and extending from ascent above the baseline to descent below * it. */ private double[] getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds) { float[] info = getCaretInfo(caret, bounds, null); double pos = info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean threePoints = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { threePoints = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { threePoints = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { threePoints = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { threePoints = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return threePoints ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) | java |
info = getCaretInfo(hit, bounds); return new double[] { info[2], info[3], info[4], info[5] }; } /** * Return an array of four floats corresponding the endpoints of the caret * x0, y0, x1, y1. * * This creates a line along the slope of the caret intersecting the * baseline at the caret * position, and extending from ascent above the baseline to descent below * it. */ private double[] getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds) { float[] info = getCaretInfo(caret, bounds, null); double pos = info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean <mask> <mask> <mask> <mask> = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { <mask> <mask> <mask> <mask> = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { <mask> <mask> <mask> <mask> = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { <mask> <mask> <mask> <mask> = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { <mask> <mask> <mask> <mask> = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return <mask> <mask> <mask> <mask> ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate | info = getCaretInfo(hit, bounds); return new double[] { info[2], info[3], info[4], info[5] }; } /** * Return an array of four floats corresponding the endpoints of the caret * x0, y0, x1, y1. * * This creates a line along the slope of the caret intersecting the * baseline at the caret * position, and extending from ascent above the baseline to descent below * it. */ private double[] getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds) { float[] info = getCaretInfo(caret, bounds, null); double pos = info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean threePoints = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { threePoints = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { threePoints = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { threePoints = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { threePoints = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return threePoints ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate | java |
info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean <mask> <mask> <mask> <mask> = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { <mask> <mask> <mask> <mask> = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { <mask> <mask> <mask> <mask> = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { <mask> <mask> <mask> <mask> = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { <mask> <mask> <mask> <mask> = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return <mask> <mask> <mask> <mask> ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate the caret * @param bounds the bounds of the {@code TextLayout} to use * in generating the caret. The bounds is in baseline-relative * coordinates. * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) { ensureCache(); checkTextHit(hit); if (bounds == null) { throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()"); } return pathToShape(getCaretPath(hit, bounds), false, textLine.getLayoutPath()); } /** * Returns a {@code Shape} representing the caret at the specified * hit inside | info[0]; double slope = info[1]; double x0, y0, x1, y1; double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy double left = bounds.getX(); double right = left + bounds.getWidth(); double top = bounds.getY(); double bottom = top + bounds.getHeight(); boolean threePoints = false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { threePoints = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { threePoints = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { threePoints = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { threePoints = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return threePoints ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate the caret * @param bounds the bounds of the {@code TextLayout} to use * in generating the caret. The bounds is in baseline-relative * coordinates. * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) { ensureCache(); checkTextHit(hit); if (bounds == null) { throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()"); } return pathToShape(getCaretPath(hit, bounds), false, textLine.getLayoutPath()); } /** * Returns a {@code Shape} representing the caret at the specified * hit inside | java |
false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { <mask> <mask> <mask> <mask> = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { <mask> <mask> <mask> <mask> = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { <mask> <mask> <mask> <mask> = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { <mask> <mask> <mask> <mask> = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return <mask> <mask> <mask> <mask> ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate the caret * @param bounds the bounds of the {@code TextLayout} to use * in generating the caret. The bounds is in baseline-relative * coordinates. * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) { ensureCache(); checkTextHit(hit); if (bounds == null) { throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()"); } return pathToShape(getCaretPath(hit, bounds), false, textLine.getLayoutPath()); } /** * Returns a {@code Shape} representing the caret at the specified * hit inside the natural bounds of this {@code TextLayout}. * @param hit the hit at which to generate the caret * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit) { return getCaretShape(hit, getNaturalBounds()); } /** * Return the | false; if (isVerticalLine) { if (slope >= 0) { x0 = left; x1 = right; } else { x1 = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { threePoints = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { threePoints = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { threePoints = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { threePoints = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return threePoints ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate the caret * @param bounds the bounds of the {@code TextLayout} to use * in generating the caret. The bounds is in baseline-relative * coordinates. * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) { ensureCache(); checkTextHit(hit); if (bounds == null) { throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()"); } return pathToShape(getCaretPath(hit, bounds), false, textLine.getLayoutPath()); } /** * Returns a {@code Shape} representing the caret at the specified * hit inside the natural bounds of this {@code TextLayout}. * @param hit the hit at which to generate the caret * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit) { return getCaretShape(hit, getNaturalBounds()); } /** * Return the | java |
= left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { <mask> <mask> <mask> <mask> = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { <mask> <mask> <mask> <mask> = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { <mask> <mask> <mask> <mask> = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { <mask> <mask> <mask> <mask> = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return <mask> <mask> <mask> <mask> ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate the caret * @param bounds the bounds of the {@code TextLayout} to use * in generating the caret. The bounds is in baseline-relative * coordinates. * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) { ensureCache(); checkTextHit(hit); if (bounds == null) { throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()"); } return pathToShape(getCaretPath(hit, bounds), false, textLine.getLayoutPath()); } /** * Returns a {@code Shape} representing the caret at the specified * hit inside the natural bounds of this {@code TextLayout}. * @param hit the hit at which to generate the caret * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit) { return getCaretShape(hit, getNaturalBounds()); } /** * Return the "stronger" of the TextHitInfos. The TextHitInfos * should be logical or visual counterparts. They are not * checked for | = left; x0 = right; } y0 = pos + x0 * slope; y1 = pos + x1 * slope; // y0 <= y1, always if (clipToBounds) { if (y0 < top) { if (slope <= 0 || y1 <= top) { y0 = y1 = top; } else { threePoints = true; y0 = top; y2 = top; x2 = x1 + (top-y1)/slope; if (y1 > bottom) { y1 = bottom; } } } else if (y1 > bottom) { if (slope >= 0 || y0 >= bottom) { y0 = y1 = bottom; } else { threePoints = true; y1 = bottom; y2 = bottom; x2 = x0 + (bottom-x1)/slope; } } } } else { if (slope >= 0) { y0 = bottom; y1 = top; } else { y1 = bottom; y0 = top; } x0 = pos - y0 * slope; x1 = pos - y1 * slope; // x0 <= x1, always if (clipToBounds) { if (x0 < left) { if (slope <= 0 || x1 <= left) { x0 = x1 = left; } else { threePoints = true; x0 = left; x2 = left; y2 = y1 - (left-x1)/slope; if (x1 > right) { x1 = right; } } } else if (x1 > right) { if (slope >= 0 || x0 >= right) { x0 = x1 = right; } else { threePoints = true; x1 = right; x2 = right; y2 = y0 - (right-x0)/slope; } } } } return threePoints ? new double[] { x0, y0, x2, y2, x1, y1 } : new double[] { x0, y0, x1, y1 }; } private static GeneralPath pathToShape(double[] path, boolean close, LayoutPathImpl lp) { GeneralPath result = new GeneralPath(GeneralPath.WIND_EVEN_ODD, path.length); result.moveTo((float)path[0], (float)path[1]); for (int i = 2; i < path.length; i += 2) { result.lineTo((float)path[i], (float)path[i+1]); } if (close) { result.closePath(); } if (lp != null) { result = (GeneralPath)lp.mapShape(result); } return result; } /** * Returns a {@link Shape} representing the caret at the specified * hit inside the specified bounds. * @param hit the hit at which to generate the caret * @param bounds the bounds of the {@code TextLayout} to use * in generating the caret. The bounds is in baseline-relative * coordinates. * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) { ensureCache(); checkTextHit(hit); if (bounds == null) { throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()"); } return pathToShape(getCaretPath(hit, bounds), false, textLine.getLayoutPath()); } /** * Returns a {@code Shape} representing the caret at the specified * hit inside the natural bounds of this {@code TextLayout}. * @param hit the hit at which to generate the caret * @return a {@code Shape} representing the caret. The returned * shape is in standard coordinates. */ public Shape getCaretShape(TextHitInfo hit) { return getCaretShape(hit, getNaturalBounds()); } /** * Return the "stronger" of the TextHitInfos. The TextHitInfos * should be logical or visual counterparts. They are not * checked for | java |
GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent <mask> <mask> <mask> <mask> = new MyEvent(); <mask> <mask> <mask> <mask> .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, <mask> <mask> <mask> <mask> ); } } private static void testGetField(RecordedEvent event, MyEvent <mask> <mask> <mask> <mask> ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, <mask> <mask> <mask> <mask> .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, <mask> <mask> <mask> <mask> .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, <mask> <mask> <mask> <mask> .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, <mask> <mask> <mask> <mask> .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, <mask> <mask> <mask> <mask> .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, <mask> <mask> <mask> <mask> .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, <mask> <mask> <mask> <mask> .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, <mask> <mask> <mask> <mask> .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, <mask> <mask> <mask> <mask> .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), <mask> <mask> <mask> <mask> .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), <mask> <mask> <mask> <mask> .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer; import java.util.List; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedThread; import jdk.test.lib.Asserts; import jdk.test.lib.jfr.Events; /** * @test * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.TestFieldAccess */ public class TestFieldAccess { private static class MyEvent extends Event { byte byteField = 42; char charField = 'X'; String stringField = "Hello"; int intField = 4711; long longField = 4712L; short shortField = (short)67; double doubleField = Double.NaN; float floatField = Float.MIN_VALUE; boolean booleanField = false; Thread threadField = Thread.currentThread(); Class<?> classField = MyEvent.class; } public static void main(String[] args) throws Throwable { try (Recording r = new Recording()) { r.enable(MyEvent.class); r.start(); MyEvent myEvent = new MyEvent(); myEvent .commit(); r.stop(); List<RecordedEvent> events = Events.fromRecording(r); Events.hasEvents(events); RecordedEvent event = events.getFirst(); testHasField(event); testGetField(event, myEvent ); } } private static void testGetField(RecordedEvent event, MyEvent myEvent ) { char charField = event.getValue("charField"); Asserts.assertEquals(charField, myEvent .charField); byte byteField = event.getValue("byteField"); Asserts.assertEquals(byteField, myEvent .byteField); String stringField = event.getValue("stringField"); Asserts.assertEquals(stringField, myEvent .stringField); int intField = event.getValue("intField"); Asserts.assertEquals(intField, myEvent .intField); long longField = event.getValue("longField"); Asserts.assertEquals(longField, myEvent .longField); short shortField = event.getValue("shortField"); Asserts.assertEquals(shortField, myEvent .shortField); double doubleField = event.getValue("doubleField"); Asserts.assertEquals(doubleField, myEvent .doubleField); float floatField = event.getValue("floatField"); Asserts.assertEquals(floatField, myEvent .floatField); boolean booleanField = event.getValue("booleanField"); Asserts.assertEquals(booleanField, myEvent .booleanField); RecordedThread threadField = event.getValue("eventThread"); Asserts.assertEquals(threadField.getJavaName(), myEvent .threadField.getName()); String threadGroupName = event.getValue("eventThread.group.name"); Asserts.assertEquals(threadField.getThreadGroup().getName(), threadGroupName); RecordedClass classField = event.getValue("classField"); Asserts.assertEquals(classField.getName(), myEvent .classField.getName()); String className = event.getValue("classField.name"); Asserts.assertEquals(classField.getName(), className.replace("/", ".")); try { event.getValue("doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue("classField.doesnotexist"); } catch (IllegalArgumentException iae) { // as expected } try { event.getValue(null); } catch (NullPointerException npe) { // as expected } } private static void testHasField(RecordedEvent event) { System.out.println(event); Asserts.assertTrue(event.hasField("charField")); Asserts.assertTrue(event.hasField("byteField")); Asserts.assertTrue(event.hasField("stringField")); Asserts.assertTrue(event.hasField("intField")); Asserts.assertTrue(event.hasField("longField")); Asserts.assertTrue(event.hasField("shortField")); Asserts.assertTrue(event.hasField("doubleField")); Asserts.assertTrue(event.hasField("floatField")); Asserts.assertTrue(event.hasField("threadField")); Asserts.assertTrue(event.hasField("classField")); Asserts.assertTrue(event.hasField("classField.name")); Asserts.assertTrue(event.hasField("eventThread")); Asserts.assertTrue(event.hasField("eventThread.group.name")); Asserts.assertTrue(event.hasField("startTime")); Asserts.assertTrue(event.hasField("stackTrace")); Asserts.assertTrue(event.hasField("duration")); Asserts.assertFalse(event.hasField("doesNotExist")); Asserts.assertFalse(event.hasField("classField.doesNotExist")); Asserts.assertFalse(event.hasField("")); try { event.hasField(null); } catch (NullPointerException npe) { // as expected } } } | java |
package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. <mask> <mask> <mask> <mask> .context.ApplicationContext; import org. <mask> <mask> <mask> <mask> .context.ApplicationEvent; import org. <mask> <mask> <mask> <mask> .context.ApplicationEventPublisher; import org. <mask> <mask> <mask> <mask> .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. springframework .context.ApplicationContext; import org. springframework .context.ApplicationEvent; import org. springframework .context.ApplicationEventPublisher; import org. springframework .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | java |
package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. <mask> <mask> <mask> <mask> .context.ApplicationContext; import org. <mask> <mask> <mask> <mask> .context.ApplicationEvent; import org. <mask> <mask> <mask> <mask> .context.ApplicationEventPublisher; import org. <mask> <mask> <mask> <mask> .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. springframework .context.ApplicationContext; import org. springframework .context.ApplicationEvent; import org. springframework .context.ApplicationEventPublisher; import org. springframework .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | java |
package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. <mask> <mask> <mask> <mask> .context.ApplicationContext; import org. <mask> <mask> <mask> <mask> .context.ApplicationEvent; import org. <mask> <mask> <mask> <mask> .context.ApplicationEventPublisher; import org. <mask> <mask> <mask> <mask> .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. springframework .context.ApplicationContext; import org. springframework .context.ApplicationEvent; import org. springframework .context.ApplicationEventPublisher; import org. springframework .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | java |
package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. <mask> <mask> <mask> <mask> .context.ApplicationContext; import org. <mask> <mask> <mask> <mask> .context.ApplicationEvent; import org. <mask> <mask> <mask> <mask> .context.ApplicationEventPublisher; import org. <mask> <mask> <mask> <mask> .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | package run.halo.app.plugin; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.pf4j.PluginManager; import org.pf4j.PluginWrapper; import org. springframework .context.ApplicationContext; import org. springframework .context.ApplicationEvent; import org. springframework .context.ApplicationEventPublisher; import org. springframework .context.Lifecycle; @ExtendWith(MockitoExtension.class) class SharedEventDispatcherTest { @Mock PluginManager pluginManager; @Mock ApplicationEventPublisher publisher; @InjectMocks SharedEventDispatcher dispatcher; @Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); } @Test void shouldDispatchEventToAllStartedPlugins() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(true); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context).publishEvent(new HaloSharedEventDelegator(dispatcher, event)); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotRunning() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class, withSettings().extraInterfaces(Lifecycle.class)); when(((Lifecycle) context).isRunning()).thenReturn(false); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() { var pw = mock(PluginWrapper.class); var plugin = mock(SpringPlugin.class); var context = mock(ApplicationContext.class); when(plugin.getApplicationContext()).thenReturn(context); when(pw.getPlugin()).thenReturn(plugin); when(pluginManager.getStartedPlugins()).thenReturn(List.of(pw)); var event = new FakeSharedEvent(this); dispatcher.onApplicationEvent(event); verify(context, never()).publishEvent(event); } @Test void shouldUnwrapPluginSharedEventAndRepublish() { var event = new PluginSharedEventDelegator(this, new FakeSharedEvent(this)); dispatcher.onApplicationEvent(event); verify(publisher).publishEvent(event.getDelegate()); } class FakeEvent extends ApplicationEvent { public FakeEvent(Object source) { super(source); } } @SharedEvent class FakeSharedEvent extends ApplicationEvent { public FakeSharedEvent(Object source) { super(source); } } } | java |
left in the original loop or the loop is inverted " + loop; for (SafepointNode safepoint : loop.whole().nodes().filter(SafepointNode.class)) { graph().removeFixed(safepoint); } StructuredGraph graph = mainLoopBegin.graph(); if (opaqueUnrolledStrides != null) { OpaqueNode opaque = opaqueUnrolledStrides.get(loop.loopBegin()); CountedLoopInfo counted = loop.counted(); ValueNode counterStride = counted.getLimitCheckedIV().strideNode(); if (opaque == null || opaque.isDeleted()) { ValueNode limit = counted.getLimit(); opaque = new OpaqueValueNode(AddNode.add(counterStride, counterStride, NodeView.DEFAULT)); ValueNode newLimit = partialUnrollOverflowCheck(opaque, limit, counted); GraalError.guarantee(condition.hasExactlyOneUsage(), "Unrolling loop %s with condition %s, which has multiple usages. Usages other than the loop exit check would get an incorrect condition.", loop.loopBegin(), condition); condition.replaceFirstInput(limit, graph.addOrUniqueWithInputs(newLimit)); opaqueUnrolledStrides.put(loop.loopBegin(), opaque); } else { assert counted.getLimitCheckedIV().isConstantStride(); assert !LoopTransformations.strideAdditionOverflows(loop) : "Stride addition must not overflow"; ValueNode previousValue = opaque.getValue(); opaque.setValue(graph.addOrUniqueWithInputs(AddNode.add(counterStride, previousValue, NodeView.DEFAULT))); GraphUtil.tryKillUnused(previousValue); } } mainLoopBegin.setUnrollFactor(mainLoopBegin.getUnrollFactor() * 2); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "LoopPartialUnroll %s", loop); mainLoopBegin.getDebug().dump(DebugContext.VERBOSE_LEVEL, mainLoopBegin.graph(), "After insertWithinAfter %s", mainLoopBegin); } public static ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). | left in the original loop or the loop is inverted " + loop; for (SafepointNode safepoint : loop.whole().nodes().filter(SafepointNode.class)) { graph().removeFixed(safepoint); } StructuredGraph graph = mainLoopBegin.graph(); if (opaqueUnrolledStrides != null) { OpaqueNode opaque = opaqueUnrolledStrides.get(loop.loopBegin()); CountedLoopInfo counted = loop.counted(); ValueNode counterStride = counted.getLimitCheckedIV().strideNode(); if (opaque == null || opaque.isDeleted()) { ValueNode limit = counted.getLimit(); opaque = new OpaqueValueNode(AddNode.add(counterStride, counterStride, NodeView.DEFAULT)); ValueNode newLimit = partialUnrollOverflowCheck(opaque, limit, counted); GraalError.guarantee(condition.hasExactlyOneUsage(), "Unrolling loop %s with condition %s, which has multiple usages. Usages other than the loop exit check would get an incorrect condition.", loop.loopBegin(), condition); condition.replaceFirstInput(limit, graph.addOrUniqueWithInputs(newLimit)); opaqueUnrolledStrides.put(loop.loopBegin(), opaque); } else { assert counted.getLimitCheckedIV().isConstantStride(); assert !LoopTransformations.strideAdditionOverflows(loop) : "Stride addition must not overflow"; ValueNode previousValue = opaque.getValue(); opaque.setValue(graph.addOrUniqueWithInputs(AddNode.add(counterStride, previousValue, NodeView.DEFAULT))); GraphUtil.tryKillUnused(previousValue); } } mainLoopBegin.setUnrollFactor(mainLoopBegin.getUnrollFactor() * 2); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "LoopPartialUnroll %s", loop); mainLoopBegin.getDebug().dump(DebugContext.VERBOSE_LEVEL, mainLoopBegin.graph(), "After insertWithinAfter %s", mainLoopBegin); } public static ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). | java |
{ OpaqueNode opaque = opaqueUnrolledStrides.get(loop.loopBegin()); CountedLoopInfo counted = loop.counted(); ValueNode counterStride = counted.getLimitCheckedIV().strideNode(); if (opaque == null || opaque.isDeleted()) { ValueNode limit = counted.getLimit(); opaque = new OpaqueValueNode(AddNode.add(counterStride, counterStride, NodeView.DEFAULT)); ValueNode newLimit = partialUnrollOverflowCheck(opaque, limit, counted); GraalError.guarantee(condition.hasExactlyOneUsage(), "Unrolling loop %s with condition %s, which has multiple usages. Usages other than the loop exit check would get an incorrect condition.", loop.loopBegin(), condition); condition.replaceFirstInput(limit, graph.addOrUniqueWithInputs(newLimit)); opaqueUnrolledStrides.put(loop.loopBegin(), opaque); } else { assert counted.getLimitCheckedIV().isConstantStride(); assert !LoopTransformations.strideAdditionOverflows(loop) : "Stride addition must not overflow"; ValueNode previousValue = opaque.getValue(); opaque.setValue(graph.addOrUniqueWithInputs(AddNode.add(counterStride, previousValue, NodeView.DEFAULT))); GraphUtil.tryKillUnused(previousValue); } } mainLoopBegin.setUnrollFactor(mainLoopBegin.getUnrollFactor() * 2); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "LoopPartialUnroll %s", loop); mainLoopBegin.getDebug().dump(DebugContext.VERBOSE_LEVEL, mainLoopBegin.graph(), "After insertWithinAfter %s", mainLoopBegin); } public static ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else | { OpaqueNode opaque = opaqueUnrolledStrides.get(loop.loopBegin()); CountedLoopInfo counted = loop.counted(); ValueNode counterStride = counted.getLimitCheckedIV().strideNode(); if (opaque == null || opaque.isDeleted()) { ValueNode limit = counted.getLimit(); opaque = new OpaqueValueNode(AddNode.add(counterStride, counterStride, NodeView.DEFAULT)); ValueNode newLimit = partialUnrollOverflowCheck(opaque, limit, counted); GraalError.guarantee(condition.hasExactlyOneUsage(), "Unrolling loop %s with condition %s, which has multiple usages. Usages other than the loop exit check would get an incorrect condition.", loop.loopBegin(), condition); condition.replaceFirstInput(limit, graph.addOrUniqueWithInputs(newLimit)); opaqueUnrolledStrides.put(loop.loopBegin(), opaque); } else { assert counted.getLimitCheckedIV().isConstantStride(); assert !LoopTransformations.strideAdditionOverflows(loop) : "Stride addition must not overflow"; ValueNode previousValue = opaque.getValue(); opaque.setValue(graph.addOrUniqueWithInputs(AddNode.add(counterStride, previousValue, NodeView.DEFAULT))); GraphUtil.tryKillUnused(previousValue); } } mainLoopBegin.setUnrollFactor(mainLoopBegin.getUnrollFactor() * 2); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "LoopPartialUnroll %s", loop); mainLoopBegin.getDebug().dump(DebugContext.VERBOSE_LEVEL, mainLoopBegin.graph(), "After insertWithinAfter %s", mainLoopBegin); } public static ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else | java |
if (opaque == null || opaque.isDeleted()) { ValueNode limit = counted.getLimit(); opaque = new OpaqueValueNode(AddNode.add(counterStride, counterStride, NodeView.DEFAULT)); ValueNode newLimit = partialUnrollOverflowCheck(opaque, limit, counted); GraalError.guarantee(condition.hasExactlyOneUsage(), "Unrolling loop %s with condition %s, which has multiple usages. Usages other than the loop exit check would get an incorrect condition.", loop.loopBegin(), condition); condition.replaceFirstInput(limit, graph.addOrUniqueWithInputs(newLimit)); opaqueUnrolledStrides.put(loop.loopBegin(), opaque); } else { assert counted.getLimitCheckedIV().isConstantStride(); assert !LoopTransformations.strideAdditionOverflows(loop) : "Stride addition must not overflow"; ValueNode previousValue = opaque.getValue(); opaque.setValue(graph.addOrUniqueWithInputs(AddNode.add(counterStride, previousValue, NodeView.DEFAULT))); GraphUtil.tryKillUnused(previousValue); } } mainLoopBegin.setUnrollFactor(mainLoopBegin.getUnrollFactor() * 2); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "LoopPartialUnroll %s", loop); mainLoopBegin.getDebug().dump(DebugContext.VERBOSE_LEVEL, mainLoopBegin.graph(), "After insertWithinAfter %s", mainLoopBegin); } public static ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) | if (opaque == null || opaque.isDeleted()) { ValueNode limit = counted.getLimit(); opaque = new OpaqueValueNode(AddNode.add(counterStride, counterStride, NodeView.DEFAULT)); ValueNode newLimit = partialUnrollOverflowCheck(opaque, limit, counted); GraalError.guarantee(condition.hasExactlyOneUsage(), "Unrolling loop %s with condition %s, which has multiple usages. Usages other than the loop exit check would get an incorrect condition.", loop.loopBegin(), condition); condition.replaceFirstInput(limit, graph.addOrUniqueWithInputs(newLimit)); opaqueUnrolledStrides.put(loop.loopBegin(), opaque); } else { assert counted.getLimitCheckedIV().isConstantStride(); assert !LoopTransformations.strideAdditionOverflows(loop) : "Stride addition must not overflow"; ValueNode previousValue = opaque.getValue(); opaque.setValue(graph.addOrUniqueWithInputs(AddNode.add(counterStride, previousValue, NodeView.DEFAULT))); GraphUtil.tryKillUnused(previousValue); } } mainLoopBegin.setUnrollFactor(mainLoopBegin.getUnrollFactor() * 2); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "LoopPartialUnroll %s", loop); mainLoopBegin.getDebug().dump(DebugContext.VERBOSE_LEVEL, mainLoopBegin.graph(), "After insertWithinAfter %s", mainLoopBegin); } public static ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) | java |
ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { | ValueNode partialUnrollOverflowCheck(OpaqueNode opaque, ValueNode limit, CountedLoopInfo counted) { int bits = ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { | java |
((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } | ((IntegerStamp) limit.stamp(NodeView.DEFAULT)).getBits(); ValueNode newLimit = SubNode.create(limit, opaque, NodeView.DEFAULT); IntegerHelper helper = counted.getCounterIntegerHelper(); LogicNode overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } | java |
overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here | overflowCheck; ConstantNode extremum; if (counted.getDirection() == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here | java |
== InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof | == InductionVariable.Direction.Up) { // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof | java |
// limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo <mask> <mask> <mask> <mask> <mask> = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = <mask> <mask> <mask> <mask> <mask> .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, <mask> <mask> <mask> <mask> <mask> , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == <mask> <mask> <mask> <mask> <mask> .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( <mask> <mask> <mask> <mask> <mask> .getBody().next() instanceof LoopEndNode && <mask> <mask> <mask> <mask> <mask> .getLimitTest().predecessor() == <mask> <mask> <mask> <mask> <mask> .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof SafepointNode)).count() == 0 | // limit - counterStride could overflow negatively if limit - min < // counterStride extremum = ConstantNode.forIntegerBits(bits, helper.minValue()); overflowCheck = IntegerBelowNode.create(SubNode.create(limit, extremum, NodeView.DEFAULT), opaque, NodeView.DEFAULT); } else { assert counted.getDirection() == InductionVariable.Direction.Down : counted.getDirection(); // limit - counterStride could overflow if max - limit < -counterStride // i.e., counterStride < limit - max extremum = ConstantNode.forIntegerBits(bits, helper.maxValue()); overflowCheck = IntegerBelowNode.create(opaque, SubNode.create(limit, extremum, NodeView.DEFAULT), NodeView.DEFAULT); } return ConditionalNode.create(overflowCheck, extremum, newLimit, NodeView.DEFAULT); } protected CompareNode placeNewSegmentAndCleanup(Loop loop, EconomicMap<Node, Node> new2OldPhis, @SuppressWarnings("unused") EconomicMap<Node, Node> originalPhi2Backedges) { CountedLoopInfo mainCounted = loop.counted(); LoopBeginNode mainLoopBegin = loop.loopBegin(); // Discard the segment entry and its flow, after if merging it into the loop StructuredGraph graph = mainLoopBegin.graph(); IfNode loopTest = mainCounted .getLimitTest(); IfNode newSegmentLoopTest = getDuplicatedNode(loopTest); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After duplicating segment"); if ( mainCounted .getBody() != loop.loopBegin()) { // regular loop Node predecessor = newSegmentLoopTest.predecessor(); while (predecessor instanceof FixedWithNextNode fixedPredecessor) { for (Node usage : fixedPredecessor.usages().snapshot()) { usage.replaceFirstInput(fixedPredecessor, loopTest.predecessor()); } predecessor = fixedPredecessor.predecessor(); } AbstractBeginNode falseSuccessor = newSegmentLoopTest.falseSuccessor(); for (Node usage : falseSuccessor.anchored().snapshot()) { usage.replaceFirstInput(falseSuccessor, loopTest.falseSuccessor()); } AbstractBeginNode trueSuccessor = newSegmentLoopTest.trueSuccessor(); for (Node usage : trueSuccessor.anchored().snapshot()) { usage.replaceFirstInput(trueSuccessor, loopTest.trueSuccessor()); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After stitching new segment into control flow after existing one"); assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) || mainLoopBegin.loopExits().count() <= 1 : "Can only merge early loop exits if graph has value proxies " + mainLoopBegin; mergeEarlyLoopExits(graph, mainLoopBegin, mainCounted , new2OldPhis, loop); // remove if test graph.removeSplitPropagate(newSegmentLoopTest, loopTest.trueSuccessor() == mainCounted .getBody() ? trueSuccessor : falseSuccessor); graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "Before placing segment"); if ( mainCounted .getBody().next() instanceof LoopEndNode && mainCounted .getLimitTest().predecessor() == mainCounted .loop.loopBegin()) { /** * We assume here that the body of the loop is completely empty, i.e., we assume * that there is no control flow in the counted loop body. This however means that * we also did not have any code between the loop header and the counted begin (we * allow a few special nodes there). Else we would be killing nodes that are as well * between - that potentially could be used by loop phis (which we also disallow). * Thus, just be safe here and ensure we really see the pattern we are expect namely * a completely empty (fixed nodes) loop body. */ GraphUtil.killCFG(getDuplicatedNode(mainLoopBegin)); } else { AbstractBeginNode newSegmentBegin = getDuplicatedNode(mainLoopBegin); FixedNode newSegmentFirstNode = newSegmentBegin.next(); EndNode newSegmentEnd = getBlockEnd((FixedNode) getDuplicatedNode(mainLoopBegin.loopEnds().first().predecessor())); FixedWithNextNode newSegmentLastNode = (FixedWithNextNode) newSegmentEnd.predecessor(); LoopEndNode loopEndNode = mainLoopBegin.getSingleLoopEnd(); FixedWithNextNode lastCodeNode = (FixedWithNextNode) loopEndNode.predecessor(); newSegmentBegin.clearSuccessors(); if (newSegmentBegin.hasAnchored()) { /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof SafepointNode)).count() == 0 | java |
/* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof SafepointNode)).count() == 0 : "Must only have safepoint(association) usages left for " + newSegmentBegin + " usages=" + newSegmentBegin.usages(); newSegmentBegin.replaceAtUsages(mainLoopBegin, InputType.Association); } lastCodeNode.replaceFirstSuccessor(loopEndNode, newSegmentFirstNode); newSegmentLastNode.replaceFirstSuccessor(newSegmentEnd, loopEndNode); newSegmentBegin.safeDelete(); newSegmentEnd.safeDelete(); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After placing segment"); return (CompareNode) loopTest.condition(); } else { throw GraalError.shouldNotReachHere("Cannot unroll inverted loop"); // ExcludeFromJacocoGeneratedReport } } /** * * For counted loops we have a special nomenclature regarding loop exits, the counted loop exit * is the regular loop exit after all iterations finished, all other loop exits exit the loop * earlier, thus we call them early exits. * * Merge early, non-counted, loop exits of the loop for unrolling, this currently requires value * proxies to properly proxy all values along the way. * * Unrolling loops with multiple exits is special in the way the exits are handled. * Pre-Main-Post creation will merge them. */ protected void mergeEarlyLoopExits(StructuredGraph graph, LoopBeginNode mainLoopBegin, CountedLoopInfo <mask> <mask> <mask> <mask> <mask> , EconomicMap<Node, Node> new2OldPhis, Loop loop) { if (mainLoopBegin.loopExits().count() <= 1) { return; } assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) : "Unrolling with multiple exits requires proxies"; // rewire non-counted exits with the follow nodes: merges or sinks for (LoopExitNode exit : mainLoopBegin.loopExits().snapshot()) { // regular path along we unroll if (exit == <mask> <mask> <mask> <mask> <mask> .getCountedExit()) { continue; } FixedNode next = exit.next(); AbstractBeginNode begin = getDuplicatedNode(exit); if (next instanceof EndNode) { mergeRegularEarlyExit(next, begin, exit, mainLoopBegin, graph, new2OldPhis, loop); } else { GraalError.shouldNotReachHere("Can only unroll loops where the early exits which merge " + next + " duplicated node is " + begin + " main loop begin is " + mainLoopBegin); // ExcludeFromJacocoGeneratedReport } } } private void mergeRegularEarlyExit(FixedNode next, AbstractBeginNode exitBranchBegin, LoopExitNode oldExit, LoopBeginNode mainLoopBegin, StructuredGraph graph, EconomicMap<Node, Node> new2OldPhis, Loop loop) { AbstractMergeNode merge = ((EndNode) next).merge(); assert merge instanceof MergeNode : "Can only merge loop exits on regular merges"; assert exitBranchBegin.next() == null; LoopExitNode lex = graph.add(new LoopExitNode(mainLoopBegin)); createExitStateForNewSegmentEarlyExit(graph, oldExit, lex, new2OldPhis); EndNode end = graph.add(new EndNode()); exitBranchBegin.setNext(lex); lex.setNext(end); merge.addForwardEnd(end); for (PhiNode phi : merge.phis()) { ValueNode input = phi.valueAt((EndNode) next); ValueNode replacement; if (!loop.whole().contains(input)) { // node is produced above the loop replacement = input; } else { // if the node is inside this loop the input must be a proxy replacement = patchProxyAtPhi(phi, lex, getNodeInExitPathFromUnrolledSegment((ProxyNode) input, new2OldPhis)); } phi.addInput(replacement); } } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput) { return patchProxyAtPhi(phi, lex, proxyInput, false); } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput, boolean unrestrictedStamp) | /* * LoopPartialUnrollPhase runs after guard lowering, thus we cannot see any * floating guards here except multi-guard nodes (pointing to abstract begins) * and other anchored nodes. We need to ensure anything anchored on the original * loop begin will be anchored on the unrolled iteration. Thus we create an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof SafepointNode)).count() == 0 : "Must only have safepoint(association) usages left for " + newSegmentBegin + " usages=" + newSegmentBegin.usages(); newSegmentBegin.replaceAtUsages(mainLoopBegin, InputType.Association); } lastCodeNode.replaceFirstSuccessor(loopEndNode, newSegmentFirstNode); newSegmentLastNode.replaceFirstSuccessor(newSegmentEnd, loopEndNode); newSegmentBegin.safeDelete(); newSegmentEnd.safeDelete(); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After placing segment"); return (CompareNode) loopTest.condition(); } else { throw GraalError.shouldNotReachHere("Cannot unroll inverted loop"); // ExcludeFromJacocoGeneratedReport } } /** * * For counted loops we have a special nomenclature regarding loop exits, the counted loop exit * is the regular loop exit after all iterations finished, all other loop exits exit the loop * earlier, thus we call them early exits. * * Merge early, non-counted, loop exits of the loop for unrolling, this currently requires value * proxies to properly proxy all values along the way. * * Unrolling loops with multiple exits is special in the way the exits are handled. * Pre-Main-Post creation will merge them. */ protected void mergeEarlyLoopExits(StructuredGraph graph, LoopBeginNode mainLoopBegin, CountedLoopInfo mainCounted , EconomicMap<Node, Node> new2OldPhis, Loop loop) { if (mainLoopBegin.loopExits().count() <= 1) { return; } assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) : "Unrolling with multiple exits requires proxies"; // rewire non-counted exits with the follow nodes: merges or sinks for (LoopExitNode exit : mainLoopBegin.loopExits().snapshot()) { // regular path along we unroll if (exit == mainCounted .getCountedExit()) { continue; } FixedNode next = exit.next(); AbstractBeginNode begin = getDuplicatedNode(exit); if (next instanceof EndNode) { mergeRegularEarlyExit(next, begin, exit, mainLoopBegin, graph, new2OldPhis, loop); } else { GraalError.shouldNotReachHere("Can only unroll loops where the early exits which merge " + next + " duplicated node is " + begin + " main loop begin is " + mainLoopBegin); // ExcludeFromJacocoGeneratedReport } } } private void mergeRegularEarlyExit(FixedNode next, AbstractBeginNode exitBranchBegin, LoopExitNode oldExit, LoopBeginNode mainLoopBegin, StructuredGraph graph, EconomicMap<Node, Node> new2OldPhis, Loop loop) { AbstractMergeNode merge = ((EndNode) next).merge(); assert merge instanceof MergeNode : "Can only merge loop exits on regular merges"; assert exitBranchBegin.next() == null; LoopExitNode lex = graph.add(new LoopExitNode(mainLoopBegin)); createExitStateForNewSegmentEarlyExit(graph, oldExit, lex, new2OldPhis); EndNode end = graph.add(new EndNode()); exitBranchBegin.setNext(lex); lex.setNext(end); merge.addForwardEnd(end); for (PhiNode phi : merge.phis()) { ValueNode input = phi.valueAt((EndNode) next); ValueNode replacement; if (!loop.whole().contains(input)) { // node is produced above the loop replacement = input; } else { // if the node is inside this loop the input must be a proxy replacement = patchProxyAtPhi(phi, lex, getNodeInExitPathFromUnrolledSegment((ProxyNode) input, new2OldPhis)); } phi.addInput(replacement); } } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput) { return patchProxyAtPhi(phi, lex, proxyInput, false); } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput, boolean unrestrictedStamp) | java |
an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof SafepointNode)).count() == 0 : "Must only have safepoint(association) usages left for " + newSegmentBegin + " usages=" + newSegmentBegin.usages(); newSegmentBegin.replaceAtUsages(mainLoopBegin, InputType.Association); } lastCodeNode.replaceFirstSuccessor(loopEndNode, newSegmentFirstNode); newSegmentLastNode.replaceFirstSuccessor(newSegmentEnd, loopEndNode); newSegmentBegin.safeDelete(); newSegmentEnd.safeDelete(); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After placing segment"); return (CompareNode) loopTest.condition(); } else { throw GraalError.shouldNotReachHere("Cannot unroll inverted loop"); // ExcludeFromJacocoGeneratedReport } } /** * * For counted loops we have a special nomenclature regarding loop exits, the counted loop exit * is the regular loop exit after all iterations finished, all other loop exits exit the loop * earlier, thus we call them early exits. * * Merge early, non-counted, loop exits of the loop for unrolling, this currently requires value * proxies to properly proxy all values along the way. * * Unrolling loops with multiple exits is special in the way the exits are handled. * Pre-Main-Post creation will merge them. */ protected void mergeEarlyLoopExits(StructuredGraph graph, LoopBeginNode mainLoopBegin, CountedLoopInfo <mask> <mask> <mask> <mask> <mask> , EconomicMap<Node, Node> new2OldPhis, Loop loop) { if (mainLoopBegin.loopExits().count() <= 1) { return; } assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) : "Unrolling with multiple exits requires proxies"; // rewire non-counted exits with the follow nodes: merges or sinks for (LoopExitNode exit : mainLoopBegin.loopExits().snapshot()) { // regular path along we unroll if (exit == <mask> <mask> <mask> <mask> <mask> .getCountedExit()) { continue; } FixedNode next = exit.next(); AbstractBeginNode begin = getDuplicatedNode(exit); if (next instanceof EndNode) { mergeRegularEarlyExit(next, begin, exit, mainLoopBegin, graph, new2OldPhis, loop); } else { GraalError.shouldNotReachHere("Can only unroll loops where the early exits which merge " + next + " duplicated node is " + begin + " main loop begin is " + mainLoopBegin); // ExcludeFromJacocoGeneratedReport } } } private void mergeRegularEarlyExit(FixedNode next, AbstractBeginNode exitBranchBegin, LoopExitNode oldExit, LoopBeginNode mainLoopBegin, StructuredGraph graph, EconomicMap<Node, Node> new2OldPhis, Loop loop) { AbstractMergeNode merge = ((EndNode) next).merge(); assert merge instanceof MergeNode : "Can only merge loop exits on regular merges"; assert exitBranchBegin.next() == null; LoopExitNode lex = graph.add(new LoopExitNode(mainLoopBegin)); createExitStateForNewSegmentEarlyExit(graph, oldExit, lex, new2OldPhis); EndNode end = graph.add(new EndNode()); exitBranchBegin.setNext(lex); lex.setNext(end); merge.addForwardEnd(end); for (PhiNode phi : merge.phis()) { ValueNode input = phi.valueAt((EndNode) next); ValueNode replacement; if (!loop.whole().contains(input)) { // node is produced above the loop replacement = input; } else { // if the node is inside this loop the input must be a proxy replacement = patchProxyAtPhi(phi, lex, getNodeInExitPathFromUnrolledSegment((ProxyNode) input, new2OldPhis)); } phi.addInput(replacement); } } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput) { return patchProxyAtPhi(phi, lex, proxyInput, false); } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput, boolean unrestrictedStamp) { if (phi instanceof ValuePhiNode) { if (unrestrictedStamp) { /* * Delay precise stamp injection to the first time #inferStamp is called on the * value proxy. */ return phi.graph().addOrUnique(new ValueProxyNode(proxyInput.stamp(NodeView.DEFAULT).unrestricted(), proxyInput, lex)); } else { return phi.graph().addOrUnique(new ValueProxyNode(proxyInput, lex)); } } else if (phi instanceof MemoryPhiNode) { return phi.graph().addOrUnique(new | an * anchor point here ensuring nothing can flow above the original iteration. */ if (!(lastCodeNode instanceof GuardingNode) || !(lastCodeNode instanceof AnchoringNode)) { ValueAnchorNode newAnchoringPointAfterPrevIteration = graph.add(new ValueAnchorNode()); graph.addAfterFixed(lastCodeNode, newAnchoringPointAfterPrevIteration); lastCodeNode = newAnchoringPointAfterPrevIteration; } newSegmentBegin.replaceAtUsages(lastCodeNode, InputType.Guard, InputType.Anchor); // at this point only safepoint usages can live here assert newSegmentBegin.usages().filter(x -> !(x instanceof SafepointNode)).count() == 0 : "Must only have safepoint(association) usages left for " + newSegmentBegin + " usages=" + newSegmentBegin.usages(); newSegmentBegin.replaceAtUsages(mainLoopBegin, InputType.Association); } lastCodeNode.replaceFirstSuccessor(loopEndNode, newSegmentFirstNode); newSegmentLastNode.replaceFirstSuccessor(newSegmentEnd, loopEndNode); newSegmentBegin.safeDelete(); newSegmentEnd.safeDelete(); } graph.getDebug().dump(DebugContext.DETAILED_LEVEL, graph, "After placing segment"); return (CompareNode) loopTest.condition(); } else { throw GraalError.shouldNotReachHere("Cannot unroll inverted loop"); // ExcludeFromJacocoGeneratedReport } } /** * * For counted loops we have a special nomenclature regarding loop exits, the counted loop exit * is the regular loop exit after all iterations finished, all other loop exits exit the loop * earlier, thus we call them early exits. * * Merge early, non-counted, loop exits of the loop for unrolling, this currently requires value * proxies to properly proxy all values along the way. * * Unrolling loops with multiple exits is special in the way the exits are handled. * Pre-Main-Post creation will merge them. */ protected void mergeEarlyLoopExits(StructuredGraph graph, LoopBeginNode mainLoopBegin, CountedLoopInfo mainCounted , EconomicMap<Node, Node> new2OldPhis, Loop loop) { if (mainLoopBegin.loopExits().count() <= 1) { return; } assert graph.isBeforeStage(GraphState.StageFlag.VALUE_PROXY_REMOVAL) : "Unrolling with multiple exits requires proxies"; // rewire non-counted exits with the follow nodes: merges or sinks for (LoopExitNode exit : mainLoopBegin.loopExits().snapshot()) { // regular path along we unroll if (exit == mainCounted .getCountedExit()) { continue; } FixedNode next = exit.next(); AbstractBeginNode begin = getDuplicatedNode(exit); if (next instanceof EndNode) { mergeRegularEarlyExit(next, begin, exit, mainLoopBegin, graph, new2OldPhis, loop); } else { GraalError.shouldNotReachHere("Can only unroll loops where the early exits which merge " + next + " duplicated node is " + begin + " main loop begin is " + mainLoopBegin); // ExcludeFromJacocoGeneratedReport } } } private void mergeRegularEarlyExit(FixedNode next, AbstractBeginNode exitBranchBegin, LoopExitNode oldExit, LoopBeginNode mainLoopBegin, StructuredGraph graph, EconomicMap<Node, Node> new2OldPhis, Loop loop) { AbstractMergeNode merge = ((EndNode) next).merge(); assert merge instanceof MergeNode : "Can only merge loop exits on regular merges"; assert exitBranchBegin.next() == null; LoopExitNode lex = graph.add(new LoopExitNode(mainLoopBegin)); createExitStateForNewSegmentEarlyExit(graph, oldExit, lex, new2OldPhis); EndNode end = graph.add(new EndNode()); exitBranchBegin.setNext(lex); lex.setNext(end); merge.addForwardEnd(end); for (PhiNode phi : merge.phis()) { ValueNode input = phi.valueAt((EndNode) next); ValueNode replacement; if (!loop.whole().contains(input)) { // node is produced above the loop replacement = input; } else { // if the node is inside this loop the input must be a proxy replacement = patchProxyAtPhi(phi, lex, getNodeInExitPathFromUnrolledSegment((ProxyNode) input, new2OldPhis)); } phi.addInput(replacement); } } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput) { return patchProxyAtPhi(phi, lex, proxyInput, false); } public static ProxyNode patchProxyAtPhi(PhiNode phi, LoopExitNode lex, ValueNode proxyInput, boolean unrestrictedStamp) { if (phi instanceof ValuePhiNode) { if (unrestrictedStamp) { /* * Delay precise stamp injection to the first time #inferStamp is called on the * value proxy. */ return phi.graph().addOrUnique(new ValueProxyNode(proxyInput.stamp(NodeView.DEFAULT).unrestricted(), proxyInput, lex)); } else { return phi.graph().addOrUnique(new ValueProxyNode(proxyInput, lex)); } } else if (phi instanceof MemoryPhiNode) { return phi.graph().addOrUnique(new | java |
/* * Licensed 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 com.facebook. <mask> <mask> <mask> <mask> <mask> .hive.security; import com.facebook. <mask> <mask> <mask> <mask> <mask> .spi.connector.ConnectorAccessControl; import org.testng.annotations.Test; import static com.facebook. <mask> <mask> <mask> <mask> <mask> .spi.testing.InterfaceTestUtils.assertAllMethodsOverridden; public class TestSqlStandardAccessControl { @Test public void testEverythingImplemented() { assertAllMethodsOverridden(ConnectorAccessControl.class, SqlStandardAccessControl.class); } } | /* * Licensed 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 com.facebook. presto .hive.security; import com.facebook. presto .spi.connector.ConnectorAccessControl; import org.testng.annotations.Test; import static com.facebook. presto .spi.testing.InterfaceTestUtils.assertAllMethodsOverridden; public class TestSqlStandardAccessControl { @Test public void testEverythingImplemented() { assertAllMethodsOverridden(ConnectorAccessControl.class, SqlStandardAccessControl.class); } } | java |
/* * Licensed 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 com.facebook. <mask> <mask> <mask> <mask> <mask> .hive.security; import com.facebook. <mask> <mask> <mask> <mask> <mask> .spi.connector.ConnectorAccessControl; import org.testng.annotations.Test; import static com.facebook. <mask> <mask> <mask> <mask> <mask> .spi.testing.InterfaceTestUtils.assertAllMethodsOverridden; public class TestSqlStandardAccessControl { @Test public void testEverythingImplemented() { assertAllMethodsOverridden(ConnectorAccessControl.class, SqlStandardAccessControl.class); } } | /* * Licensed 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 com.facebook. presto .hive.security; import com.facebook. presto .spi.connector.ConnectorAccessControl; import org.testng.annotations.Test; import static com.facebook. presto .spi.testing.InterfaceTestUtils.assertAllMethodsOverridden; public class TestSqlStandardAccessControl { @Test public void testEverythingImplemented() { assertAllMethodsOverridden(ConnectorAccessControl.class, SqlStandardAccessControl.class); } } | java |
/* * Licensed 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 com.facebook. <mask> <mask> <mask> <mask> <mask> .hive.security; import com.facebook. <mask> <mask> <mask> <mask> <mask> .spi.connector.ConnectorAccessControl; import org.testng.annotations.Test; import static com.facebook. <mask> <mask> <mask> <mask> <mask> .spi.testing.InterfaceTestUtils.assertAllMethodsOverridden; public class TestSqlStandardAccessControl { @Test public void testEverythingImplemented() { assertAllMethodsOverridden(ConnectorAccessControl.class, SqlStandardAccessControl.class); } } | /* * Licensed 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 com.facebook. presto .hive.security; import com.facebook. presto .spi.connector.ConnectorAccessControl; import org.testng.annotations.Test; import static com.facebook. presto .spi.testing.InterfaceTestUtils.assertAllMethodsOverridden; public class TestSqlStandardAccessControl { @Test public void testEverythingImplemented() { assertAllMethodsOverridden(ConnectorAccessControl.class, SqlStandardAccessControl.class); } } | java |
/* * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import javax. <mask> <mask> <mask> .JButton; import javax. <mask> <mask> <mask> .JCheckBox; import javax. <mask> <mask> <mask> .JComboBox; import javax. <mask> <mask> <mask> .JComponent; import javax. <mask> <mask> <mask> .JEditorPane; import javax. <mask> <mask> <mask> .JFormattedTextField; import javax. <mask> <mask> <mask> .JFrame; import javax. <mask> <mask> <mask> .JLabel; import javax. <mask> <mask> <mask> .JList; import javax. <mask> <mask> <mask> .JMenu; import javax. <mask> <mask> <mask> .JMenuItem; import javax. <mask> <mask> <mask> .JRadioButton; import javax. <mask> <mask> <mask> .JScrollPane; import javax. <mask> <mask> <mask> .JSpinner; import javax. <mask> <mask> <mask> .JTable; import javax. <mask> <mask> <mask> .JTextArea; import javax. <mask> <mask> <mask> .JTextField; import javax. <mask> <mask> <mask> .JToolTip; import javax. <mask> <mask> <mask> .JTree; import javax. <mask> <mask> <mask> .Popup; import javax. <mask> <mask> <mask> .PopupFactory; import javax. <mask> <mask> <mask> .SpinnerListModel; import javax. <mask> <mask> <mask> .SwingUtilities; import javax. <mask> <mask> <mask> .UIManager; import javax. <mask> <mask> <mask> .UnsupportedLookAndFeelException; import javax. <mask> <mask> <mask> .tree.DefaultMutableTreeNode; import static javax. <mask> <mask> <mask> .UIManager.getInstalledLookAndFeels; /** * @test * @key headful * @bug 8201552 8213843 8213535 8244400 * @summary Initial layout of the component should use correct graphics config. * It is checked by SwingUtilities.updateComponentTreeUI(), if layout * was correct the call to updateComponentTreeUI() will be no-op. * @compile -encoding utf-8 StalePreferredSize.java * @run main/othervm/timeout=600 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=1 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=2.25 StalePreferredSize */ public final class StalePreferredSize { // Some text to be tested static final String TEXT[] = new String[]{ "<span>A few words to get started before the " + "bug</span><span>overlapping text</span>", "A quick brown fox jumps over the lazy dog", "El veloz murciélago hindú comía feliz cardillo y kiwi. La cigüeña " + "tocaba el saxofón detrás del palenque de paja", "Voix ambiguë d’un cœur qui au zéphyr préfère les jattes de kiwis", "다람쥐 헌 쳇바퀴에 타고파", "Съешь ещё этих мягких французских булок | /* * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import javax. swing .JButton; import javax. swing .JCheckBox; import javax. swing .JComboBox; import javax. swing .JComponent; import javax. swing .JEditorPane; import javax. swing .JFormattedTextField; import javax. swing .JFrame; import javax. swing .JLabel; import javax. swing .JList; import javax. swing .JMenu; import javax. swing .JMenuItem; import javax. swing .JRadioButton; import javax. swing .JScrollPane; import javax. swing .JSpinner; import javax. swing .JTable; import javax. swing .JTextArea; import javax. swing .JTextField; import javax. swing .JToolTip; import javax. swing .JTree; import javax. swing .Popup; import javax. swing .PopupFactory; import javax. swing .SpinnerListModel; import javax. swing .SwingUtilities; import javax. swing .UIManager; import javax. swing .UnsupportedLookAndFeelException; import javax. swing .tree.DefaultMutableTreeNode; import static javax. swing .UIManager.getInstalledLookAndFeels; /** * @test * @key headful * @bug 8201552 8213843 8213535 8244400 * @summary Initial layout of the component should use correct graphics config. * It is checked by SwingUtilities.updateComponentTreeUI(), if layout * was correct the call to updateComponentTreeUI() will be no-op. * @compile -encoding utf-8 StalePreferredSize.java * @run main/othervm/timeout=600 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=1 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=2.25 StalePreferredSize */ public final class StalePreferredSize { // Some text to be tested static final String TEXT[] = new String[]{ "<span>A few words to get started before the " + "bug</span><span>overlapping text</span>", "A quick brown fox jumps over the lazy dog", "El veloz murciélago hindú comía feliz cardillo y kiwi. La cigüeña " + "tocaba el saxofón detrás del palenque de paja", "Voix ambiguë d’un cœur qui au zéphyr préfère les jattes de kiwis", "다람쥐 헌 쳇바퀴에 타고파", "Съешь ещё этих мягких французских булок | java |
/* * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import javax. <mask> <mask> <mask> .JButton; import javax. <mask> <mask> <mask> .JCheckBox; import javax. <mask> <mask> <mask> .JComboBox; import javax. <mask> <mask> <mask> .JComponent; import javax. <mask> <mask> <mask> .JEditorPane; import javax. <mask> <mask> <mask> .JFormattedTextField; import javax. <mask> <mask> <mask> .JFrame; import javax. <mask> <mask> <mask> .JLabel; import javax. <mask> <mask> <mask> .JList; import javax. <mask> <mask> <mask> .JMenu; import javax. <mask> <mask> <mask> .JMenuItem; import javax. <mask> <mask> <mask> .JRadioButton; import javax. <mask> <mask> <mask> .JScrollPane; import javax. <mask> <mask> <mask> .JSpinner; import javax. <mask> <mask> <mask> .JTable; import javax. <mask> <mask> <mask> .JTextArea; import javax. <mask> <mask> <mask> .JTextField; import javax. <mask> <mask> <mask> .JToolTip; import javax. <mask> <mask> <mask> .JTree; import javax. <mask> <mask> <mask> .Popup; import javax. <mask> <mask> <mask> .PopupFactory; import javax. <mask> <mask> <mask> .SpinnerListModel; import javax. <mask> <mask> <mask> .SwingUtilities; import javax. <mask> <mask> <mask> .UIManager; import javax. <mask> <mask> <mask> .UnsupportedLookAndFeelException; import javax. <mask> <mask> <mask> .tree.DefaultMutableTreeNode; import static javax. <mask> <mask> <mask> .UIManager.getInstalledLookAndFeels; /** * @test * @key headful * @bug 8201552 8213843 8213535 8244400 * @summary Initial layout of the component should use correct graphics config. * It is checked by SwingUtilities.updateComponentTreeUI(), if layout * was correct the call to updateComponentTreeUI() will be no-op. * @compile -encoding utf-8 StalePreferredSize.java * @run main/othervm/timeout=600 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=1 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=2.25 StalePreferredSize */ public final class StalePreferredSize { // Some text to be tested static final String TEXT[] = new String[]{ "<span>A few words to get started before the " + "bug</span><span>overlapping text</span>", "A quick brown fox jumps over the lazy dog", "El veloz murciélago hindú comía feliz cardillo y kiwi. La cigüeña " + "tocaba el saxofón detrás del palenque de paja", "Voix ambiguë d’un cœur qui au zéphyr préfère les jattes de kiwis", "다람쥐 헌 쳇바퀴에 타고파", "Съешь ещё этих мягких французских булок да выпей же чаю"}; | /* * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import javax. swing .JButton; import javax. swing .JCheckBox; import javax. swing .JComboBox; import javax. swing .JComponent; import javax. swing .JEditorPane; import javax. swing .JFormattedTextField; import javax. swing .JFrame; import javax. swing .JLabel; import javax. swing .JList; import javax. swing .JMenu; import javax. swing .JMenuItem; import javax. swing .JRadioButton; import javax. swing .JScrollPane; import javax. swing .JSpinner; import javax. swing .JTable; import javax. swing .JTextArea; import javax. swing .JTextField; import javax. swing .JToolTip; import javax. swing .JTree; import javax. swing .Popup; import javax. swing .PopupFactory; import javax. swing .SpinnerListModel; import javax. swing .SwingUtilities; import javax. swing .UIManager; import javax. swing .UnsupportedLookAndFeelException; import javax. swing .tree.DefaultMutableTreeNode; import static javax. swing .UIManager.getInstalledLookAndFeels; /** * @test * @key headful * @bug 8201552 8213843 8213535 8244400 * @summary Initial layout of the component should use correct graphics config. * It is checked by SwingUtilities.updateComponentTreeUI(), if layout * was correct the call to updateComponentTreeUI() will be no-op. * @compile -encoding utf-8 StalePreferredSize.java * @run main/othervm/timeout=600 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=1 StalePreferredSize * @run main/othervm/timeout=600 -Dsun.java2d.uiScale=2.25 StalePreferredSize */ public final class StalePreferredSize { // Some text to be tested static final String TEXT[] = new String[]{ "<span>A few words to get started before the " + "bug</span><span>overlapping text</span>", "A quick brown fox jumps over the lazy dog", "El veloz murciélago hindú comía feliz cardillo y kiwi. La cigüeña " + "tocaba el saxofón detrás del palenque de paja", "Voix ambiguë d’un cœur qui au zéphyr préfère les jattes de kiwis", "다람쥐 헌 쳇바퀴에 타고파", "Съешь ещё этих мягких французских булок да выпей же чаю"}; | java |