repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/AbstractElasticsearchMojo.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ChainedArtifactResolver.java // public class ChainedArtifactResolver // implements PluginArtifactResolver // { // // protected List<PluginArtifactResolver> resolverChain = new LinkedList<PluginArtifactResolver>(); // // public ChainedArtifactResolver() // { // this.resolverChain.add(new SystemPathArtifactResolver()); // } // // @Override // public File resolveArtifact(final String coordinates) throws ArtifactException // { // File result = null; // for (PluginArtifactResolver resolver : resolverChain) // { // try // { // result = resolver.resolveArtifact(coordinates); // if (result != null) // { // break; // } // // CHECKSTYLE:OFF: Empty catch block // } // catch (ArtifactException e) // { // } // // CHECKSTYLE:ON: Empty catch block // } // if (result == null) // { // throw new ArtifactException( // "Could not resolve artifact with coordinates " + coordinates); // } // return result; // } // // public void addPluginArtifactResolver(PluginArtifactResolver pluginArtifactResolver) // { // Validate.notNull(pluginArtifactResolver, "PluginArtifactResolvers should not be null"); // this.resolverChain.add(pluginArtifactResolver); // } // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ElasticsearchConfiguration.java // public interface ElasticsearchConfiguration extends ElasticsearchBaseConfiguration // { // String getVersion(); // // String getClusterName(); // // int getHttpPort(); // // int getTransportPort(); // // String getPathConf(); // // String getPathData(); // // String getPathLogs(); // // List<PluginConfiguration> getPlugins(); // // List<String> getPathInitScript(); // // boolean isKeepExistingData(); // // int getInstanceStartupTimeout(); // // int getClusterStartupTimeout(); // // boolean isSetAwait(); // // boolean isAutoCreateIndex(); // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // }
import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ChainedArtifactResolver; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ElasticsearchConfiguration; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver; import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream;
clusterConfigBuilder.addInstanceConfiguration(new InstanceConfiguration.Builder() .withId(i) .withBaseDir(baseDir.getAbsolutePath() + i) .withHttpPort(httpPort + i) .withTransportPort(transportPort + i) .withPathData(pathData) .withPathLogs(pathLogs) .withEnvironmentVariables(environmentVariables) .withSettings(settings) .withStartupTimeout(instanceStartupTimeout) .build()); } ClusterConfiguration clusterConfig = clusterConfigBuilder.build(); return clusterConfig; } @Override public PluginArtifactResolver buildArtifactResolver() { ChainedArtifactResolver artifactResolver = new ChainedArtifactResolver(); artifactResolver.addPluginArtifactResolver(new MyArtifactResolver( repositorySystem, repositorySession, remoteRepositories, getLog())); return artifactResolver; }
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ChainedArtifactResolver.java // public class ChainedArtifactResolver // implements PluginArtifactResolver // { // // protected List<PluginArtifactResolver> resolverChain = new LinkedList<PluginArtifactResolver>(); // // public ChainedArtifactResolver() // { // this.resolverChain.add(new SystemPathArtifactResolver()); // } // // @Override // public File resolveArtifact(final String coordinates) throws ArtifactException // { // File result = null; // for (PluginArtifactResolver resolver : resolverChain) // { // try // { // result = resolver.resolveArtifact(coordinates); // if (result != null) // { // break; // } // // CHECKSTYLE:OFF: Empty catch block // } // catch (ArtifactException e) // { // } // // CHECKSTYLE:ON: Empty catch block // } // if (result == null) // { // throw new ArtifactException( // "Could not resolve artifact with coordinates " + coordinates); // } // return result; // } // // public void addPluginArtifactResolver(PluginArtifactResolver pluginArtifactResolver) // { // Validate.notNull(pluginArtifactResolver, "PluginArtifactResolvers should not be null"); // this.resolverChain.add(pluginArtifactResolver); // } // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ElasticsearchConfiguration.java // public interface ElasticsearchConfiguration extends ElasticsearchBaseConfiguration // { // String getVersion(); // // String getClusterName(); // // int getHttpPort(); // // int getTransportPort(); // // String getPathConf(); // // String getPathData(); // // String getPathLogs(); // // List<PluginConfiguration> getPlugins(); // // List<String> getPathInitScript(); // // boolean isKeepExistingData(); // // int getInstanceStartupTimeout(); // // int getClusterStartupTimeout(); // // boolean isSetAwait(); // // boolean isAutoCreateIndex(); // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/AbstractElasticsearchMojo.java import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ChainedArtifactResolver; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ElasticsearchConfiguration; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver; import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; clusterConfigBuilder.addInstanceConfiguration(new InstanceConfiguration.Builder() .withId(i) .withBaseDir(baseDir.getAbsolutePath() + i) .withHttpPort(httpPort + i) .withTransportPort(transportPort + i) .withPathData(pathData) .withPathLogs(pathLogs) .withEnvironmentVariables(environmentVariables) .withSettings(settings) .withStartupTimeout(instanceStartupTimeout) .build()); } ClusterConfiguration clusterConfig = clusterConfigBuilder.build(); return clusterConfig; } @Override public PluginArtifactResolver buildArtifactResolver() { ChainedArtifactResolver artifactResolver = new ChainedArtifactResolver(); artifactResolver.addPluginArtifactResolver(new MyArtifactResolver( repositorySystem, repositorySession, remoteRepositories, getLog())); return artifactResolver; }
public PluginArtifactInstaller buildArtifactInstaller()
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/FilesystemUtil.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // }
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.exec.CommandLine; import org.apache.commons.lang3.SystemUtils; import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration;
public static void copyRecursively(Path source, Path destination) throws IOException { if (Files.isDirectory(source)) { Files.createDirectories(destination); final Set<Path> sources = listFiles(source); for (Path srcFile : sources) { Path destFile = destination.resolve(srcFile.getFileName()); copyRecursively(srcFile, destFile); } } else { Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } } private static Set<Path> listFiles(Path directory) throws IOException { try (Stream<Path> stream = Files.list(directory)) { return stream.collect(Collectors.toSet()); } } /** * Set the 755 permissions on the given script. * @param config - the instance config * @param scriptName - the name of the script (located in the bin directory) to make executable */
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/FilesystemUtil.java import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.exec.CommandLine; import org.apache.commons.lang3.SystemUtils; import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration; public static void copyRecursively(Path source, Path destination) throws IOException { if (Files.isDirectory(source)) { Files.createDirectories(destination); final Set<Path> sources = listFiles(source); for (Path srcFile : sources) { Path destFile = destination.resolve(srcFile.getFileName()); copyRecursively(srcFile, destFile); } } else { Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } } private static Set<Path> listFiles(Path directory) throws IOException { try (Stream<Path> stream = Files.list(directory)) { return stream.collect(Collectors.toSet()); } } /** * Set the 755 permissions on the given script. * @param config - the instance config * @param scriptName - the name of the script (located in the bin directory) to make executable */
public static void setScriptPermission(InstanceConfiguration config, String scriptName)
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ClusterConfiguration.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // }
import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.maven.plugin.logging.Log; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The cluster configuration, containing the list of ES configurations, * the artifact resolver, the logger, and other cluster specific attributes. * * @author Alex Cojocaru */ public class ClusterConfiguration { private List<InstanceConfiguration> instanceConfigurationList;
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ClusterConfiguration.java import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.maven.plugin.logging.Log; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The cluster configuration, containing the list of ES configurations, * the artifact resolver, the logger, and other cluster specific attributes. * * @author Alex Cojocaru */ public class ClusterConfiguration { private List<InstanceConfiguration> instanceConfigurationList;
private PluginArtifactResolver artifactResolver;
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ClusterConfiguration.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // }
import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.maven.plugin.logging.Log; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The cluster configuration, containing the list of ES configurations, * the artifact resolver, the logger, and other cluster specific attributes. * * @author Alex Cojocaru */ public class ClusterConfiguration { private List<InstanceConfiguration> instanceConfigurationList; private PluginArtifactResolver artifactResolver;
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ClusterConfiguration.java import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.maven.plugin.logging.Log; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The cluster configuration, containing the list of ES configurations, * the artifact resolver, the logger, and other cluster specific attributes. * * @author Alex Cojocaru */ public class ClusterConfiguration { private List<InstanceConfiguration> instanceConfigurationList; private PluginArtifactResolver artifactResolver;
private PluginArtifactInstaller artifactInstaller;
alexcojocaru/elasticsearch-maven-plugin
src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ItSetup.java
// Path: src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/NetUtil.java // public enum ElasticsearchPort // { // HTTP, // TRANSPORT // };
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.lang3.RandomStringUtils; import com.github.alexcojocaru.mojo.elasticsearch.v2.NetUtil.ElasticsearchPort;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * Used by the groovy setup scripts executed at the beginning of each integration test. * * @author alexcojocaru */ public class ItSetup { /** * The base direction of the test execution (ie. the project directory) */ private final File baseDir; /** * @param executionBaseDir */ public ItSetup(File baseDir) { this.baseDir = baseDir; } /** * Generate a map of properties to be passed to the plugin * * @param count the number of ES instances * @throws IOException */ public Map<String, String> generateProperties(int count) throws IOException { String clusterName = RandomStringUtils.randomAlphanumeric(8);
// Path: src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/NetUtil.java // public enum ElasticsearchPort // { // HTTP, // TRANSPORT // }; // Path: src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ItSetup.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.lang3.RandomStringUtils; import com.github.alexcojocaru.mojo.elasticsearch.v2.NetUtil.ElasticsearchPort; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * Used by the groovy setup scripts executed at the beginning of each integration test. * * @author alexcojocaru */ public class ItSetup { /** * The base direction of the test execution (ie. the project directory) */ private final File baseDir; /** * @param executionBaseDir */ public ItSetup(File baseDir) { this.baseDir = baseDir; } /** * Generate a map of properties to be passed to the plugin * * @param count the number of ES instances * @throws IOException */ public Map<String, String> generateProperties(int count) throws IOException { String clusterName = RandomStringUtils.randomAlphanumeric(8);
Map<ElasticsearchPort, Integer> esPorts = NetUtil.findOpenPortsForElasticsearch(count);
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ElasticsearchArtifact.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/VersionUtil.java // public class VersionUtil { // // public static boolean isUnder_5_0_0(String version) // { // return version.matches("[0-4]\\..*"); // } // // public static boolean isBetween_6_3_0_and_7_10_x(String version) // { // return version.matches("6\\.([3-9]|(\\d){2,})\\..*") // || version.matches("7\\.[0-9]\\..*") // || version.matches("7\\.10\\..*"); // } // // public static boolean isEqualOrGreater_6_4_0(String version) // { // return version.matches("6\\.([4-9]|(\\d){2,})\\..*") // || version.matches("([7-9]|(\\d){2,})\\..*"); // } // // public static boolean isEqualOrGreater_7_0_0(String version) // { // return version.matches("([7-9]|(\\d){2,})\\..*"); // } // // public static boolean isEqualOrGreater_8_0_0(String version) // { // return version.matches("([8-9]|(\\d){2,})\\..*"); // } // // }
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import com.github.alexcojocaru.mojo.elasticsearch.v2.util.VersionUtil; import com.google.common.base.Joiner;
public String toString() { return "ElasticsearchArtifact[" + super.getArtifactCoordinates() + "]"; } public static class ElasticsearchArtifactBuilder { private ClusterConfiguration clusterConfig; public ElasticsearchArtifactBuilder withClusterConfig(ClusterConfiguration clusterConfig) { this.clusterConfig = clusterConfig; return this; } public ElasticsearchArtifact build() { String flavour = clusterConfig.getFlavour(); String version = clusterConfig.getVersion(); String id = getArtifactId(flavour, version); String classifier = getArtifactClassifier(version); String type = getArtifactType(version); return new ElasticsearchArtifact(id, version, classifier, type); } private String getArtifactId(String flavour, String version) {
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/VersionUtil.java // public class VersionUtil { // // public static boolean isUnder_5_0_0(String version) // { // return version.matches("[0-4]\\..*"); // } // // public static boolean isBetween_6_3_0_and_7_10_x(String version) // { // return version.matches("6\\.([3-9]|(\\d){2,})\\..*") // || version.matches("7\\.[0-9]\\..*") // || version.matches("7\\.10\\..*"); // } // // public static boolean isEqualOrGreater_6_4_0(String version) // { // return version.matches("6\\.([4-9]|(\\d){2,})\\..*") // || version.matches("([7-9]|(\\d){2,})\\..*"); // } // // public static boolean isEqualOrGreater_7_0_0(String version) // { // return version.matches("([7-9]|(\\d){2,})\\..*"); // } // // public static boolean isEqualOrGreater_8_0_0(String version) // { // return version.matches("([8-9]|(\\d){2,})\\..*"); // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ElasticsearchArtifact.java import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import com.github.alexcojocaru.mojo.elasticsearch.v2.util.VersionUtil; import com.google.common.base.Joiner; public String toString() { return "ElasticsearchArtifact[" + super.getArtifactCoordinates() + "]"; } public static class ElasticsearchArtifactBuilder { private ClusterConfiguration clusterConfig; public ElasticsearchArtifactBuilder withClusterConfig(ClusterConfiguration clusterConfig) { this.clusterConfig = clusterConfig; return this; } public ElasticsearchArtifact build() { String flavour = clusterConfig.getFlavour(); String version = clusterConfig.getVersion(); String id = getArtifactId(flavour, version); String classifier = getArtifactClassifier(version); String type = getArtifactType(version); return new ElasticsearchArtifact(id, version, classifier, type); } private String getArtifactId(String flavour, String version) {
if (VersionUtil.isBetween_6_3_0_and_7_10_x(version))
alexcojocaru/elasticsearch-maven-plugin
src/it/runforked-skip/src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/SkipTest.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java // public class Monitor // { // private final ElasticsearchClient client; // private final Log log; // // public Monitor(ElasticsearchClient client, Log log) // { // this.client = client; // this.log = log; // } // // public void waitToStartInstance(final String baseDir, final String clusterName, int timeout) // { // log.debug(String.format( // "Waiting up to %ds for the Elasticsearch instance to start ...", // timeout)); // Awaitility.await() // .atMost(timeout, TimeUnit.SECONDS) // .pollDelay(1, TimeUnit.SECONDS) // .pollInterval(1, TimeUnit.SECONDS) // .until(new Callable<Boolean>() // { // @Override // public Boolean call() throws Exception // { // return isProcessRunning(baseDir) // && isInstanceRunning(clusterName); // } // } // ); // log.info("The Elasticsearch instance has started"); // } // // /** // * Check whether the PID file created by the ES process exists or not. // * @param baseDir the ES base directory // * @return true if the process is running, false otherwise // */ // public static boolean isProcessRunning(String baseDir) // { // File pidFile = new File(baseDir, "pid"); // boolean exists = pidFile.isFile(); // return exists; // } // // /** // * Check whether the cluster with the given name exists in the current ES instance. // * @param clusterName the ES cluster name // * @return true if the instance is running, false otherwise // */ // public boolean isInstanceRunning(String clusterName) // { // boolean result; // try // { // @SuppressWarnings("unchecked") // Map<String, Object> response = client.get("/", Map.class); // result = clusterName.equals(response.get("cluster_name")); // } // catch (ElasticsearchClientException e) // { // // failure is allowed // result = false; // } // // return result; // } // // /** // * Check whether the cluster with the given name exists in the ES running on the given port. // * <br><br> // * This is an expensive method, for it initializes a new ES client. // * @param clusterName the ES cluster name // * @param httpPort the HTTP port to connect to ES // * @return true if the instance is running, false otherwise // */ // public static boolean isInstanceRunning(String clusterName, int httpPort) // { // Log log = Mockito.mock(Log.class); // // try (ElasticsearchClient client = new ElasticsearchClient.Builder() // .withLog(log) // .withHostname("localhost") // .withPort(httpPort) // .withSocketTimeout(5000) // .build()) // { // return new Monitor(client, log).isInstanceRunning(clusterName); // } // } // // /** // * Wait until the cluster has fully started (ie. all nodes have joined). // * @param clusterName the ES cluster name // * @param nodesCount the number of nodes in the cluster // * @param timeout how many seconds to wait // */ // public void waitToStartCluster(final String clusterName, int nodesCount, int timeout) // { // log.debug(String.format( // "Waiting up to %ds for the Elasticsearch cluster to start ...", // timeout)); // Awaitility.await() // .atMost(timeout, TimeUnit.SECONDS) // .pollDelay(1, TimeUnit.SECONDS) // .pollInterval(1, TimeUnit.SECONDS) // .until(new Callable<Boolean>() // { // @Override // public Boolean call() throws Exception // { // return isClusterRunning(clusterName, nodesCount, client); // } // } // ); // log.info("The Elasticsearch cluster has started"); // } // // /** // * Verify that the cluster name and the number of nodes in the cluster, // * as reported by the ES node, is as expected. // * @param clusterName the ES cluster name // * @param instanceCount the number of ES nodes in the cluster // * @param client the ES client to use to connect to ES // * @return true if the cluster is running, false otherwise // */ // public static boolean isClusterRunning(String clusterName, // int instanceCount, // ElasticsearchClient client) // { // boolean result; // try // { // @SuppressWarnings("unchecked") // Map<String, Object> response = client.get("/_nodes", Map.class); // result = clusterName.equals(response.get("cluster_name")); // // @SuppressWarnings("unchecked") // Map<String, Object> nodesInfo = (Map<String, Object>)response.get("_nodes"); // result &= instanceCount == (int)(nodesInfo.get("successful")); // } // catch (ElasticsearchClientException e) // { // // failure is allowed // result = false; // } // // return result; // } // // /** // * Verify that the cluster name and the number of nodes in the cluster, // * as reported by the ES node, is as expected. // * @param clusterName the ES cluster name // * @param instanceCount the number of ES nodes in the cluster // * @param httpPort the HTTP port to connect to ES // * @return true if the cluster is running, false otherwise // */ // public static boolean isClusterRunning(String clusterName, int instanceCount, int httpPort) // { // Log log = Mockito.mock(Log.class); // // try (ElasticsearchClient client = new ElasticsearchClient.Builder() // .withLog(log) // .withHostname("localhost") // .withPort(httpPort) // .withSocketTimeout(5000) // .build()) // { // return isClusterRunning(clusterName, instanceCount, client); // } // } // }
import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import com.github.alexcojocaru.mojo.elasticsearch.v2.client.Monitor;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * * @author Alex Cojocaru * */ @RunWith(MockitoJUnitRunner.class) public class SkipTest extends ItBase { @Test public void testClusterNotRunning() {
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java // public class Monitor // { // private final ElasticsearchClient client; // private final Log log; // // public Monitor(ElasticsearchClient client, Log log) // { // this.client = client; // this.log = log; // } // // public void waitToStartInstance(final String baseDir, final String clusterName, int timeout) // { // log.debug(String.format( // "Waiting up to %ds for the Elasticsearch instance to start ...", // timeout)); // Awaitility.await() // .atMost(timeout, TimeUnit.SECONDS) // .pollDelay(1, TimeUnit.SECONDS) // .pollInterval(1, TimeUnit.SECONDS) // .until(new Callable<Boolean>() // { // @Override // public Boolean call() throws Exception // { // return isProcessRunning(baseDir) // && isInstanceRunning(clusterName); // } // } // ); // log.info("The Elasticsearch instance has started"); // } // // /** // * Check whether the PID file created by the ES process exists or not. // * @param baseDir the ES base directory // * @return true if the process is running, false otherwise // */ // public static boolean isProcessRunning(String baseDir) // { // File pidFile = new File(baseDir, "pid"); // boolean exists = pidFile.isFile(); // return exists; // } // // /** // * Check whether the cluster with the given name exists in the current ES instance. // * @param clusterName the ES cluster name // * @return true if the instance is running, false otherwise // */ // public boolean isInstanceRunning(String clusterName) // { // boolean result; // try // { // @SuppressWarnings("unchecked") // Map<String, Object> response = client.get("/", Map.class); // result = clusterName.equals(response.get("cluster_name")); // } // catch (ElasticsearchClientException e) // { // // failure is allowed // result = false; // } // // return result; // } // // /** // * Check whether the cluster with the given name exists in the ES running on the given port. // * <br><br> // * This is an expensive method, for it initializes a new ES client. // * @param clusterName the ES cluster name // * @param httpPort the HTTP port to connect to ES // * @return true if the instance is running, false otherwise // */ // public static boolean isInstanceRunning(String clusterName, int httpPort) // { // Log log = Mockito.mock(Log.class); // // try (ElasticsearchClient client = new ElasticsearchClient.Builder() // .withLog(log) // .withHostname("localhost") // .withPort(httpPort) // .withSocketTimeout(5000) // .build()) // { // return new Monitor(client, log).isInstanceRunning(clusterName); // } // } // // /** // * Wait until the cluster has fully started (ie. all nodes have joined). // * @param clusterName the ES cluster name // * @param nodesCount the number of nodes in the cluster // * @param timeout how many seconds to wait // */ // public void waitToStartCluster(final String clusterName, int nodesCount, int timeout) // { // log.debug(String.format( // "Waiting up to %ds for the Elasticsearch cluster to start ...", // timeout)); // Awaitility.await() // .atMost(timeout, TimeUnit.SECONDS) // .pollDelay(1, TimeUnit.SECONDS) // .pollInterval(1, TimeUnit.SECONDS) // .until(new Callable<Boolean>() // { // @Override // public Boolean call() throws Exception // { // return isClusterRunning(clusterName, nodesCount, client); // } // } // ); // log.info("The Elasticsearch cluster has started"); // } // // /** // * Verify that the cluster name and the number of nodes in the cluster, // * as reported by the ES node, is as expected. // * @param clusterName the ES cluster name // * @param instanceCount the number of ES nodes in the cluster // * @param client the ES client to use to connect to ES // * @return true if the cluster is running, false otherwise // */ // public static boolean isClusterRunning(String clusterName, // int instanceCount, // ElasticsearchClient client) // { // boolean result; // try // { // @SuppressWarnings("unchecked") // Map<String, Object> response = client.get("/_nodes", Map.class); // result = clusterName.equals(response.get("cluster_name")); // // @SuppressWarnings("unchecked") // Map<String, Object> nodesInfo = (Map<String, Object>)response.get("_nodes"); // result &= instanceCount == (int)(nodesInfo.get("successful")); // } // catch (ElasticsearchClientException e) // { // // failure is allowed // result = false; // } // // return result; // } // // /** // * Verify that the cluster name and the number of nodes in the cluster, // * as reported by the ES node, is as expected. // * @param clusterName the ES cluster name // * @param instanceCount the number of ES nodes in the cluster // * @param httpPort the HTTP port to connect to ES // * @return true if the cluster is running, false otherwise // */ // public static boolean isClusterRunning(String clusterName, int instanceCount, int httpPort) // { // Log log = Mockito.mock(Log.class); // // try (ElasticsearchClient client = new ElasticsearchClient.Builder() // .withLog(log) // .withHostname("localhost") // .withPort(httpPort) // .withSocketTimeout(5000) // .build()) // { // return isClusterRunning(clusterName, instanceCount, client); // } // } // } // Path: src/it/runforked-skip/src/test/java/com/github/alexcojocaru/mojo/elasticsearch/v2/SkipTest.java import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import com.github.alexcojocaru.mojo.elasticsearch.v2.client.Monitor; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * * @author Alex Cojocaru * */ @RunWith(MockitoJUnitRunner.class) public class SkipTest extends ItBase { @Test public void testClusterNotRunning() {
boolean isRunning = Monitor.isClusterRunning(clusterName, instanceCount, client);
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/DefaultInstanceStepSequence.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // }
import java.util.LinkedList; import java.util.List; import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration;
package com.github.alexcojocaru.mojo.elasticsearch.v2.step; /** * Implementation of a {@link InstanceStepSequence}. * * @author Alex Cojocaru */ public class DefaultInstanceStepSequence implements InstanceStepSequence { protected List<InstanceStep> sequence = new LinkedList<InstanceStep>(); @Override
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/DefaultInstanceStepSequence.java import java.util.LinkedList; import java.util.List; import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration; package com.github.alexcojocaru.mojo.elasticsearch.v2.step; /** * Implementation of a {@link InstanceStepSequence}. * * @author Alex Cojocaru */ public class DefaultInstanceStepSequence implements InstanceStepSequence { protected List<InstanceStep> sequence = new LinkedList<InstanceStep>(); @Override
public void execute(InstanceConfiguration config)
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/ElasticsearchClient.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // }
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.lang3.Validate; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.config.SocketConfig; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.maven.plugin.logging.Log; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration;
{ private Log log; private String hostname; private int port; private int socketTimeout; public Builder withLog(Log log) { this.log = log; return this; } public Builder withHostname(String hostname) { this.hostname = hostname; return this; } public Builder withPort(int port) { this.port = port; return this; } public Builder withSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; return this; }
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/ElasticsearchClient.java import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.lang3.Validate; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.config.SocketConfig; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.maven.plugin.logging.Log; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration; { private Log log; private String hostname; private int port; private int socketTimeout; public Builder withLog(Log log) { this.log = log; return this; } public Builder withHostname(String hostname) { this.hostname = hostname; return this; } public Builder withPort(int port) { this.port = port; return this; } public Builder withSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; return this; }
public Builder withInstanceConfiguration(InstanceConfiguration config)
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/InstanceStep.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // }
import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration;
package com.github.alexcojocaru.mojo.elasticsearch.v2.step; /** * Defines a small simple Step/Task/Unit of Work for an Elasticsearch instance. * * @author Alex Cojocaru */ public interface InstanceStep {
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/InstanceConfiguration.java // public class InstanceConfiguration // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public ClusterConfiguration getClusterConfiguration() // { // return clusterConfiguration; // } // // public void setClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // } // // public int getId() // { // return id; // } // // public String getBaseDir() // { // return baseDir; // } // // public int getHttpPort() // { // return httpPort; // } // // public int getTransportPort() // { // return transportPort; // } // // public String getPathData() // { // return pathData; // } // // public String getPathLogs() // { // return pathLogs; // } // // public Map<String, String> getEnvironmentVariables() { // return environmentVariables; // } // // public Properties getSettings() // { // return settings; // } // // public int getStartupTimeout() // { // return startupTimeout; // } // // public String toString() // { // return new ToStringBuilder(this) // .append("id", id) // .append("baseDir", baseDir) // .append("httpPort", httpPort) // .append("transportPort", transportPort) // .append("pathData", pathData) // .append("pathLogs", pathLogs) // .append("settings", settings) // .append("startupTimeout", startupTimeout) // .toString(); // } // // public static class Builder // { // private ClusterConfiguration clusterConfiguration; // private int id; // private String baseDir; // private int httpPort; // private int transportPort; // private String pathData; // private String pathLogs; // private Map<String, String> environmentVariables; // private Properties settings; // private int startupTimeout; // // // public Builder withClusterConfiguration(ClusterConfiguration clusterConfiguration) // { // this.clusterConfiguration = clusterConfiguration; // return this; // } // // public Builder withId(int id) // { // this.id = id; // return this; // } // // public Builder withBaseDir(String baseDir) // { // this.baseDir = baseDir; // return this; // } // // public Builder withHttpPort(int httpPort) // { // this.httpPort = httpPort; // return this; // } // // public Builder withTransportPort(int transportPort) // { // this.transportPort = transportPort; // return this; // } // // public Builder withPathData(String pathData) // { // this.pathData = pathData; // return this; // } // // public Builder withPathLogs(String pathLogs) // { // this.pathLogs = pathLogs; // return this; // } // // public Builder withEnvironmentVariables(final Map<String, String> environmentVariables) { // this.environmentVariables = environmentVariables; // return this; // } // // public Builder withSettings(final Properties settings) { // this.settings = settings; // return this; // } // // public Builder withStartupTimeout(int startupTimeout) // { // this.startupTimeout = startupTimeout; // return this; // } // // public InstanceConfiguration build() // { // InstanceConfiguration config = new InstanceConfiguration(); // // config.clusterConfiguration = clusterConfiguration; // config.id = id; // config.baseDir = baseDir; // config.httpPort = httpPort; // config.transportPort = transportPort; // config.pathData = pathData; // config.pathLogs = pathLogs; // config.environmentVariables = environmentVariables == null ? Collections.emptyMap() : environmentVariables; // config.settings = settings; // config.startupTimeout = startupTimeout; // // return config; // } // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/InstanceStep.java import com.github.alexcojocaru.mojo.elasticsearch.v2.InstanceConfiguration; package com.github.alexcojocaru.mojo.elasticsearch.v2.step; /** * Defines a small simple Step/Task/Unit of Work for an Elasticsearch instance. * * @author Alex Cojocaru */ public interface InstanceStep {
void execute(InstanceConfiguration config);
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/RunForkedMojo.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartClusterSequence.java // public class PostStartClusterSequence // extends DefaultClusterStepSequence // { // // public PostStartClusterSequence() // { // add(new WaitToStartClusterStep()); // add(new BootstrapClusterStep()); // add(new BlockProcessExecutionStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartInstanceSequence.java // public class PostStartInstanceSequence // extends DefaultInstanceStepSequence // { // // public PostStartInstanceSequence() // { // add(new WaitToStartInstanceStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PreStartClusterSequence.java // public class PreStartClusterSequence // extends DefaultClusterStepSequence // { // // public PreStartClusterSequence() // { // add(new ValidateInstanceCountStep()); // add(new ValidateBaseDirectoryStep()); // add(new ValidateFlavourStep()); // add(new ValidateVersionStep()); // add(new ValidateClusterNameStep()); // add(new ValidateUniquePortsStep()); // add(new ValidatePortsStep()); // add(new ValidatePathConfStep()); // } // }
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartClusterSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartInstanceSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PreStartClusterSequence;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The main plugin mojo to start a forked ES instances. * * @author Alex Cojocaru */ @Mojo(name = "runforked", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, threadSafe = true) public class RunForkedMojo extends AbstractElasticsearchMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping plugin execution"); return; } ClusterConfiguration clusterConfig = buildClusterConfiguration();
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartClusterSequence.java // public class PostStartClusterSequence // extends DefaultClusterStepSequence // { // // public PostStartClusterSequence() // { // add(new WaitToStartClusterStep()); // add(new BootstrapClusterStep()); // add(new BlockProcessExecutionStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartInstanceSequence.java // public class PostStartInstanceSequence // extends DefaultInstanceStepSequence // { // // public PostStartInstanceSequence() // { // add(new WaitToStartInstanceStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PreStartClusterSequence.java // public class PreStartClusterSequence // extends DefaultClusterStepSequence // { // // public PreStartClusterSequence() // { // add(new ValidateInstanceCountStep()); // add(new ValidateBaseDirectoryStep()); // add(new ValidateFlavourStep()); // add(new ValidateVersionStep()); // add(new ValidateClusterNameStep()); // add(new ValidateUniquePortsStep()); // add(new ValidatePortsStep()); // add(new ValidatePathConfStep()); // } // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/RunForkedMojo.java import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartClusterSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartInstanceSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PreStartClusterSequence; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The main plugin mojo to start a forked ES instances. * * @author Alex Cojocaru */ @Mojo(name = "runforked", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, threadSafe = true) public class RunForkedMojo extends AbstractElasticsearchMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping plugin execution"); return; } ClusterConfiguration clusterConfig = buildClusterConfiguration();
new PreStartClusterSequence().execute(clusterConfig);
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/RunForkedMojo.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartClusterSequence.java // public class PostStartClusterSequence // extends DefaultClusterStepSequence // { // // public PostStartClusterSequence() // { // add(new WaitToStartClusterStep()); // add(new BootstrapClusterStep()); // add(new BlockProcessExecutionStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartInstanceSequence.java // public class PostStartInstanceSequence // extends DefaultInstanceStepSequence // { // // public PostStartInstanceSequence() // { // add(new WaitToStartInstanceStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PreStartClusterSequence.java // public class PreStartClusterSequence // extends DefaultClusterStepSequence // { // // public PreStartClusterSequence() // { // add(new ValidateInstanceCountStep()); // add(new ValidateBaseDirectoryStep()); // add(new ValidateFlavourStep()); // add(new ValidateVersionStep()); // add(new ValidateClusterNameStep()); // add(new ValidateUniquePortsStep()); // add(new ValidatePortsStep()); // add(new ValidatePathConfStep()); // } // }
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartClusterSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartInstanceSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PreStartClusterSequence;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The main plugin mojo to start a forked ES instances. * * @author Alex Cojocaru */ @Mojo(name = "runforked", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, threadSafe = true) public class RunForkedMojo extends AbstractElasticsearchMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping plugin execution"); return; } ClusterConfiguration clusterConfig = buildClusterConfiguration(); new PreStartClusterSequence().execute(clusterConfig); for (InstanceConfiguration config : clusterConfig.getInstanceConfigurationList()) { getLog().info(String.format( "Using Elasticsearch [%d] configuration: %s", config.getId(), config)); try { ForkedInstance instance = new ForkedInstance(config); instance.configureInstance(); Thread thread = new Thread(instance); thread.start();
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartClusterSequence.java // public class PostStartClusterSequence // extends DefaultClusterStepSequence // { // // public PostStartClusterSequence() // { // add(new WaitToStartClusterStep()); // add(new BootstrapClusterStep()); // add(new BlockProcessExecutionStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartInstanceSequence.java // public class PostStartInstanceSequence // extends DefaultInstanceStepSequence // { // // public PostStartInstanceSequence() // { // add(new WaitToStartInstanceStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PreStartClusterSequence.java // public class PreStartClusterSequence // extends DefaultClusterStepSequence // { // // public PreStartClusterSequence() // { // add(new ValidateInstanceCountStep()); // add(new ValidateBaseDirectoryStep()); // add(new ValidateFlavourStep()); // add(new ValidateVersionStep()); // add(new ValidateClusterNameStep()); // add(new ValidateUniquePortsStep()); // add(new ValidatePortsStep()); // add(new ValidatePathConfStep()); // } // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/RunForkedMojo.java import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartClusterSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartInstanceSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PreStartClusterSequence; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * The main plugin mojo to start a forked ES instances. * * @author Alex Cojocaru */ @Mojo(name = "runforked", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, threadSafe = true) public class RunForkedMojo extends AbstractElasticsearchMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping plugin execution"); return; } ClusterConfiguration clusterConfig = buildClusterConfiguration(); new PreStartClusterSequence().execute(clusterConfig); for (InstanceConfiguration config : clusterConfig.getInstanceConfigurationList()) { getLog().info(String.format( "Using Elasticsearch [%d] configuration: %s", config.getId(), config)); try { ForkedInstance instance = new ForkedInstance(config); instance.configureInstance(); Thread thread = new Thread(instance); thread.start();
new PostStartInstanceSequence().execute(config);
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/RunForkedMojo.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartClusterSequence.java // public class PostStartClusterSequence // extends DefaultClusterStepSequence // { // // public PostStartClusterSequence() // { // add(new WaitToStartClusterStep()); // add(new BootstrapClusterStep()); // add(new BlockProcessExecutionStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartInstanceSequence.java // public class PostStartInstanceSequence // extends DefaultInstanceStepSequence // { // // public PostStartInstanceSequence() // { // add(new WaitToStartInstanceStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PreStartClusterSequence.java // public class PreStartClusterSequence // extends DefaultClusterStepSequence // { // // public PreStartClusterSequence() // { // add(new ValidateInstanceCountStep()); // add(new ValidateBaseDirectoryStep()); // add(new ValidateFlavourStep()); // add(new ValidateVersionStep()); // add(new ValidateClusterNameStep()); // add(new ValidateUniquePortsStep()); // add(new ValidatePortsStep()); // add(new ValidatePathConfStep()); // } // }
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartClusterSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartInstanceSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PreStartClusterSequence;
getLog().info("Skipping plugin execution"); return; } ClusterConfiguration clusterConfig = buildClusterConfiguration(); new PreStartClusterSequence().execute(clusterConfig); for (InstanceConfiguration config : clusterConfig.getInstanceConfigurationList()) { getLog().info(String.format( "Using Elasticsearch [%d] configuration: %s", config.getId(), config)); try { ForkedInstance instance = new ForkedInstance(config); instance.configureInstance(); Thread thread = new Thread(instance); thread.start(); new PostStartInstanceSequence().execute(config); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } }
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartClusterSequence.java // public class PostStartClusterSequence // extends DefaultClusterStepSequence // { // // public PostStartClusterSequence() // { // add(new WaitToStartClusterStep()); // add(new BootstrapClusterStep()); // add(new BlockProcessExecutionStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PostStartInstanceSequence.java // public class PostStartInstanceSequence // extends DefaultInstanceStepSequence // { // // public PostStartInstanceSequence() // { // add(new WaitToStartInstanceStep()); // } // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/step/PreStartClusterSequence.java // public class PreStartClusterSequence // extends DefaultClusterStepSequence // { // // public PreStartClusterSequence() // { // add(new ValidateInstanceCountStep()); // add(new ValidateBaseDirectoryStep()); // add(new ValidateFlavourStep()); // add(new ValidateVersionStep()); // add(new ValidateClusterNameStep()); // add(new ValidateUniquePortsStep()); // add(new ValidatePortsStep()); // add(new ValidatePathConfStep()); // } // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/RunForkedMojo.java import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartClusterSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PostStartInstanceSequence; import com.github.alexcojocaru.mojo.elasticsearch.v2.step.PreStartClusterSequence; getLog().info("Skipping plugin execution"); return; } ClusterConfiguration clusterConfig = buildClusterConfiguration(); new PreStartClusterSequence().execute(clusterConfig); for (InstanceConfiguration config : clusterConfig.getInstanceConfigurationList()) { getLog().info(String.format( "Using Elasticsearch [%d] configuration: %s", config.getId(), config)); try { ForkedInstance instance = new ForkedInstance(config); instance.configureInstance(); Thread thread = new Thread(instance); thread.start(); new PostStartInstanceSequence().execute(config); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } }
new PostStartClusterSequence().execute(clusterConfig);
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/MyArtifactResolver.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ArtifactException.java // public class ArtifactException extends Exception { // // private static final long serialVersionUID = -3217334010123902842L; // // public ArtifactException(String message, Throwable cause) { // super(message, cause); // } // // public ArtifactException(Throwable cause) { // super(cause); // } // // public ArtifactException(String message) { // super(message); // } // // }
import java.io.File; import java.util.List; import org.apache.maven.plugin.logging.Log; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ArtifactException;
/** * Copyright (C) 2010-2012 Joerg Bellmann <joerg.bellmann@googlemail.com> * * 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.github.alexcojocaru.mojo.elasticsearch.v2; /** * Copied from the t7mp project. * Uses Maven-API to resolve the Artifacts. */ public class MyArtifactResolver implements PluginArtifactResolver { private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySession; private final List<RemoteRepository> remoteRepositories; private final Log log; public MyArtifactResolver(RepositorySystem repositorySystem, RepositorySystemSession repositorySession, List<RemoteRepository> remoteRepositories, Log log) { this.repositorySystem = repositorySystem; this.repositorySession = repositorySession; this.remoteRepositories = remoteRepositories; this.log = log; } /** * Resolves an Artifact from the repositories. * * @param coordinates The artifact coordinates * @return The local file resolved/downloaded for the given coordinates * @throws ArtifactException If the artifact cannot be resolved */ @Override
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactResolver.java // public interface PluginArtifactResolver // { // File resolveArtifact(String coordinates) throws ArtifactException; // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ArtifactException.java // public class ArtifactException extends Exception { // // private static final long serialVersionUID = -3217334010123902842L; // // public ArtifactException(String message, Throwable cause) { // super(message, cause); // } // // public ArtifactException(Throwable cause) { // super(cause); // } // // public ArtifactException(String message) { // super(message); // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/MyArtifactResolver.java import java.io.File; import java.util.List; import org.apache.maven.plugin.logging.Log; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactResolver; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ArtifactException; /** * Copyright (C) 2010-2012 Joerg Bellmann <joerg.bellmann@googlemail.com> * * 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.github.alexcojocaru.mojo.elasticsearch.v2; /** * Copied from the t7mp project. * Uses Maven-API to resolve the Artifacts. */ public class MyArtifactResolver implements PluginArtifactResolver { private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySession; private final List<RemoteRepository> remoteRepositories; private final Log log; public MyArtifactResolver(RepositorySystem repositorySystem, RepositorySystemSession repositorySession, List<RemoteRepository> remoteRepositories, Log log) { this.repositorySystem = repositorySystem; this.repositorySession = repositorySession; this.remoteRepositories = remoteRepositories; this.log = log; } /** * Resolves an Artifact from the repositories. * * @param coordinates The artifact coordinates * @return The local file resolved/downloaded for the given coordinates * @throws ArtifactException If the artifact cannot be resolved */ @Override
public File resolveArtifact(String coordinates) throws ArtifactException
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/MyArtifactInstaller.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ArtifactException.java // public class ArtifactException extends Exception { // // private static final long serialVersionUID = -3217334010123902842L; // // public ArtifactException(String message, Throwable cause) { // super(message, cause); // } // // public ArtifactException(Throwable cause) { // super(cause); // } // // public ArtifactException(String message) { // super(message); // } // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // }
import java.io.File; import org.apache.maven.plugin.logging.Log; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.installation.InstallRequest; import org.eclipse.aether.installation.InstallationException; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ArtifactException; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller;
package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * @author Alex Cojocaru */ public class MyArtifactInstaller implements PluginArtifactInstaller { private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySession; private final Log log; public MyArtifactInstaller(RepositorySystem repositorySystem, RepositorySystemSession repositorySession, Log log) { this.repositorySystem = repositorySystem; this.repositorySession = repositorySession; this.log = log; } @Override
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ArtifactException.java // public class ArtifactException extends Exception { // // private static final long serialVersionUID = -3217334010123902842L; // // public ArtifactException(String message, Throwable cause) { // super(message, cause); // } // // public ArtifactException(Throwable cause) { // super(cause); // } // // public ArtifactException(String message) { // super(message); // } // // } // // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java // public interface PluginArtifactInstaller // { // // void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException; // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/MyArtifactInstaller.java import java.io.File; import org.apache.maven.plugin.logging.Log; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.installation.InstallRequest; import org.eclipse.aether.installation.InstallationException; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.ArtifactException; import com.github.alexcojocaru.mojo.elasticsearch.v2.configuration.PluginArtifactInstaller; package com.github.alexcojocaru.mojo.elasticsearch.v2; /** * @author Alex Cojocaru */ public class MyArtifactInstaller implements PluginArtifactInstaller { private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySession; private final Log log; public MyArtifactInstaller(RepositorySystem repositorySystem, RepositorySystemSession repositorySession, Log log) { this.repositorySystem = repositorySystem; this.repositorySession = repositorySession; this.log = log; } @Override
public void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ElasticsearchConfiguration.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/PluginConfiguration.java // public class PluginConfiguration // { // private String uri; // private String esJavaOpts; // // // public String getUri() // { // return uri; // } // // public String getEsJavaOpts() // { // return esJavaOpts; // } // // public void setUri(String uri) // { // this.uri = uri; // } // // public void setEsJavaOpts(String esJavaOpts) // { // this.esJavaOpts = esJavaOpts; // } // // @Override // public String toString() // { // return new ToStringBuilder(this) // .append("uri", uri) // .append("esJavaOpts", esJavaOpts) // .toString(); // } // // }
import java.util.List; import com.github.alexcojocaru.mojo.elasticsearch.v2.PluginConfiguration;
package com.github.alexcojocaru.mojo.elasticsearch.v2.configuration; /** * The more complete configuration of an ES mojo. * * @author Alex Cojocaru * */ public interface ElasticsearchConfiguration extends ElasticsearchBaseConfiguration { String getVersion(); String getClusterName(); int getHttpPort(); int getTransportPort(); String getPathConf(); String getPathData(); String getPathLogs();
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/PluginConfiguration.java // public class PluginConfiguration // { // private String uri; // private String esJavaOpts; // // // public String getUri() // { // return uri; // } // // public String getEsJavaOpts() // { // return esJavaOpts; // } // // public void setUri(String uri) // { // this.uri = uri; // } // // public void setEsJavaOpts(String esJavaOpts) // { // this.esJavaOpts = esJavaOpts; // } // // @Override // public String toString() // { // return new ToStringBuilder(this) // .append("uri", uri) // .append("esJavaOpts", esJavaOpts) // .toString(); // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/ElasticsearchConfiguration.java import java.util.List; import com.github.alexcojocaru.mojo.elasticsearch.v2.PluginConfiguration; package com.github.alexcojocaru.mojo.elasticsearch.v2.configuration; /** * The more complete configuration of an ES mojo. * * @author Alex Cojocaru * */ public interface ElasticsearchConfiguration extends ElasticsearchBaseConfiguration { String getVersion(); String getClusterName(); int getHttpPort(); int getTransportPort(); String getPathConf(); String getPathData(); String getPathLogs();
List<PluginConfiguration> getPlugins();
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ElasticsearchArtifact.java // public class ElasticsearchArtifact // extends AbstractArtifact // { // public static final String ELASTICSEARCH_GROUPID = "com.github.alexcojocaru"; // // public ElasticsearchArtifact( // final String artifactId, // final String version, // final String classifier, // final String type) // { // super(ELASTICSEARCH_GROUPID, artifactId, version, classifier, type); // } // // @Override // public String getType() // { // return type; // } // // public String buildBundleFilename() // { // return Joiner // .on("-") // .skipNulls() // .join(getArtifactId(), getVersion(), getClassifier() /* May be null */) // + "." + getType(); // } // // @Override // public String toString() // { // return "ElasticsearchArtifact[" + super.getArtifactCoordinates() + "]"; // } // // // public static class ElasticsearchArtifactBuilder // { // private ClusterConfiguration clusterConfig; // // public ElasticsearchArtifactBuilder withClusterConfig(ClusterConfiguration clusterConfig) // { // this.clusterConfig = clusterConfig; // return this; // } // // public ElasticsearchArtifact build() // { // String flavour = clusterConfig.getFlavour(); // String version = clusterConfig.getVersion(); // // String id = getArtifactId(flavour, version); // String classifier = getArtifactClassifier(version); // String type = getArtifactType(version); // // return new ElasticsearchArtifact(id, version, classifier, type); // } // // private String getArtifactId(String flavour, String version) // { // if (VersionUtil.isBetween_6_3_0_and_7_10_x(version)) // { // if (StringUtils.isEmpty(flavour)) // { // return "elasticsearch-oss"; // } // else if ("default".equals(flavour)) // { // return "elasticsearch"; // } // else // { // return String.format("elasticsearch-%s", flavour); // } // } // else { // return "elasticsearch"; // } // } // // private String getArtifactClassifier(String version) // { // if (VersionUtil.isEqualOrGreater_7_0_0(version)) // { // if (SystemUtils.IS_OS_WINDOWS) // { // return "windows-x86_64"; // } // else if (SystemUtils.IS_OS_MAC) // { // return "darwin-x86_64"; // } // else if (SystemUtils.IS_OS_LINUX) // { // return "linux-x86_64"; // } // else { // throw new IllegalStateException("Unknown OS, cannot determine the Elasticsearch classifier."); // } // } // else // No classifier for ES below 7.0.0 // { // return null; // } // } // // private String getArtifactType(String version) // { // if (VersionUtil.isEqualOrGreater_7_0_0(version)) // { // if (SystemUtils.IS_OS_WINDOWS) // { // return "zip"; // } // else if (SystemUtils.IS_OS_MAC) // { // return "tar.gz"; // } // else if (SystemUtils.IS_OS_LINUX) // { // return "tar.gz"; // } // else { // throw new IllegalStateException("Unknown OS, cannot determine the Elasticsearch classifier."); // } // } // else // Only a single artifact type below 7.0.0 // { // return "zip"; // } // } // } // // }
import java.io.File; import com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchArtifact;
package com.github.alexcojocaru.mojo.elasticsearch.v2.configuration; /** * @author Alex Cojocaru * */ public interface PluginArtifactInstaller {
// Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/ElasticsearchArtifact.java // public class ElasticsearchArtifact // extends AbstractArtifact // { // public static final String ELASTICSEARCH_GROUPID = "com.github.alexcojocaru"; // // public ElasticsearchArtifact( // final String artifactId, // final String version, // final String classifier, // final String type) // { // super(ELASTICSEARCH_GROUPID, artifactId, version, classifier, type); // } // // @Override // public String getType() // { // return type; // } // // public String buildBundleFilename() // { // return Joiner // .on("-") // .skipNulls() // .join(getArtifactId(), getVersion(), getClassifier() /* May be null */) // + "." + getType(); // } // // @Override // public String toString() // { // return "ElasticsearchArtifact[" + super.getArtifactCoordinates() + "]"; // } // // // public static class ElasticsearchArtifactBuilder // { // private ClusterConfiguration clusterConfig; // // public ElasticsearchArtifactBuilder withClusterConfig(ClusterConfiguration clusterConfig) // { // this.clusterConfig = clusterConfig; // return this; // } // // public ElasticsearchArtifact build() // { // String flavour = clusterConfig.getFlavour(); // String version = clusterConfig.getVersion(); // // String id = getArtifactId(flavour, version); // String classifier = getArtifactClassifier(version); // String type = getArtifactType(version); // // return new ElasticsearchArtifact(id, version, classifier, type); // } // // private String getArtifactId(String flavour, String version) // { // if (VersionUtil.isBetween_6_3_0_and_7_10_x(version)) // { // if (StringUtils.isEmpty(flavour)) // { // return "elasticsearch-oss"; // } // else if ("default".equals(flavour)) // { // return "elasticsearch"; // } // else // { // return String.format("elasticsearch-%s", flavour); // } // } // else { // return "elasticsearch"; // } // } // // private String getArtifactClassifier(String version) // { // if (VersionUtil.isEqualOrGreater_7_0_0(version)) // { // if (SystemUtils.IS_OS_WINDOWS) // { // return "windows-x86_64"; // } // else if (SystemUtils.IS_OS_MAC) // { // return "darwin-x86_64"; // } // else if (SystemUtils.IS_OS_LINUX) // { // return "linux-x86_64"; // } // else { // throw new IllegalStateException("Unknown OS, cannot determine the Elasticsearch classifier."); // } // } // else // No classifier for ES below 7.0.0 // { // return null; // } // } // // private String getArtifactType(String version) // { // if (VersionUtil.isEqualOrGreater_7_0_0(version)) // { // if (SystemUtils.IS_OS_WINDOWS) // { // return "zip"; // } // else if (SystemUtils.IS_OS_MAC) // { // return "tar.gz"; // } // else if (SystemUtils.IS_OS_LINUX) // { // return "tar.gz"; // } // else { // throw new IllegalStateException("Unknown OS, cannot determine the Elasticsearch classifier."); // } // } // else // Only a single artifact type below 7.0.0 // { // return "zip"; // } // } // } // // } // Path: src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/configuration/PluginArtifactInstaller.java import java.io.File; import com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchArtifact; package com.github.alexcojocaru.mojo.elasticsearch.v2.configuration; /** * @author Alex Cojocaru * */ public interface PluginArtifactInstaller {
void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException;
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/controller/AuthenticationController.java
// Path: server/src/main/java/com/changeme/controller/utils/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: server/src/main/java/com/changeme/controller/utils/AuthenticationResponse.java // public class AuthenticationResponse { // // private String token; // // public AuthenticationResponse() { // } // // public AuthenticationResponse(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: server/src/main/java/com/changeme/security/TokenUtils.java // @Component // public class TokenUtils { // @Value("${changeme.token.secret}") // private String secret; // @Value("${changeme.token.expiration}") // private long expiration; // // public String getUsernameFromToken(String token) { // String username; // try { // username = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getSubject(); // } catch (Exception e) { // username = null; // } // return username; // } // // private Date getExpirationDate(String token) { // Date expiration; // try { // expiration = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getExpiration(); // } catch (Exception e) { // expiration = null; // } // return expiration; // } // // public String generateToken(UserDetails userDetails) { // return Jwts.builder() // .setSubject(userDetails.getUsername()) // .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) // .signWith(SignatureAlgorithm.HS512, secret) // .compact(); // } // // public boolean validateToken(String token, UserDetails userDetails) { // final String username = getUsernameFromToken(token); // final Date expiration = getExpirationDate(token); // return username.equals(userDetails.getUsername()) && // expiration.after(new Date(System.currentTimeMillis())); // } // // // }
import com.changeme.controller.utils.AuthenticationRequest; import com.changeme.controller.utils.AuthenticationResponse; import com.changeme.security.TokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package com.changeme.controller; @RestController @RequestMapping(path = "/public") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired
// Path: server/src/main/java/com/changeme/controller/utils/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: server/src/main/java/com/changeme/controller/utils/AuthenticationResponse.java // public class AuthenticationResponse { // // private String token; // // public AuthenticationResponse() { // } // // public AuthenticationResponse(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: server/src/main/java/com/changeme/security/TokenUtils.java // @Component // public class TokenUtils { // @Value("${changeme.token.secret}") // private String secret; // @Value("${changeme.token.expiration}") // private long expiration; // // public String getUsernameFromToken(String token) { // String username; // try { // username = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getSubject(); // } catch (Exception e) { // username = null; // } // return username; // } // // private Date getExpirationDate(String token) { // Date expiration; // try { // expiration = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getExpiration(); // } catch (Exception e) { // expiration = null; // } // return expiration; // } // // public String generateToken(UserDetails userDetails) { // return Jwts.builder() // .setSubject(userDetails.getUsername()) // .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) // .signWith(SignatureAlgorithm.HS512, secret) // .compact(); // } // // public boolean validateToken(String token, UserDetails userDetails) { // final String username = getUsernameFromToken(token); // final Date expiration = getExpirationDate(token); // return username.equals(userDetails.getUsername()) && // expiration.after(new Date(System.currentTimeMillis())); // } // // // } // Path: server/src/main/java/com/changeme/controller/AuthenticationController.java import com.changeme.controller.utils.AuthenticationRequest; import com.changeme.controller.utils.AuthenticationResponse; import com.changeme.security.TokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package com.changeme.controller; @RestController @RequestMapping(path = "/public") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired
private TokenUtils tokenUtils;
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/controller/AuthenticationController.java
// Path: server/src/main/java/com/changeme/controller/utils/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: server/src/main/java/com/changeme/controller/utils/AuthenticationResponse.java // public class AuthenticationResponse { // // private String token; // // public AuthenticationResponse() { // } // // public AuthenticationResponse(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: server/src/main/java/com/changeme/security/TokenUtils.java // @Component // public class TokenUtils { // @Value("${changeme.token.secret}") // private String secret; // @Value("${changeme.token.expiration}") // private long expiration; // // public String getUsernameFromToken(String token) { // String username; // try { // username = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getSubject(); // } catch (Exception e) { // username = null; // } // return username; // } // // private Date getExpirationDate(String token) { // Date expiration; // try { // expiration = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getExpiration(); // } catch (Exception e) { // expiration = null; // } // return expiration; // } // // public String generateToken(UserDetails userDetails) { // return Jwts.builder() // .setSubject(userDetails.getUsername()) // .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) // .signWith(SignatureAlgorithm.HS512, secret) // .compact(); // } // // public boolean validateToken(String token, UserDetails userDetails) { // final String username = getUsernameFromToken(token); // final Date expiration = getExpirationDate(token); // return username.equals(userDetails.getUsername()) && // expiration.after(new Date(System.currentTimeMillis())); // } // // // }
import com.changeme.controller.utils.AuthenticationRequest; import com.changeme.controller.utils.AuthenticationResponse; import com.changeme.security.TokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package com.changeme.controller; @RestController @RequestMapping(path = "/public") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenUtils tokenUtils; @Autowired private UserDetailsService userDetailsService; @RequestMapping(method = RequestMethod.POST, value = "/auth")
// Path: server/src/main/java/com/changeme/controller/utils/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: server/src/main/java/com/changeme/controller/utils/AuthenticationResponse.java // public class AuthenticationResponse { // // private String token; // // public AuthenticationResponse() { // } // // public AuthenticationResponse(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: server/src/main/java/com/changeme/security/TokenUtils.java // @Component // public class TokenUtils { // @Value("${changeme.token.secret}") // private String secret; // @Value("${changeme.token.expiration}") // private long expiration; // // public String getUsernameFromToken(String token) { // String username; // try { // username = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getSubject(); // } catch (Exception e) { // username = null; // } // return username; // } // // private Date getExpirationDate(String token) { // Date expiration; // try { // expiration = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getExpiration(); // } catch (Exception e) { // expiration = null; // } // return expiration; // } // // public String generateToken(UserDetails userDetails) { // return Jwts.builder() // .setSubject(userDetails.getUsername()) // .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) // .signWith(SignatureAlgorithm.HS512, secret) // .compact(); // } // // public boolean validateToken(String token, UserDetails userDetails) { // final String username = getUsernameFromToken(token); // final Date expiration = getExpirationDate(token); // return username.equals(userDetails.getUsername()) && // expiration.after(new Date(System.currentTimeMillis())); // } // // // } // Path: server/src/main/java/com/changeme/controller/AuthenticationController.java import com.changeme.controller.utils.AuthenticationRequest; import com.changeme.controller.utils.AuthenticationResponse; import com.changeme.security.TokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package com.changeme.controller; @RestController @RequestMapping(path = "/public") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenUtils tokenUtils; @Autowired private UserDetailsService userDetailsService; @RequestMapping(method = RequestMethod.POST, value = "/auth")
public ResponseEntity<?> authenticationRequest(@RequestBody AuthenticationRequest authenticationRequest)
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/controller/AuthenticationController.java
// Path: server/src/main/java/com/changeme/controller/utils/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: server/src/main/java/com/changeme/controller/utils/AuthenticationResponse.java // public class AuthenticationResponse { // // private String token; // // public AuthenticationResponse() { // } // // public AuthenticationResponse(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: server/src/main/java/com/changeme/security/TokenUtils.java // @Component // public class TokenUtils { // @Value("${changeme.token.secret}") // private String secret; // @Value("${changeme.token.expiration}") // private long expiration; // // public String getUsernameFromToken(String token) { // String username; // try { // username = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getSubject(); // } catch (Exception e) { // username = null; // } // return username; // } // // private Date getExpirationDate(String token) { // Date expiration; // try { // expiration = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getExpiration(); // } catch (Exception e) { // expiration = null; // } // return expiration; // } // // public String generateToken(UserDetails userDetails) { // return Jwts.builder() // .setSubject(userDetails.getUsername()) // .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) // .signWith(SignatureAlgorithm.HS512, secret) // .compact(); // } // // public boolean validateToken(String token, UserDetails userDetails) { // final String username = getUsernameFromToken(token); // final Date expiration = getExpirationDate(token); // return username.equals(userDetails.getUsername()) && // expiration.after(new Date(System.currentTimeMillis())); // } // // // }
import com.changeme.controller.utils.AuthenticationRequest; import com.changeme.controller.utils.AuthenticationResponse; import com.changeme.security.TokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package com.changeme.controller; @RestController @RequestMapping(path = "/public") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenUtils tokenUtils; @Autowired private UserDetailsService userDetailsService; @RequestMapping(method = RequestMethod.POST, value = "/auth") public ResponseEntity<?> authenticationRequest(@RequestBody AuthenticationRequest authenticationRequest) throws AuthenticationException { // Perform the authentication Authentication authentication = null; try { authentication = this.authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword() ) ); } catch (BadCredentialsException e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); } catch (AuthenticationException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); } System.out.println("Authentication is done"); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-authentication so we can generate token UserDetails userDetails = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); String token = this.tokenUtils.generateToken(userDetails); // Return the token
// Path: server/src/main/java/com/changeme/controller/utils/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: server/src/main/java/com/changeme/controller/utils/AuthenticationResponse.java // public class AuthenticationResponse { // // private String token; // // public AuthenticationResponse() { // } // // public AuthenticationResponse(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: server/src/main/java/com/changeme/security/TokenUtils.java // @Component // public class TokenUtils { // @Value("${changeme.token.secret}") // private String secret; // @Value("${changeme.token.expiration}") // private long expiration; // // public String getUsernameFromToken(String token) { // String username; // try { // username = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getSubject(); // } catch (Exception e) { // username = null; // } // return username; // } // // private Date getExpirationDate(String token) { // Date expiration; // try { // expiration = Jwts.parser() // .setSigningKey(secret) // .parseClaimsJws(token) // .getBody() // .getExpiration(); // } catch (Exception e) { // expiration = null; // } // return expiration; // } // // public String generateToken(UserDetails userDetails) { // return Jwts.builder() // .setSubject(userDetails.getUsername()) // .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) // .signWith(SignatureAlgorithm.HS512, secret) // .compact(); // } // // public boolean validateToken(String token, UserDetails userDetails) { // final String username = getUsernameFromToken(token); // final Date expiration = getExpirationDate(token); // return username.equals(userDetails.getUsername()) && // expiration.after(new Date(System.currentTimeMillis())); // } // // // } // Path: server/src/main/java/com/changeme/controller/AuthenticationController.java import com.changeme.controller.utils.AuthenticationRequest; import com.changeme.controller.utils.AuthenticationResponse; import com.changeme.security.TokenUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package com.changeme.controller; @RestController @RequestMapping(path = "/public") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenUtils tokenUtils; @Autowired private UserDetailsService userDetailsService; @RequestMapping(method = RequestMethod.POST, value = "/auth") public ResponseEntity<?> authenticationRequest(@RequestBody AuthenticationRequest authenticationRequest) throws AuthenticationException { // Perform the authentication Authentication authentication = null; try { authentication = this.authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword() ) ); } catch (BadCredentialsException e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); } catch (AuthenticationException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); } System.out.println("Authentication is done"); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-authentication so we can generate token UserDetails userDetails = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); String token = this.tokenUtils.generateToken(userDetails); // Return the token
return ResponseEntity.ok(new AuthenticationResponse(token));
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/security/SecurityConfiguration.java
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // }
import com.changeme.repository.UserProfile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.http.HttpServletResponse;
package com.changeme.security; @Profile("development") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserProfileDetailsService userProfileDetailsService; @Override public void configure(AuthenticationManagerBuilder auth) throws Exception {
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // Path: server/src/main/java/com/changeme/security/SecurityConfiguration.java import com.changeme.repository.UserProfile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.http.HttpServletResponse; package com.changeme.security; @Profile("development") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserProfileDetailsService userProfileDetailsService; @Override public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userProfileDetailsService).passwordEncoder(UserProfile.PASSWORD_ENCODER);
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/security/UserProfileDetailsService.java
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // }
import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component;
package com.changeme.security; @Component public class UserProfileDetailsService implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserProfileDetailsService.class);
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // } // Path: server/src/main/java/com/changeme/security/UserProfileDetailsService.java import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; package com.changeme.security; @Component public class UserProfileDetailsService implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserProfileDetailsService.class);
private UserProfileRepository repository;
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/security/UserProfileDetailsService.java
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // }
import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component;
package com.changeme.security; @Component public class UserProfileDetailsService implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserProfileDetailsService.class); private UserProfileRepository repository; @Autowired public UserProfileDetailsService(UserProfileRepository userProfileRepository) { this.repository = userProfileRepository; } @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { log.info("Fetching user " + s);
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // } // Path: server/src/main/java/com/changeme/security/UserProfileDetailsService.java import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; package com.changeme.security; @Component public class UserProfileDetailsService implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserProfileDetailsService.class); private UserProfileRepository repository; @Autowired public UserProfileDetailsService(UserProfileRepository userProfileRepository) { this.repository = userProfileRepository; } @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { log.info("Fetching user " + s);
UserProfile userProfile = repository.findByUsername(s);
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/controller/UserProfileController.java
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // }
import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.security.Principal;
package com.changeme.controller; @RestController @RequestMapping(path = "/secure") public class UserProfileController { @Autowired
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // } // Path: server/src/main/java/com/changeme/controller/UserProfileController.java import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.security.Principal; package com.changeme.controller; @RestController @RequestMapping(path = "/secure") public class UserProfileController { @Autowired
private UserProfileRepository userProfileRepository;
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/controller/UserProfileController.java
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // }
import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.security.Principal;
package com.changeme.controller; @RestController @RequestMapping(path = "/secure") public class UserProfileController { @Autowired private UserProfileRepository userProfileRepository; @RequestMapping(method = RequestMethod.GET, value = "/user/profile") @PreAuthorize("hasAuthority('USER')") public ResponseEntity<?> authenticationRequest(HttpServletRequest request){ Principal user = request.getUserPrincipal(); if(user != null){
// Path: server/src/main/java/com/changeme/repository/UserProfile.java // @Entity // @Table(name = "user_profile") // public class UserProfile { // // public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); // // @Id // @Column(name = "id") // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Long id; // @Column(name = "username") // private String username; // @JsonIgnore // @Column(name = "password") // private String password; // @Column(name = "authorities") // private String authorities; // // public UserProfile() { // } // // public UserProfile(String username, String password, String roles) { // this.setUsername(username); // this.setPassword(password); // this.setAuthorities(roles); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = PASSWORD_ENCODER.encode(password); // } // // public String getAuthorities() { // return this.authorities; // } // // public void setAuthorities(String authorities) { // this.authorities = authorities; // } // // // } // // Path: server/src/main/java/com/changeme/repository/UserProfileRepository.java // @RepositoryRestResource(exported = false) // public interface UserProfileRepository extends CrudRepository<UserProfile, Long> { // // UserProfile findByUsername(String username); // // } // Path: server/src/main/java/com/changeme/controller/UserProfileController.java import com.changeme.repository.UserProfile; import com.changeme.repository.UserProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.security.Principal; package com.changeme.controller; @RestController @RequestMapping(path = "/secure") public class UserProfileController { @Autowired private UserProfileRepository userProfileRepository; @RequestMapping(method = RequestMethod.GET, value = "/user/profile") @PreAuthorize("hasAuthority('USER')") public ResponseEntity<?> authenticationRequest(HttpServletRequest request){ Principal user = request.getUserPrincipal(); if(user != null){
UserProfile userProfile = userProfileRepository.findByUsername(user.getName());
ipselon/sdr-bootstrap-prepack
server/src/main/java/com/changeme/Application.java
// Path: server/src/main/java/com/changeme/service/DataInitialization.java // @Service // public class DataInitialization { // // private static final String[] departmentNames = { // "Front Office", "Reservations", "Housekeeping", "Concierge", "Guest service", "Security", "Communication" // }; // // private static final String[] lastNames = { // "Dough", "Longhorn", "Smith", "Lee", "Ferguson", "March", "Dark" // }; // // private static final String[] firstNames = { // "Ann", "John", "Eliot", "George", "Marian", "Julia", "Elvis" // }; // // private static final NumberFormat numberFormat = new DecimalFormat("###.00"); // // @Autowired // private DepartmentRepository departmentRepository; // // @Autowired // private AccessLevelRepository accessLevelRepository; // // @Autowired // private PersonRepository personRepository; // // @PostConstruct // public void init(){ // // Locale.setDefault(Locale.US); // // List<AccessLevel> accessLevels = new ArrayList<>(); // for(int i = 0; i < departmentNames.length; i++){ // AccessLevel accessLevel = new AccessLevel(); // accessLevel.setDescription("Level " + (i + 1)); // accessLevelRepository.save(accessLevel); // accessLevels.add(accessLevel); // } // // List<Department> departments = new ArrayList<Department>(); // for(int i = 0; i < departmentNames.length; i++){ // Department department = new Department(); // department.setName(departmentNames[i]); // department.setAccessLevel(accessLevels.get(i)); // departmentRepository.save(department); // departments.add(department); // } // // Calendar cal = Calendar.getInstance(); // Random rnd = new Random(); // for(int i = 0, d = 0; i < departmentNames.length * 2; i++, d += 2){ // // cal.set(1980 + rnd.nextInt(10), Calendar.MAY, 17 + rnd.nextInt(10)); // // Person person = new Person(); // try { // person.setSalary(numberFormat.parse(numberFormat.format(rnd.nextDouble() * 1000)).floatValue()); // } catch (ParseException e) { // e.printStackTrace(); // } // person.setBirthDate(new Date(cal.getTimeInMillis())); // person.setFirstName(firstNames[rnd.nextInt(firstNames.length - 1)]); // person.setLastName(lastNames[rnd.nextInt(lastNames.length - 1)]); // person.setDepartment(departments.get(rnd.nextInt(departments.size() - 1))); // personRepository.save(person); // } // // } // // }
import com.changeme.service.DataInitialization; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.EnableTransactionManagement;
package com.changeme; @SpringBootApplication @ComponentScan("com.changeme") @EnableTransactionManagement public class Application { @Autowired
// Path: server/src/main/java/com/changeme/service/DataInitialization.java // @Service // public class DataInitialization { // // private static final String[] departmentNames = { // "Front Office", "Reservations", "Housekeeping", "Concierge", "Guest service", "Security", "Communication" // }; // // private static final String[] lastNames = { // "Dough", "Longhorn", "Smith", "Lee", "Ferguson", "March", "Dark" // }; // // private static final String[] firstNames = { // "Ann", "John", "Eliot", "George", "Marian", "Julia", "Elvis" // }; // // private static final NumberFormat numberFormat = new DecimalFormat("###.00"); // // @Autowired // private DepartmentRepository departmentRepository; // // @Autowired // private AccessLevelRepository accessLevelRepository; // // @Autowired // private PersonRepository personRepository; // // @PostConstruct // public void init(){ // // Locale.setDefault(Locale.US); // // List<AccessLevel> accessLevels = new ArrayList<>(); // for(int i = 0; i < departmentNames.length; i++){ // AccessLevel accessLevel = new AccessLevel(); // accessLevel.setDescription("Level " + (i + 1)); // accessLevelRepository.save(accessLevel); // accessLevels.add(accessLevel); // } // // List<Department> departments = new ArrayList<Department>(); // for(int i = 0; i < departmentNames.length; i++){ // Department department = new Department(); // department.setName(departmentNames[i]); // department.setAccessLevel(accessLevels.get(i)); // departmentRepository.save(department); // departments.add(department); // } // // Calendar cal = Calendar.getInstance(); // Random rnd = new Random(); // for(int i = 0, d = 0; i < departmentNames.length * 2; i++, d += 2){ // // cal.set(1980 + rnd.nextInt(10), Calendar.MAY, 17 + rnd.nextInt(10)); // // Person person = new Person(); // try { // person.setSalary(numberFormat.parse(numberFormat.format(rnd.nextDouble() * 1000)).floatValue()); // } catch (ParseException e) { // e.printStackTrace(); // } // person.setBirthDate(new Date(cal.getTimeInMillis())); // person.setFirstName(firstNames[rnd.nextInt(firstNames.length - 1)]); // person.setLastName(lastNames[rnd.nextInt(lastNames.length - 1)]); // person.setDepartment(departments.get(rnd.nextInt(departments.size() - 1))); // personRepository.save(person); // } // // } // // } // Path: server/src/main/java/com/changeme/Application.java import com.changeme.service.DataInitialization; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.EnableTransactionManagement; package com.changeme; @SpringBootApplication @ComponentScan("com.changeme") @EnableTransactionManagement public class Application { @Autowired
private DataInitialization dataInitialization;
dimensoft/improved-journey
src/main/java/com/ilog/flume/source/tail/FileTailerSource.java
// Path: src/main/java/com/ilog/util/security/PropertyUtil.java // public class PropertyUtil { // private static Logger logger = Logger.getLogger(PropertyUtil.class); // // /** // * 获取当前项目配置文件根路径 // * @return java.lang.String // */ // // public static String getCurrentConfPath() { // String c_path = PropertyUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // String os_name = System.getProperty("os.name").toLowerCase(); // c_path = os_name.startsWith("win") ? c_path.substring(1, c_path.lastIndexOf("/") + 1) : c_path.substring(0, c_path.lastIndexOf("/") + 1); // return c_path + "../conf/"; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.EventDrivenSource; import org.apache.flume.conf.Configurable; import org.apache.flume.event.EventBuilder; import org.apache.flume.source.AbstractSource; import org.apache.log4j.PropertyConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ilog.util.security.PropertyUtil;
if(headers != null){ eventList.add(EventBuilder.withBody(body, headers)); } if (eventList.size()>0 && (eventList.size() == batchUpperLimit || timeInterval>=TIME_INTERVAL)) {//批量提交Event getChannelProcessor().processEventBatch(eventList); eventList.clear(); startTime = cur; } } public synchronized void stop() { log.info("File Tailer Source is stopping."); //确保读取信息写入磁盘文件不丢失 tailer.stop(); //实时采集主题程序 if(log.isInfoEnabled()){ log.info("file tailer is stopped,wait for bakup marks while sleeping 5s."); } try{ Thread.sleep(5000);// 为了让下一行fReader.readLine()读取不会出现null的情况 }catch(InterruptedException ex){ log.error("File Tailer Source is intterrupted while sleeping.", ex); } this.handle(null, new HashMap<String,String>(){{put(FileTailer.FLUME_STOP_TIMER_KEY,null);}});//保证event及时刷新 super.stop(); log.info("File Tailer Source is stopped."); } public void configure(Context context) { batchUpperLimit = context.getInteger("batchUpperLimit",1);
// Path: src/main/java/com/ilog/util/security/PropertyUtil.java // public class PropertyUtil { // private static Logger logger = Logger.getLogger(PropertyUtil.class); // // /** // * 获取当前项目配置文件根路径 // * @return java.lang.String // */ // // public static String getCurrentConfPath() { // String c_path = PropertyUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // String os_name = System.getProperty("os.name").toLowerCase(); // c_path = os_name.startsWith("win") ? c_path.substring(1, c_path.lastIndexOf("/") + 1) : c_path.substring(0, c_path.lastIndexOf("/") + 1); // return c_path + "../conf/"; // } // } // Path: src/main/java/com/ilog/flume/source/tail/FileTailerSource.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.EventDrivenSource; import org.apache.flume.conf.Configurable; import org.apache.flume.event.EventBuilder; import org.apache.flume.source.AbstractSource; import org.apache.log4j.PropertyConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ilog.util.security.PropertyUtil; if(headers != null){ eventList.add(EventBuilder.withBody(body, headers)); } if (eventList.size()>0 && (eventList.size() == batchUpperLimit || timeInterval>=TIME_INTERVAL)) {//批量提交Event getChannelProcessor().processEventBatch(eventList); eventList.clear(); startTime = cur; } } public synchronized void stop() { log.info("File Tailer Source is stopping."); //确保读取信息写入磁盘文件不丢失 tailer.stop(); //实时采集主题程序 if(log.isInfoEnabled()){ log.info("file tailer is stopped,wait for bakup marks while sleeping 5s."); } try{ Thread.sleep(5000);// 为了让下一行fReader.readLine()读取不会出现null的情况 }catch(InterruptedException ex){ log.error("File Tailer Source is intterrupted while sleeping.", ex); } this.handle(null, new HashMap<String,String>(){{put(FileTailer.FLUME_STOP_TIMER_KEY,null);}});//保证event及时刷新 super.stop(); log.info("File Tailer Source is stopped."); } public void configure(Context context) { batchUpperLimit = context.getInteger("batchUpperLimit",1);
PropertyConfigurator.configure(PropertyUtil.getCurrentConfPath() + "log4j.properties");
dydra/dydra.java
doc/examples/sdk-jena/select.java
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // }
import com.dydra.Repository; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter;
public class select { public static final String REPOSITORY = "jhacker/foaf"; public static final String QUERY = "SELECT * WHERE {?s ?p ?o} LIMIT 10"; public static void main(String[] args) {
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // } // Path: doc/examples/sdk-jena/select.java import com.dydra.Repository; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter; public class select { public static final String REPOSITORY = "jhacker/foaf"; public static final String QUERY = "SELECT * WHERE {?s ?p ?o} LIMIT 10"; public static void main(String[] args) {
QueryExecution exec = new Repository(REPOSITORY).prepareQueryExecution(QUERY);
dydra/dydra.java
doc/examples/sdk-jena/ask.java
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // }
import com.dydra.Repository; import com.hp.hpl.jena.query.QueryExecution;
public class ask { public static final String REPOSITORY = "jhacker/foaf"; public static final String QUERY = "ASK WHERE {?s ?p ?o}"; public static void main(String[] args) {
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // } // Path: doc/examples/sdk-jena/ask.java import com.dydra.Repository; import com.hp.hpl.jena.query.QueryExecution; public class ask { public static final String REPOSITORY = "jhacker/foaf"; public static final String QUERY = "ASK WHERE {?s ?p ?o}"; public static void main(String[] args) {
QueryExecution exec = new Repository(REPOSITORY).prepareQueryExecution(QUERY);
dydra/dydra.java
doc/examples/sdk-jena/construct.java
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // }
import com.dydra.Repository; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.rdf.model.Model;
public class construct { public static final String REPOSITORY = "jhacker/foaf"; public static final String QUERY = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o} LIMIT 10"; public static void main(String[] args) {
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // } // Path: doc/examples/sdk-jena/construct.java import com.dydra.Repository; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.rdf.model.Model; public class construct { public static final String REPOSITORY = "jhacker/foaf"; public static final String QUERY = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o} LIMIT 10"; public static void main(String[] args) {
QueryExecution exec = new Repository(REPOSITORY).prepareQueryExecution(QUERY);
dydra/dydra.java
src/com/dydra/Repository.java
// Path: src/com/dydra/jena/DydraNTripleWriter.java // public class DydraNTripleWriter extends NTripleWriter implements RDFWriter { // @NotNull // public static String formatQuery(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (nodes == null || nodes.length == 0) { // return queryTemplate; // } // else { // final String[] args = new String[nodes.length]; // for (int i = 0; i < nodes.length; i++) { // args[i] = (nodes[i] != null) ? formatNode(nodes[i]) : "[]"; // } // return String.format(queryTemplate, (Object[])args); // } // } // // @NotNull // public static String formatNode(@NotNull final Node node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // if (node instanceof Node_Variable) { // return node.toString(); // special case for variables // } // // final Model model = ModelFactory.createDefaultModel(); // try { // final RDFNode rdfNode = model.getRDFNode(node); // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(rdfNode, new PrintWriter(writer)); // return writer.toString(); // } finally { model.close(); } // } // // @NotNull // public static String formatNode(@NotNull final RDFNode node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(node, new PrintWriter(writer)); // return writer.toString(); // } // } // // Path: src/com/dydra/jena/DydraQueryExecutionFactory.java // public class DydraQueryExecutionFactory { // protected DydraQueryExecutionFactory() {} // // /** // * @param query // * @param repository // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository) { // return new DydraQueryEngine(repository, query); // } // // /** // * @param query // * @param repository // * @param defaultGraphURI // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final String defaultGraphURI) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURI != null) { // engine.addDefaultGraph(defaultGraphURI); // } // return engine; // } // // /** // * @param query // * @param repository // * @param defaultGraphURIs // * @param namedGraphURIs // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final List<String> defaultGraphURIs, // @Nullable final List<String> namedGraphURIs) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURIs != null) { // engine.setDefaultGraphURIs(defaultGraphURIs); // } // if (namedGraphURIs != null) { // engine.setNamedGraphURIs(namedGraphURIs); // } // return engine; // } // }
import com.dydra.annotation.*; import com.dydra.jena.DydraNTripleWriter; import com.dydra.jena.DydraQueryExecutionFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Node_Variable; import com.hp.hpl.jena.graph.TripleMatch; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.update.Update; import com.hp.hpl.jena.update.UpdateExecutionFactory; import com.hp.hpl.jena.update.UpdateProcessor;
@NotNull public Operation importFromURL(@NotNull final String url) { if (url == null) throw new NullPointerException("url cannot be null"); // TODO: call the dydra.repository.import RPC method throw new UnsupportedOperationException("not implemented"); } /** * Prepares to execute the given SPARQL query on this repository. * * Note: this is a Jena-specific method. * * @param queryTemplate * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" * @param triplePattern */ @NotNull public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, @NotNull final TripleMatch triplePattern) { if (queryTemplate == null) throw new NullPointerException("queryTemplate cannot be null"); if (triplePattern == null) throw new NullPointerException("triplePattern cannot be null"); final Node s = triplePattern.getMatchSubject(); final Node p = triplePattern.getMatchPredicate(); final Node o = triplePattern.getMatchObject();
// Path: src/com/dydra/jena/DydraNTripleWriter.java // public class DydraNTripleWriter extends NTripleWriter implements RDFWriter { // @NotNull // public static String formatQuery(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (nodes == null || nodes.length == 0) { // return queryTemplate; // } // else { // final String[] args = new String[nodes.length]; // for (int i = 0; i < nodes.length; i++) { // args[i] = (nodes[i] != null) ? formatNode(nodes[i]) : "[]"; // } // return String.format(queryTemplate, (Object[])args); // } // } // // @NotNull // public static String formatNode(@NotNull final Node node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // if (node instanceof Node_Variable) { // return node.toString(); // special case for variables // } // // final Model model = ModelFactory.createDefaultModel(); // try { // final RDFNode rdfNode = model.getRDFNode(node); // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(rdfNode, new PrintWriter(writer)); // return writer.toString(); // } finally { model.close(); } // } // // @NotNull // public static String formatNode(@NotNull final RDFNode node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(node, new PrintWriter(writer)); // return writer.toString(); // } // } // // Path: src/com/dydra/jena/DydraQueryExecutionFactory.java // public class DydraQueryExecutionFactory { // protected DydraQueryExecutionFactory() {} // // /** // * @param query // * @param repository // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository) { // return new DydraQueryEngine(repository, query); // } // // /** // * @param query // * @param repository // * @param defaultGraphURI // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final String defaultGraphURI) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURI != null) { // engine.addDefaultGraph(defaultGraphURI); // } // return engine; // } // // /** // * @param query // * @param repository // * @param defaultGraphURIs // * @param namedGraphURIs // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final List<String> defaultGraphURIs, // @Nullable final List<String> namedGraphURIs) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURIs != null) { // engine.setDefaultGraphURIs(defaultGraphURIs); // } // if (namedGraphURIs != null) { // engine.setNamedGraphURIs(namedGraphURIs); // } // return engine; // } // } // Path: src/com/dydra/Repository.java import com.dydra.annotation.*; import com.dydra.jena.DydraNTripleWriter; import com.dydra.jena.DydraQueryExecutionFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Node_Variable; import com.hp.hpl.jena.graph.TripleMatch; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.update.Update; import com.hp.hpl.jena.update.UpdateExecutionFactory; import com.hp.hpl.jena.update.UpdateProcessor; @NotNull public Operation importFromURL(@NotNull final String url) { if (url == null) throw new NullPointerException("url cannot be null"); // TODO: call the dydra.repository.import RPC method throw new UnsupportedOperationException("not implemented"); } /** * Prepares to execute the given SPARQL query on this repository. * * Note: this is a Jena-specific method. * * @param queryTemplate * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" * @param triplePattern */ @NotNull public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, @NotNull final TripleMatch triplePattern) { if (queryTemplate == null) throw new NullPointerException("queryTemplate cannot be null"); if (triplePattern == null) throw new NullPointerException("triplePattern cannot be null"); final Node s = triplePattern.getMatchSubject(); final Node p = triplePattern.getMatchPredicate(); final Node o = triplePattern.getMatchObject();
final String queryString = DydraNTripleWriter.formatQuery(queryTemplate,
dydra/dydra.java
src/com/dydra/Repository.java
// Path: src/com/dydra/jena/DydraNTripleWriter.java // public class DydraNTripleWriter extends NTripleWriter implements RDFWriter { // @NotNull // public static String formatQuery(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (nodes == null || nodes.length == 0) { // return queryTemplate; // } // else { // final String[] args = new String[nodes.length]; // for (int i = 0; i < nodes.length; i++) { // args[i] = (nodes[i] != null) ? formatNode(nodes[i]) : "[]"; // } // return String.format(queryTemplate, (Object[])args); // } // } // // @NotNull // public static String formatNode(@NotNull final Node node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // if (node instanceof Node_Variable) { // return node.toString(); // special case for variables // } // // final Model model = ModelFactory.createDefaultModel(); // try { // final RDFNode rdfNode = model.getRDFNode(node); // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(rdfNode, new PrintWriter(writer)); // return writer.toString(); // } finally { model.close(); } // } // // @NotNull // public static String formatNode(@NotNull final RDFNode node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(node, new PrintWriter(writer)); // return writer.toString(); // } // } // // Path: src/com/dydra/jena/DydraQueryExecutionFactory.java // public class DydraQueryExecutionFactory { // protected DydraQueryExecutionFactory() {} // // /** // * @param query // * @param repository // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository) { // return new DydraQueryEngine(repository, query); // } // // /** // * @param query // * @param repository // * @param defaultGraphURI // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final String defaultGraphURI) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURI != null) { // engine.addDefaultGraph(defaultGraphURI); // } // return engine; // } // // /** // * @param query // * @param repository // * @param defaultGraphURIs // * @param namedGraphURIs // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final List<String> defaultGraphURIs, // @Nullable final List<String> namedGraphURIs) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURIs != null) { // engine.setDefaultGraphURIs(defaultGraphURIs); // } // if (namedGraphURIs != null) { // engine.setNamedGraphURIs(namedGraphURIs); // } // return engine; // } // }
import com.dydra.annotation.*; import com.dydra.jena.DydraNTripleWriter; import com.dydra.jena.DydraQueryExecutionFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Node_Variable; import com.hp.hpl.jena.graph.TripleMatch; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.update.Update; import com.hp.hpl.jena.update.UpdateExecutionFactory; import com.hp.hpl.jena.update.UpdateProcessor;
/** * Prepares to execute the given SPARQL query on this repository. * * Note: this is a Jena-specific method. * * @param queryTemplate * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" */ @NotNull public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, @Nullable final Node... nodes) { if (queryTemplate == null) throw new NullPointerException("queryTemplate cannot be null"); return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); } /** * Prepares to execute the given SPARQL query on this repository. * * Note: this is a Jena-specific method. * * @param queryString * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" */ @NotNull public QueryExecution prepareQueryExecution(@NotNull final String queryString) { if (queryString == null) throw new NullPointerException("queryString cannot be null");
// Path: src/com/dydra/jena/DydraNTripleWriter.java // public class DydraNTripleWriter extends NTripleWriter implements RDFWriter { // @NotNull // public static String formatQuery(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (nodes == null || nodes.length == 0) { // return queryTemplate; // } // else { // final String[] args = new String[nodes.length]; // for (int i = 0; i < nodes.length; i++) { // args[i] = (nodes[i] != null) ? formatNode(nodes[i]) : "[]"; // } // return String.format(queryTemplate, (Object[])args); // } // } // // @NotNull // public static String formatNode(@NotNull final Node node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // if (node instanceof Node_Variable) { // return node.toString(); // special case for variables // } // // final Model model = ModelFactory.createDefaultModel(); // try { // final RDFNode rdfNode = model.getRDFNode(node); // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(rdfNode, new PrintWriter(writer)); // return writer.toString(); // } finally { model.close(); } // } // // @NotNull // public static String formatNode(@NotNull final RDFNode node) { // if (node == null) // throw new NullPointerException("node cannot be null"); // // final StringWriter writer = new StringWriter(); // NTripleWriter.writeNode(node, new PrintWriter(writer)); // return writer.toString(); // } // } // // Path: src/com/dydra/jena/DydraQueryExecutionFactory.java // public class DydraQueryExecutionFactory { // protected DydraQueryExecutionFactory() {} // // /** // * @param query // * @param repository // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository) { // return new DydraQueryEngine(repository, query); // } // // /** // * @param query // * @param repository // * @param defaultGraphURI // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final String defaultGraphURI) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURI != null) { // engine.addDefaultGraph(defaultGraphURI); // } // return engine; // } // // /** // * @param query // * @param repository // * @param defaultGraphURIs // * @param namedGraphURIs // */ // @NotNull // public static QueryExecution prepare(@NotNull final String query, // @NotNull final Repository repository, // @Nullable final List<String> defaultGraphURIs, // @Nullable final List<String> namedGraphURIs) { // DydraQueryEngine engine = new DydraQueryEngine(repository, query); // if (defaultGraphURIs != null) { // engine.setDefaultGraphURIs(defaultGraphURIs); // } // if (namedGraphURIs != null) { // engine.setNamedGraphURIs(namedGraphURIs); // } // return engine; // } // } // Path: src/com/dydra/Repository.java import com.dydra.annotation.*; import com.dydra.jena.DydraNTripleWriter; import com.dydra.jena.DydraQueryExecutionFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Node_Variable; import com.hp.hpl.jena.graph.TripleMatch; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.update.Update; import com.hp.hpl.jena.update.UpdateExecutionFactory; import com.hp.hpl.jena.update.UpdateProcessor; /** * Prepares to execute the given SPARQL query on this repository. * * Note: this is a Jena-specific method. * * @param queryTemplate * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" */ @NotNull public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, @Nullable final Node... nodes) { if (queryTemplate == null) throw new NullPointerException("queryTemplate cannot be null"); return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); } /** * Prepares to execute the given SPARQL query on this repository. * * Note: this is a Jena-specific method. * * @param queryString * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" */ @NotNull public QueryExecution prepareQueryExecution(@NotNull final String queryString) { if (queryString == null) throw new NullPointerException("queryString cannot be null");
return DydraQueryExecutionFactory.prepare(queryString, this);
dydra/dydra.java
src/com/dydra/jena/DydraQueryExecutionFactory.java
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // }
import com.dydra.Repository; import com.dydra.annotation.*; import com.hp.hpl.jena.query.QueryExecution; import java.util.List;
/* This is free and unencumbered software released into the public domain. */ package com.dydra.jena; /** * @see http://docs.dydra.com/sdk/java/jena * @see http://openjena.org/ARQ/javadoc/com/hp/hpl/jena/query/QueryExecutionFactory.html */ public class DydraQueryExecutionFactory { protected DydraQueryExecutionFactory() {} /** * @param query * @param repository */ @NotNull public static QueryExecution prepare(@NotNull final String query,
// Path: src/com/dydra/Repository.java // public class Repository extends Resource { // /** // * The repository name. // */ // public String name; // // /** // * Constructs... // * // * @param name a valid repository name // */ // public Repository(@NotNull final String name) { // super(name); // this.name = name; // } // // /** // * Constructs... // * // * @param name a valid repository name // * @param session // */ // public Repository(@NotNull final String name, @NotNull final Session session) { // super(name, session); // this.name = name; // } // // /** // * Returns ... // * // * @return the repository owner // */ // @NotNull // public Account getAccount() { // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Returns the number of RDF statements in this repository. // * // * @return a positive integer // */ // public long getCount() { // return 0; // TODO: call the dydra.repository.count RPC method // } // // /** // * Deletes all data in this repository. // * // * @return a pending operation // */ // @NotNull // public Operation clear() { // // TODO: call the dydra.repository.clear RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Imports data from the given URL into this repository. // * // * @param url a valid URL string // * @return a pending operation // * @throws NullPointerException if <code>url</code> is null // */ // @NotNull // public Operation importFromURL(@NotNull final String url) { // if (url == null) // throw new NullPointerException("url cannot be null"); // // // TODO: call the dydra.repository.import RPC method // throw new UnsupportedOperationException("not implemented"); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s %s %s} LIMIT 10" // * @param triplePattern // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @NotNull final TripleMatch triplePattern) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // if (triplePattern == null) // throw new NullPointerException("triplePattern cannot be null"); // // final Node s = triplePattern.getMatchSubject(); // final Node p = triplePattern.getMatchPredicate(); // final Node o = triplePattern.getMatchObject(); // // final String queryString = DydraNTripleWriter.formatQuery(queryTemplate, // (s != null && s != Node.ANY) ? s : new Node_Variable("s"), // (p != null && p != Node.ANY) ? p : new Node_Variable("p"), // (o != null && o != Node.ANY) ? o : new Node_Variable("o")); // // return prepareQueryExecution(queryString); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryTemplate // * the SPARQL query template, e.g. "SELECT * WHERE {%s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryTemplate, // @Nullable final Node... nodes) { // if (queryTemplate == null) // throw new NullPointerException("queryTemplate cannot be null"); // // return prepareQueryExecution(DydraNTripleWriter.formatQuery(queryTemplate, nodes)); // } // // /** // * Prepares to execute the given SPARQL query on this repository. // * // * Note: this is a Jena-specific method. // * // * @param queryString // * the SPARQL query string, e.g. "SELECT * WHERE {?s ?p ?o} LIMIT 10" // */ // @NotNull // public QueryExecution prepareQueryExecution(@NotNull final String queryString) { // if (queryString == null) // throw new NullPointerException("queryString cannot be null"); // // return DydraQueryExecutionFactory.prepare(queryString, this); // } // // public UpdateProcessor prepareUpdate(@NotNull final Update update) { // if (update == null) // throw new NullPointerException("update cannot be null"); // // return UpdateExecutionFactory.createRemote(update, // Dydra.getAuthenticatedURL(this.getSession(), this.name + "/sparql")); // } // } // Path: src/com/dydra/jena/DydraQueryExecutionFactory.java import com.dydra.Repository; import com.dydra.annotation.*; import com.hp.hpl.jena.query.QueryExecution; import java.util.List; /* This is free and unencumbered software released into the public domain. */ package com.dydra.jena; /** * @see http://docs.dydra.com/sdk/java/jena * @see http://openjena.org/ARQ/javadoc/com/hp/hpl/jena/query/QueryExecutionFactory.html */ public class DydraQueryExecutionFactory { protected DydraQueryExecutionFactory() {} /** * @param query * @param repository */ @NotNull public static QueryExecution prepare(@NotNull final String query,
@NotNull final Repository repository) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types
registerSinkFieldLogicalConverter(new DateFieldConverter());
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types registerSinkFieldLogicalConverter(new DateFieldConverter());
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types registerSinkFieldLogicalConverter(new DateFieldConverter());
registerSinkFieldLogicalConverter(new TimeFieldConverter());
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types registerSinkFieldLogicalConverter(new DateFieldConverter()); registerSinkFieldLogicalConverter(new TimeFieldConverter());
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types registerSinkFieldLogicalConverter(new DateFieldConverter()); registerSinkFieldLogicalConverter(new TimeFieldConverter());
registerSinkFieldLogicalConverter(new TimestampFieldConverter());
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types registerSinkFieldLogicalConverter(new DateFieldConverter()); registerSinkFieldLogicalConverter(new TimeFieldConverter()); registerSinkFieldLogicalConverter(new TimestampFieldConverter());
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/AvroJsonSchemafulRecordConverter.java import org.slf4j.LoggerFactory; import java.util.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.Date; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import org.slf4j.Logger; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.converter; //looks like Avro and JSON + Schema is convertible by means of //a unified conversion approach since they are using the //same the Struct/Type information ... public class AvroJsonSchemafulRecordConverter implements RecordConverter { public static final Set<String> LOGICAL_TYPE_NAMES = new HashSet<>( Arrays.asList(Date.LOGICAL_NAME, Decimal.LOGICAL_NAME, Time.LOGICAL_NAME, Timestamp.LOGICAL_NAME) ); private final Map<Schema.Type, SinkFieldConverter> converters = new HashMap<>(); private final Map<String, SinkFieldConverter> logicalConverters = new HashMap<>(); private static Logger logger = LoggerFactory.getLogger(AvroJsonSchemafulRecordConverter.class); public AvroJsonSchemafulRecordConverter() { //standard types registerSinkFieldConverter(new BooleanFieldConverter()); registerSinkFieldConverter(new Int8FieldConverter()); registerSinkFieldConverter(new Int16FieldConverter()); registerSinkFieldConverter(new Int32FieldConverter()); registerSinkFieldConverter(new Int64FieldConverter()); registerSinkFieldConverter(new Float32FieldConverter()); registerSinkFieldConverter(new Float64FieldConverter()); registerSinkFieldConverter(new StringFieldConverter()); registerSinkFieldConverter(new BytesFieldConverter()); //logical types registerSinkFieldLogicalConverter(new DateFieldConverter()); registerSinkFieldLogicalConverter(new TimeFieldConverter()); registerSinkFieldLogicalConverter(new TimestampFieldConverter());
registerSinkFieldLogicalConverter(new DecimalFieldConverter());
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/UpdateOneTimestampsStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDateTime; import org.bson.BsonDocument; import java.time.Instant;
package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class UpdateOneTimestampsStrategy implements WriteModelStrategy { public static final String FIELDNAME_MODIFIED_TS = "_modifiedTS"; public static final String FIELDNAME_INSERTED_TS = "_insertedTS"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/UpdateOneTimestampsStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDateTime; import org.bson.BsonDocument; import java.time.Instant; package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class UpdateOneTimestampsStrategy implements WriteModelStrategy { public static final String FIELDNAME_MODIFIED_TS = "_modifiedTS"; public static final String FIELDNAME_INSERTED_TS = "_insertedTS"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> createWriteModel(SinkDocument document) {
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsUpdateTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsUpdateTest { public static final RdbmsUpdate RDBMS_UPDATE = new RdbmsUpdate(); @Test @DisplayName("when valid cdc event with single field PK then correct ReplaceOneModel") public void testValidSinkDocumentSingleFieldPK() { BsonDocument filterDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))); BsonDocument replacementDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004)); BsonDocument valueDoc = new BsonDocument("op",new BsonString("u")) .append("after",new BsonDocument("id",new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org"))); WriteModel<BsonDocument> result =
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsUpdateTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*; package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsUpdateTest { public static final RdbmsUpdate RDBMS_UPDATE = new RdbmsUpdate(); @Test @DisplayName("when valid cdc event with single field PK then correct ReplaceOneModel") public void testValidSinkDocumentSingleFieldPK() { BsonDocument filterDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))); BsonDocument replacementDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004)); BsonDocument valueDoc = new BsonDocument("op",new BsonString("u")) .append("after",new BsonDocument("id",new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org"))); WriteModel<BsonDocument> result =
RDBMS_UPDATE.perform(new SinkDocument(keyDoc,valueDoc));
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/ReplaceOneBusinessKeyStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonValue;
package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class ReplaceOneBusinessKeyStrategy implements WriteModelStrategy { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/ReplaceOneBusinessKeyStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonValue; package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class ReplaceOneBusinessKeyStrategy implements WriteModelStrategy { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> createWriteModel(SinkDocument document) {
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/WriteModelStrategyTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.*; import org.bson.conversions.Bson; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.List; import static org.junit.jupiter.api.Assertions.*;
.append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")) .append("age", new BsonInt32(23)) .append("active", new BsonBoolean(true)); public static final BsonDocument FILTER_DOC_UPDATE_TIMESTAMPS = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); public static final BsonDocument UPDATE_DOC_TIMESTAMPS = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); public static final BsonDocument MONOTONIC_WRITES_DOC_DEFAULT = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")) .append("_kafkaCoords",new BsonDocument("_topic",new BsonString("some-topic")) .append("_partition",new BsonInt32(1)) .append("_offset",new BsonInt64(111)) ); @Test @DisplayName("when key document is missing for DeleteOneDefaultStrategy then DataException") public void testDeleteOneDefaultStrategyWithMissingKeyDocument() { assertThrows(DataException.class,() -> DELETE_ONE_DEFAULT_STRATEGY.createWriteModel(
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/WriteModelStrategyTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.*; import org.bson.conversions.Bson; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.List; import static org.junit.jupiter.api.Assertions.*; .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")) .append("age", new BsonInt32(23)) .append("active", new BsonBoolean(true)); public static final BsonDocument FILTER_DOC_UPDATE_TIMESTAMPS = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); public static final BsonDocument UPDATE_DOC_TIMESTAMPS = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); public static final BsonDocument MONOTONIC_WRITES_DOC_DEFAULT = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")) .append("_kafkaCoords",new BsonDocument("_topic",new BsonString("some-topic")) .append("_partition",new BsonInt32(1)) .append("_offset",new BsonInt64(111)) ); @Test @DisplayName("when key document is missing for DeleteOneDefaultStrategy then DataException") public void testDeleteOneDefaultStrategyWithMissingKeyDocument() { assertThrows(DataException.class,() -> DELETE_ONE_DEFAULT_STRATEGY.createWriteModel(
new SinkDocument(null, new BsonDocument())
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/UuidStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonString; import org.bson.BsonValue; import java.util.UUID;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class UuidStrategy implements IdStrategy { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/UuidStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonString; import org.bson.BsonValue; import java.util.UUID; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class UuidStrategy implements IdStrategy { @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbUpdate.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbUpdate implements CdcOperation { public static final String JSON_DOC_FIELD_PATH = "patch"; public static final String INTERNAL_OPLOG_FIELD_V = "$v"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbUpdate.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbUpdate implements CdcOperation { public static final String JSON_DOC_FIELD_PATH = "patch"; public static final String INTERNAL_OPLOG_FIELD_V = "$v"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbNoOp.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.WriteModel; import org.bson.BsonDocument;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbNoOp implements CdcOperation { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbNoOp.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.WriteModel; import org.bson.BsonDocument; package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbNoOp implements CdcOperation { @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsUpdate.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsUpdate implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsUpdate.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsUpdate implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsUpdate.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsUpdate implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for update operation") ); BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for update operation") ); try {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsUpdate.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsUpdate implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for update operation") ); BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for update operation") ); try {
BsonDocument filterDoc = RdbmsHandler.generateFilterDoc(keyDoc, valueDoc, OperationType.UPDATE);
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsNoOp.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.WriteModel; import org.bson.BsonDocument;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsNoOp implements CdcOperation { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsNoOp.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.WriteModel; import org.bson.BsonDocument; package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsNoOp implements CdcOperation { @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsInsertTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsInsertTest { public static final RdbmsInsert RDBMS_INSERT = new RdbmsInsert(); @Test @DisplayName("when valid cdc event with single field PK then correct ReplaceOneModel") public void testValidSinkDocumentSingleFieldPK() { BsonDocument filterDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))); BsonDocument replacementDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004)); BsonDocument valueDoc = new BsonDocument("op",new BsonString("c")) .append("after",new BsonDocument("id",new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org"))); WriteModel<BsonDocument> result =
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsInsertTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*; package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsInsertTest { public static final RdbmsInsert RDBMS_INSERT = new RdbmsInsert(); @Test @DisplayName("when valid cdc event with single field PK then correct ReplaceOneModel") public void testValidSinkDocumentSingleFieldPK() { BsonDocument filterDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))); BsonDocument replacementDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004)); BsonDocument valueDoc = new BsonDocument("op",new BsonString("c")) .append("after",new BsonDocument("id",new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org"))); WriteModel<BsonDocument> result =
RDBMS_INSERT.perform(new SinkDocument(keyDoc,valueDoc));
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/processor/field/renaming/RenamerTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.bson.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals;
expectedKeyDocRegExpSettings.put("_F1",new BsonDocument("_F2",new BsonString("testing rocks!"))); expectedValueDocRegExpSettings = new BsonDocument("abc",new BsonString("my field value")); expectedValueDocRegExpSettings.put("f2",new BsonBoolean(false)); expectedValueDocRegExpSettings.put("subDoc",new BsonDocument("123",new BsonDouble(0.0))); expectedValueDocRegExpSettings.put("foo_foo_foo",new BsonDocument("_blah__blah_",new BsonInt32(23))); } @BeforeAll public static void setupRenamerSettings() { fieldnameMappings = new HashMap<>(); fieldnameMappings.put(Renamer.PATH_PREFIX_KEY+".fieldA","f1"); fieldnameMappings.put(Renamer.PATH_PREFIX_KEY+".f2","fieldB"); fieldnameMappings.put(Renamer.PATH_PREFIX_KEY+".subDoc.fieldX","name_x"); fieldnameMappings.put(Renamer.PATH_PREFIX_VALUE+".abc","xyz"); fieldnameMappings.put(Renamer.PATH_PREFIX_VALUE+".f2","f_two"); fieldnameMappings.put(Renamer.PATH_PREFIX_VALUE+".subDoc.123","789"); regExpSettings = new HashMap<>(); regExpSettings.put("^"+Renamer.PATH_PREFIX_KEY+"\\..*my.*$",new RenameByRegExp.PatternReplace("my","")); regExpSettings.put("^"+Renamer.PATH_PREFIX_KEY+"\\..*field.*$",new RenameByRegExp.PatternReplace("field","F")); regExpSettings.put("^"+Renamer.PATH_PREFIX_VALUE+"\\..*$",new RenameByRegExp.PatternReplace("\\.","_")); } @Test @DisplayName("simple field renamer test with custom field name mappings") public void testRenamerUsingFieldnameMapping() {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/processor/field/renaming/RenamerTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.bson.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; expectedKeyDocRegExpSettings.put("_F1",new BsonDocument("_F2",new BsonString("testing rocks!"))); expectedValueDocRegExpSettings = new BsonDocument("abc",new BsonString("my field value")); expectedValueDocRegExpSettings.put("f2",new BsonBoolean(false)); expectedValueDocRegExpSettings.put("subDoc",new BsonDocument("123",new BsonDouble(0.0))); expectedValueDocRegExpSettings.put("foo_foo_foo",new BsonDocument("_blah__blah_",new BsonInt32(23))); } @BeforeAll public static void setupRenamerSettings() { fieldnameMappings = new HashMap<>(); fieldnameMappings.put(Renamer.PATH_PREFIX_KEY+".fieldA","f1"); fieldnameMappings.put(Renamer.PATH_PREFIX_KEY+".f2","fieldB"); fieldnameMappings.put(Renamer.PATH_PREFIX_KEY+".subDoc.fieldX","name_x"); fieldnameMappings.put(Renamer.PATH_PREFIX_VALUE+".abc","xyz"); fieldnameMappings.put(Renamer.PATH_PREFIX_VALUE+".f2","f_two"); fieldnameMappings.put(Renamer.PATH_PREFIX_VALUE+".subDoc.123","789"); regExpSettings = new HashMap<>(); regExpSettings.put("^"+Renamer.PATH_PREFIX_KEY+"\\..*my.*$",new RenameByRegExp.PatternReplace("my","")); regExpSettings.put("^"+Renamer.PATH_PREFIX_KEY+"\\..*field.*$",new RenameByRegExp.PatternReplace("field","F")); regExpSettings.put("^"+Renamer.PATH_PREFIX_VALUE+"\\..*$",new RenameByRegExp.PatternReplace("\\.","_")); } @Test @DisplayName("simple field renamer test with custom field name mappings") public void testRenamerUsingFieldnameMapping() {
SinkDocument sd = new SinkDocument(keyDoc, valueDoc);
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbInsert.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbInsert implements CdcOperation { public static final String JSON_DOC_FIELD_PATH = "after"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbInsert.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbInsert implements CdcOperation { public static final String JSON_DOC_FIELD_PATH = "after"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/FullKeyStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonValue;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class FullKeyStrategy implements IdStrategy { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/FullKeyStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonValue; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class FullKeyStrategy implements IdStrategy { @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsDeleteTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonBoolean; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsDeleteTest { public static final RdbmsDelete RDBMS_DELETE = new RdbmsDelete(); @Test @DisplayName("when valid cdc event with single field PK then correct DeleteOneModel") public void testValidSinkDocumentSingleFieldPK() { BsonDocument filterDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))); BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004)); BsonDocument valueDoc = new BsonDocument("op",new BsonString("d")); WriteModel<BsonDocument> result =
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsDeleteTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonBoolean; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*; package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsDeleteTest { public static final RdbmsDelete RDBMS_DELETE = new RdbmsDelete(); @Test @DisplayName("when valid cdc event with single field PK then correct DeleteOneModel") public void testValidSinkDocumentSingleFieldPK() { BsonDocument filterDoc = new BsonDocument(DBCollection.ID_FIELD_NAME, new BsonDocument("id",new BsonInt32(1004))); BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004)); BsonDocument valueDoc = new BsonDocument("op",new BsonString("d")); WriteModel<BsonDocument> result =
RDBMS_DELETE.perform(new SinkDocument(keyDoc,valueDoc));
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsNoOpTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertNull;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsNoOpTest { @Test @DisplayName("when any cdc event then WriteModel is null resulting in Optional.empty() in the corresponding handler") public void testValidSinkDocument() { assertAll("test behaviour of MongoDbNoOp",
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsNoOpTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertNull; package at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; @RunWith(JUnitPlatform.class) public class RdbmsNoOpTest { @Test @DisplayName("when any cdc event then WriteModel is null resulting in Optional.empty() in the corresponding handler") public void testValidSinkDocument() { assertAll("test behaviour of MongoDbNoOp",
() -> assertNull(new RdbmsNoOp().perform(new SinkDocument(null,null)),"RdbmsNoOp must result in null WriteModel"),
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/MonotonicWritesDefaultStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.*; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package at.grahsl.kafka.connect.mongodb.writemodel.strategy; /** * This WriteModelStrategy implementation adds the kafka coordinates of processed * records to the actual SinkDocument as meta-data before it gets written to the * MongoDB collection. The pre-defined and currently not(!) configurable data format * for this is using a sub-document with the following structure, field names * and value &lt;PLACEHOLDERS&gt;: * * { * ..., * * "_kafkaCoords":{ * "_topic": "&lt;TOPIC_NAME&gt;", * "_partition": &lt;PARTITION_NUMBER&gt;, * "_offset": &lt;OFFSET_NUMBER&gt; * }, * * ... * } * * This "meta-data" is used to perform the actual staleness check, namely, that upsert operations * based on the corresponding document's _id field will get suppressed in case newer data has * already been written to the collection in question. Newer data means a document exhibiting * a greater than or equal offset for the same kafka topic and partition is already present in the sink. * * ! IMPORTANT NOTE ! * This WriteModelStrategy needs MongoDB version 4.2+ and Java Driver 3.11+ since * lower versions of either lack the support for leveraging update pipeline syntax. * */ public class MonotonicWritesDefaultStrategy implements WriteModelStrategy { public static final String FIELD_KAFKA_COORDS = "_kafkaCoords"; public static final String FIELD_TOPIC = "_topic"; public static final String FIELD_PARTITION = "_partition"; public static final String FIELD_OFFSET = "_offset"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/MonotonicWritesDefaultStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.*; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package at.grahsl.kafka.connect.mongodb.writemodel.strategy; /** * This WriteModelStrategy implementation adds the kafka coordinates of processed * records to the actual SinkDocument as meta-data before it gets written to the * MongoDB collection. The pre-defined and currently not(!) configurable data format * for this is using a sub-document with the following structure, field names * and value &lt;PLACEHOLDERS&gt;: * * { * ..., * * "_kafkaCoords":{ * "_topic": "&lt;TOPIC_NAME&gt;", * "_partition": &lt;PARTITION_NUMBER&gt;, * "_offset": &lt;OFFSET_NUMBER&gt; * }, * * ... * } * * This "meta-data" is used to perform the actual staleness check, namely, that upsert operations * based on the corresponding document's _id field will get suppressed in case newer data has * already been written to the collection in question. Newer data means a document exhibiting * a greater than or equal offset for the same kafka topic and partition is already present in the sink. * * ! IMPORTANT NOTE ! * This WriteModelStrategy needs MongoDB version 4.2+ and Java Driver 3.11+ since * lower versions of either lack the support for leveraging update pipeline syntax. * */ public class MonotonicWritesDefaultStrategy implements WriteModelStrategy { public static final String FIELD_KAFKA_COORDS = "_kafkaCoords"; public static final String FIELD_TOPIC = "_topic"; public static final String FIELD_PARTITION = "_partition"; public static final String FIELD_OFFSET = "_offset"; private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> createWriteModel(SinkDocument document) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/BsonOidStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonObjectId; import org.bson.BsonValue; import org.bson.types.ObjectId;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class BsonOidStrategy implements IdStrategy { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/BsonOidStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonObjectId; import org.bson.BsonValue; import org.bson.types.ObjectId; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class BsonOidStrategy implements IdStrategy { @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/DeleteOneDefaultStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/IdStrategy.java // public interface IdStrategy { // // BsonValue generateId(SinkDocument doc, SinkRecord orig); // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.id.strategy.IdStrategy; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonValue;
package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class DeleteOneDefaultStrategy implements WriteModelStrategy { private IdStrategy idStrategy; @Deprecated public DeleteOneDefaultStrategy() {} public DeleteOneDefaultStrategy(IdStrategy idStrategy) { this.idStrategy = idStrategy; } @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/IdStrategy.java // public interface IdStrategy { // // BsonValue generateId(SinkDocument doc, SinkRecord orig); // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/DeleteOneDefaultStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.id.strategy.IdStrategy; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonValue; package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class DeleteOneDefaultStrategy implements WriteModelStrategy { private IdStrategy idStrategy; @Deprecated public DeleteOneDefaultStrategy() {} public DeleteOneDefaultStrategy(IdStrategy idStrategy) { this.idStrategy = idStrategy; } @Override
public WriteModel<BsonDocument> createWriteModel(SinkDocument document) {
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/processor/DocumentIdAdderTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/IdStrategy.java // public interface IdStrategy { // // BsonValue generateId(SinkDocument doc, SinkRecord orig); // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.id.strategy.IdStrategy; import com.mongodb.DBCollection; import org.bson.BsonDocument; import org.bson.BsonValue; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor; @RunWith(JUnitPlatform.class) public class DocumentIdAdderTest { @Test @DisplayName("test _id field added by IdStrategy") public void testAddingIdFieldByStrategy() { BsonValue fakeId = mock(BsonValue.class);
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/IdStrategy.java // public interface IdStrategy { // // BsonValue generateId(SinkDocument doc, SinkRecord orig); // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/processor/DocumentIdAdderTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.id.strategy.IdStrategy; import com.mongodb.DBCollection; import org.bson.BsonDocument; import org.bson.BsonValue; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor; @RunWith(JUnitPlatform.class) public class DocumentIdAdderTest { @Test @DisplayName("test _id field added by IdStrategy") public void testAddingIdFieldByStrategy() { BsonValue fakeId = mock(BsonValue.class);
IdStrategy ids = mock(IdStrategy.class);
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/processor/DocumentIdAdderTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/IdStrategy.java // public interface IdStrategy { // // BsonValue generateId(SinkDocument doc, SinkRecord orig); // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.id.strategy.IdStrategy; import com.mongodb.DBCollection; import org.bson.BsonDocument; import org.bson.BsonValue; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor; @RunWith(JUnitPlatform.class) public class DocumentIdAdderTest { @Test @DisplayName("test _id field added by IdStrategy") public void testAddingIdFieldByStrategy() { BsonValue fakeId = mock(BsonValue.class); IdStrategy ids = mock(IdStrategy.class);
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/IdStrategy.java // public interface IdStrategy { // // BsonValue generateId(SinkDocument doc, SinkRecord orig); // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/processor/DocumentIdAdderTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.id.strategy.IdStrategy; import com.mongodb.DBCollection; import org.bson.BsonDocument; import org.bson.BsonValue; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor; @RunWith(JUnitPlatform.class) public class DocumentIdAdderTest { @Test @DisplayName("test _id field added by IdStrategy") public void testAddingIdFieldByStrategy() { BsonValue fakeId = mock(BsonValue.class); IdStrategy ids = mock(IdStrategy.class);
when(ids.generateId(any(SinkDocument.class), ArgumentMatchers.isNull()))
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbDeleteTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbDeleteTest { public static final MongoDbDelete MONGODB_DELETE = new MongoDbDelete(); public static final BsonDocument FILTER_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); @Test @DisplayName("when valid cdc event then correct DeleteOneModel") public void testValidSinkDocument() { BsonDocument keyDoc = new BsonDocument("id",new BsonString("1004")); WriteModel<BsonDocument> result =
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbDeleteTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*; package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbDeleteTest { public static final MongoDbDelete MONGODB_DELETE = new MongoDbDelete(); public static final BsonDocument FILTER_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); @Test @DisplayName("when valid cdc event then correct DeleteOneModel") public void testValidSinkDocument() { BsonDocument keyDoc = new BsonDocument("id",new BsonString("1004")); WriteModel<BsonDocument> result =
MONGODB_DELETE.perform(new SinkDocument(keyDoc,null));
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/ValidatorWithOperatorsTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/MongoDbSinkConnectorConfig.java // interface ValidatorWithOperators extends ConfigDef.Validator { // // default ValidatorWithOperators or(ConfigDef.Validator other) { // return (name, value) -> { // try { // this.ensureValid(name, value); // } catch (ConfigException e) { // other.ensureValid(name, value); // } // }; // } // // default ValidatorWithOperators and(ConfigDef.Validator other) { // return (name, value) -> { // this.ensureValid(name, value); // other.ensureValid(name, value); // }; // } // }
import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.regex.Pattern; import static at.grahsl.kafka.connect.mongodb.MongoDbSinkConnectorConfig.ValidatorWithOperators; import static org.junit.jupiter.api.Assertions.assertThrows;
package at.grahsl.kafka.connect.mongodb; @RunWith(JUnitPlatform.class) public class ValidatorWithOperatorsTest { public static final String NAME = "name"; public static final Object ANY_VALUE = null;
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/MongoDbSinkConnectorConfig.java // interface ValidatorWithOperators extends ConfigDef.Validator { // // default ValidatorWithOperators or(ConfigDef.Validator other) { // return (name, value) -> { // try { // this.ensureValid(name, value); // } catch (ConfigException e) { // other.ensureValid(name, value); // } // }; // } // // default ValidatorWithOperators and(ConfigDef.Validator other) { // return (name, value) -> { // this.ensureValid(name, value); // other.ensureValid(name, value); // }; // } // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/ValidatorWithOperatorsTest.java import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.regex.Pattern; import static at.grahsl.kafka.connect.mongodb.MongoDbSinkConnectorConfig.ValidatorWithOperators; import static org.junit.jupiter.api.Assertions.assertThrows; package at.grahsl.kafka.connect.mongodb; @RunWith(JUnitPlatform.class) public class ValidatorWithOperatorsTest { public static final String NAME = "name"; public static final Object ANY_VALUE = null;
final ValidatorWithOperators PASS = (name, value) -> {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbDelete.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbDelete implements CdcOperation { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbDelete.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; public class MongoDbDelete implements CdcOperation { @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/KafkaMetaDataStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonString; import org.bson.BsonValue;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class KafkaMetaDataStrategy implements IdStrategy { public static final String DELIMITER = "#"; @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/KafkaMetaDataStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonString; import org.bson.BsonValue; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class KafkaMetaDataStrategy implements IdStrategy { public static final String DELIMITER = "#"; @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsDelete.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsDelete implements CdcOperation { @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsDelete.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsDelete implements CdcOperation { @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsDelete.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsDelete implements CdcOperation { @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for delete operation") ); BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for delete operation") ); try {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsDelete.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsDelete implements CdcOperation { @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for delete operation") ); BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for delete operation") ); try {
BsonDocument filterDoc = RdbmsHandler.generateFilterDoc(keyDoc, valueDoc, OperationType.DELETE);
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbInsertTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbInsertTest { public static final MongoDbInsert MONGODB_INSERT = new MongoDbInsert(); public static final BsonDocument FILTER_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); public static final BsonDocument REPLACEMENT_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); @Test @DisplayName("when valid cdc event then correct ReplaceOneModel") public void testValidSinkDocument() { BsonDocument keyDoc = new BsonDocument("id",new BsonString("1004")); BsonDocument valueDoc = new BsonDocument("op",new BsonString("c")) .append("after",new BsonString(REPLACEMENT_DOC.toJson())); WriteModel<BsonDocument> result =
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbInsertTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*; package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbInsertTest { public static final MongoDbInsert MONGODB_INSERT = new MongoDbInsert(); public static final BsonDocument FILTER_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); public static final BsonDocument REPLACEMENT_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); @Test @DisplayName("when valid cdc event then correct ReplaceOneModel") public void testValidSinkDocument() { BsonDocument keyDoc = new BsonDocument("id",new BsonString("1004")); BsonDocument valueDoc = new BsonDocument("op",new BsonString("c")) .append("after",new BsonString(REPLACEMENT_DOC.toJson())); WriteModel<BsonDocument> result =
MONGODB_INSERT.perform(new SinkDocument(keyDoc,valueDoc));
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest;
+ converter.getClass().getSimpleName() + " for "+el.toString() +" -> "+Arrays.toString(el.array()), () -> assertEquals(el.array(), ((BsonBinary)converter.toBson(el)).getData()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = SchemaBuilder.bytes().optional().defaultValue(ByteBuffer.wrap(new byte[]{})); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.BYTES_SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_BYTES_SCHEMA)), () -> assertEquals(((ByteBuffer)valueOptionalDefault.defaultValue()).array(), ((BsonBinary)converter.toBson(null, valueOptionalDefault)).getData()) ); })); return tests; } @Test @DisplayName("tests for bytes field conversions with invalid type") public void testBytesFieldConverterInvalidType() { assertThrows(DataException.class, () -> new BytesFieldConverter().toBson(new Object())); } @TestFactory @DisplayName("tests for logical type date field conversions") public List<DynamicTest> testDateFieldConverter() {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest; + converter.getClass().getSimpleName() + " for "+el.toString() +" -> "+Arrays.toString(el.array()), () -> assertEquals(el.array(), ((BsonBinary)converter.toBson(el)).getData()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = SchemaBuilder.bytes().optional().defaultValue(ByteBuffer.wrap(new byte[]{})); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.BYTES_SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_BYTES_SCHEMA)), () -> assertEquals(((ByteBuffer)valueOptionalDefault.defaultValue()).array(), ((BsonBinary)converter.toBson(null, valueOptionalDefault)).getData()) ); })); return tests; } @Test @DisplayName("tests for bytes field conversions with invalid type") public void testBytesFieldConverterInvalidType() { assertThrows(DataException.class, () -> new BytesFieldConverter().toBson(new Object())); } @TestFactory @DisplayName("tests for logical type date field conversions") public List<DynamicTest> testDateFieldConverter() {
SinkFieldConverter converter = new DateFieldConverter();
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest;
java.util.Date.from(ZonedDateTime.of(LocalDate.of(1983,7,31), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()), java.util.Date.from(ZonedDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) )).forEach( el -> tests.add(dynamicTest("conversion with " + converter.getClass().getSimpleName() + " for "+el, () -> assertEquals(el.toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(el)).getValue()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = Date.builder().optional().defaultValue( java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) ); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Date.SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Date.builder().optional())), () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue()) ); })); return tests; } @TestFactory @DisplayName("tests for logical type time field conversions") public List<DynamicTest> testTimeFieldConverter() {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest; java.util.Date.from(ZonedDateTime.of(LocalDate.of(1983,7,31), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()), java.util.Date.from(ZonedDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) )).forEach( el -> tests.add(dynamicTest("conversion with " + converter.getClass().getSimpleName() + " for "+el, () -> assertEquals(el.toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(el)).getValue()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = Date.builder().optional().defaultValue( java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) ); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Date.SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Date.builder().optional())), () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue()) ); })); return tests; } @TestFactory @DisplayName("tests for logical type time field conversions") public List<DynamicTest> testTimeFieldConverter() {
SinkFieldConverter converter = new TimeFieldConverter();
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest;
java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()), java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.NOON, ZoneOffset.systemDefault()).toInstant()) )).forEach( el -> tests.add(dynamicTest("conversion with " + converter.getClass().getSimpleName() + " for "+el, () -> assertEquals(el.toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(el)).getValue()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = Time.builder().optional().defaultValue( java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) ); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Time.SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Time.builder().optional())), () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue()) ); })); return tests; } @TestFactory @DisplayName("tests for logical type timestamp field conversions") public List<DynamicTest> testTimestampFieldConverter() {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest; java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()), java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.NOON, ZoneOffset.systemDefault()).toInstant()) )).forEach( el -> tests.add(dynamicTest("conversion with " + converter.getClass().getSimpleName() + " for "+el, () -> assertEquals(el.toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(el)).getValue()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = Time.builder().optional().defaultValue( java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) ); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Time.SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Time.builder().optional())), () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue()) ); })); return tests; } @TestFactory @DisplayName("tests for logical type timestamp field conversions") public List<DynamicTest> testTimestampFieldConverter() {
SinkFieldConverter converter = new TimestampFieldConverter();
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // }
import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest;
java.util.Date.from(ZonedDateTime.of(LocalDate.of(1983,7,31), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()), java.util.Date.from(ZonedDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) )).forEach( el -> tests.add(dynamicTest("conversion with " + converter.getClass().getSimpleName() + " for "+el, () -> assertEquals(el.toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(el)).getValue()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = Timestamp.builder().optional().defaultValue( java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) ); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Timestamp.SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Timestamp.builder().optional())), () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue()) ); })); return tests; } @TestFactory @DisplayName("tests for logical type decimal field conversions (new)") public List<DynamicTest> testDecimalFieldConverterNew() {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DateFieldConverter.java // public class DateFieldConverter extends SinkFieldConverter { // // public DateFieldConverter() { // super(Date.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/DecimalFieldConverter.java // public class DecimalFieldConverter extends SinkFieldConverter { // // public enum Format { // DECIMAL128, //needs MongoDB v3.4+ // LEGACYDOUBLE //results in double approximation // } // // private Format format; // // public DecimalFieldConverter() { // super(Decimal.schema(0)); // this.format = Format.DECIMAL128; // } // // public DecimalFieldConverter(Format format) { // super(Decimal.schema(0)); // this.format = format; // } // // @Override // public BsonValue toBson(Object data) { // // if(data instanceof BigDecimal) { // if(format.equals(Format.DECIMAL128)) // return new BsonDecimal128(new Decimal128((BigDecimal)data)); // // if(format.equals(Format.LEGACYDOUBLE)) // return new BsonDouble(((BigDecimal)data).doubleValue()); // } // // throw new DataException("error: decimal conversion not possible when data is" // + " of type "+data.getClass().getName() + " and format is "+format); // // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimeFieldConverter.java // public class TimeFieldConverter extends SinkFieldConverter { // // public TimeFieldConverter() { // super(Time.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/types/sink/bson/logical/TimestampFieldConverter.java // public class TimestampFieldConverter extends SinkFieldConverter { // // public TimestampFieldConverter() { // super(Timestamp.SCHEMA); // } // // @Override // public BsonValue toBson(Object data) { // return new BsonDateTime(((java.util.Date)data).getTime()); // } // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/converter/SinkFieldConverterTest.java import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DateFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.DecimalFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimeFieldConverter; import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.logical.TimestampFieldConverter; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.errors.DataException; import org.bson.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.DynamicTest.dynamicTest; java.util.Date.from(ZonedDateTime.of(LocalDate.of(1983,7,31), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()), java.util.Date.from(ZonedDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) )).forEach( el -> tests.add(dynamicTest("conversion with " + converter.getClass().getSimpleName() + " for "+el, () -> assertEquals(el.toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(el)).getValue()) )) ); tests.add(dynamicTest("optional type conversions", () -> { Schema valueOptionalDefault = Timestamp.builder().optional().defaultValue( java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()) ); assertAll("checks", () -> assertThrows(DataException.class, () -> converter.toBson(null, Timestamp.SCHEMA)), () -> assertEquals(new BsonNull(), converter.toBson(null, Timestamp.builder().optional())), () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000, ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue()) ); })); return tests; } @TestFactory @DisplayName("tests for logical type decimal field conversions (new)") public List<DynamicTest> testDecimalFieldConverterNew() {
SinkFieldConverter converter = new DecimalFieldConverter();
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/ReplaceOneDefaultStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class ReplaceOneDefaultStrategy implements WriteModelStrategy { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/writemodel/strategy/ReplaceOneDefaultStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; package at.grahsl.kafka.connect.mongodb.writemodel.strategy; public class ReplaceOneDefaultStrategy implements WriteModelStrategy { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> createWriteModel(SinkDocument document) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsInsert.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsInsert implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsInsert.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsInsert implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsInsert.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsInsert implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for insert operation") ); BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for insert operation") ); try {
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/CdcOperation.java // public interface CdcOperation { // // WriteModel<BsonDocument> perform(SinkDocument doc); // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/OperationType.java // public enum OperationType { // // CREATE("c"), // READ("r"), // UPDATE("u"), // DELETE("d"); // // private final String text; // // OperationType(String text) { // this.text = text; // } // // String type() { // return this.text; // } // // public static OperationType fromText(String text) { // switch(text) { // case "c": return CREATE; // case "r": return READ; // case "u": return UPDATE; // case "d": return DELETE; // default: // throw new IllegalArgumentException( // "error: unknown operation type " + text // ); // } // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/rdbms/RdbmsInsert.java import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.cdc.debezium.OperationType; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.cdc.debezium.rdbms; public class RdbmsInsert implements CdcOperation { private static final UpdateOptions UPDATE_OPTIONS = new UpdateOptions().upsert(true); @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for insert operation") ); BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for insert operation") ); try {
BsonDocument filterDoc = RdbmsHandler.generateFilterDoc(keyDoc, valueDoc, OperationType.CREATE);
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbNoOpTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertNull;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbNoOpTest { @Test @DisplayName("when any cdc event then WriteModel is null resulting in Optional.empty() in the corresponding handler") public void testValidSinkDocument() { assertAll("test behaviour of MongoDbNoOp",
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbNoOpTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertNull; package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbNoOpTest { @Test @DisplayName("when any cdc event then WriteModel is null resulting in Optional.empty() in the corresponding handler") public void testValidSinkDocument() { assertAll("test behaviour of MongoDbNoOp",
() -> assertNull(new MongoDbNoOp().perform(new SinkDocument(null,null)),"MongoDbNoOp must result in null WriteModel"),
hpgrahsl/kafka-connect-mongodb
src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbUpdateTest.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*;
package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbUpdateTest { public static final MongoDbUpdate MONGODB_UPDATE = new MongoDbUpdate(); public static final BsonDocument FILTER_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); public static final BsonDocument REPLACEMENT_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); public static final BsonDocument UPDATE_DOC = new BsonDocument("$set",new BsonDocument("first_name",new BsonString("Anna")) .append("last_name",new BsonString("Kretchmer")) ); //USED to verify if oplog internals ($v field) are removed correctly public static final BsonDocument UPDATE_DOC_WITH_OPLOG_INTERNALS = UPDATE_DOC.clone().append("$v",new BsonInt32(1)); @Test @DisplayName("when valid doc replace cdc event then correct ReplaceOneModel") public void testValidSinkDocumentForReplacement() { BsonDocument keyDoc = new BsonDocument("id",new BsonString("1004")); BsonDocument valueDoc = new BsonDocument("op",new BsonString("u")) .append("patch",new BsonString(REPLACEMENT_DOC.toJson())); WriteModel<BsonDocument> result =
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/test/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbUpdateTest.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import static org.junit.jupiter.api.Assertions.*; package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; @RunWith(JUnitPlatform.class) public class MongoDbUpdateTest { public static final MongoDbUpdate MONGODB_UPDATE = new MongoDbUpdate(); public static final BsonDocument FILTER_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)); public static final BsonDocument REPLACEMENT_DOC = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004)) .append("first_name",new BsonString("Anne")) .append("last_name",new BsonString("Kretchmar")) .append("email",new BsonString("annek@noanswer.org")); public static final BsonDocument UPDATE_DOC = new BsonDocument("$set",new BsonDocument("first_name",new BsonString("Anna")) .append("last_name",new BsonString("Kretchmer")) ); //USED to verify if oplog internals ($v field) are removed correctly public static final BsonDocument UPDATE_DOC_WITH_OPLOG_INTERNALS = UPDATE_DOC.clone().append("$v",new BsonInt32(1)); @Test @DisplayName("when valid doc replace cdc event then correct ReplaceOneModel") public void testValidSinkDocumentForReplacement() { BsonDocument keyDoc = new BsonDocument("id",new BsonString("1004")); BsonDocument valueDoc = new BsonDocument("op",new BsonString("u")) .append("patch",new BsonString(REPLACEMENT_DOC.toJson())); WriteModel<BsonDocument> result =
MONGODB_UPDATE.perform(new SinkDocument(keyDoc,valueDoc));
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/PartialKeyStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/field/projection/FieldProjector.java // public abstract class FieldProjector extends PostProcessor { // // public static final String SINGLE_WILDCARD = "*"; // public static final String DOUBLE_WILDCARD = "**"; // public static final String SUB_FIELD_DOT_SEPARATOR = "."; // // protected Set<String> fields; // // public FieldProjector(MongoDbSinkConnectorConfig config,String collection) { // super(config,collection); // } // // protected abstract void doProjection(String field, BsonDocument doc); // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.field.projection.FieldProjector; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonValue;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class PartialKeyStrategy implements IdStrategy { private FieldProjector fieldProjector; public PartialKeyStrategy(FieldProjector fieldProjector) { this.fieldProjector = fieldProjector; } @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/field/projection/FieldProjector.java // public abstract class FieldProjector extends PostProcessor { // // public static final String SINGLE_WILDCARD = "*"; // public static final String DOUBLE_WILDCARD = "**"; // public static final String SUB_FIELD_DOT_SEPARATOR = "."; // // protected Set<String> fields; // // public FieldProjector(MongoDbSinkConnectorConfig config,String collection) { // super(config,collection); // } // // protected abstract void doProjection(String field, BsonDocument doc); // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/PartialKeyStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.field.projection.FieldProjector; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonValue; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class PartialKeyStrategy implements IdStrategy { private FieldProjector fieldProjector; public PartialKeyStrategy(FieldProjector fieldProjector) { this.fieldProjector = fieldProjector; } @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/ProvidedStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import java.util.Optional;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class ProvidedStrategy implements IdStrategy { protected enum ProvidedIn { KEY, VALUE } protected ProvidedIn where; public ProvidedStrategy(ProvidedIn where) { this.where = where; } @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/ProvidedStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonNull; import org.bson.BsonValue; import java.util.Optional; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class ProvidedStrategy implements IdStrategy { protected enum ProvidedIn { KEY, VALUE } protected ProvidedIn where; public ProvidedStrategy(ProvidedIn where) { this.where = where; } @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/PartialValueStrategy.java
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/field/projection/FieldProjector.java // public abstract class FieldProjector extends PostProcessor { // // public static final String SINGLE_WILDCARD = "*"; // public static final String DOUBLE_WILDCARD = "**"; // public static final String SUB_FIELD_DOT_SEPARATOR = "."; // // protected Set<String> fields; // // public FieldProjector(MongoDbSinkConnectorConfig config,String collection) { // super(config,collection); // } // // protected abstract void doProjection(String field, BsonDocument doc); // // }
import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.field.projection.FieldProjector; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonValue;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class PartialValueStrategy implements IdStrategy { private FieldProjector fieldProjector; public PartialValueStrategy(FieldProjector fieldProjector) { this.fieldProjector = fieldProjector; } @Override
// Path: src/main/java/at/grahsl/kafka/connect/mongodb/converter/SinkDocument.java // public class SinkDocument { // // private final Optional<BsonDocument> keyDoc; // private final Optional<BsonDocument> valueDoc; // // public SinkDocument(BsonDocument keyDoc, BsonDocument valueDoc) { // this.keyDoc = Optional.ofNullable(keyDoc); // this.valueDoc = Optional.ofNullable(valueDoc); // } // // public Optional<BsonDocument> getKeyDoc() { // return keyDoc; // } // // public Optional<BsonDocument> getValueDoc() { // return valueDoc; // } // // public SinkDocument clone() { // BsonDocument kd = keyDoc.isPresent() ? keyDoc.get().clone() : null; // BsonDocument vd = valueDoc.isPresent() ? valueDoc.get().clone() : null; // return new SinkDocument(kd,vd); // } // // } // // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/field/projection/FieldProjector.java // public abstract class FieldProjector extends PostProcessor { // // public static final String SINGLE_WILDCARD = "*"; // public static final String DOUBLE_WILDCARD = "**"; // public static final String SUB_FIELD_DOT_SEPARATOR = "."; // // protected Set<String> fields; // // public FieldProjector(MongoDbSinkConnectorConfig config,String collection) { // super(config,collection); // } // // protected abstract void doProjection(String field, BsonDocument doc); // // } // Path: src/main/java/at/grahsl/kafka/connect/mongodb/processor/id/strategy/PartialValueStrategy.java import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.field.projection.FieldProjector; import org.apache.kafka.connect.sink.SinkRecord; import org.bson.BsonDocument; import org.bson.BsonValue; /* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * 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 at.grahsl.kafka.connect.mongodb.processor.id.strategy; public class PartialValueStrategy implements IdStrategy { private FieldProjector fieldProjector; public PartialValueStrategy(FieldProjector fieldProjector) { this.fieldProjector = fieldProjector; } @Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
chocoteam/choco-graph
src/test/java/org/chocosolver/checked/CycleTest.java
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // }
import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test;
package org.chocosolver.checked; public class CycleTest { @Test public void test() throws ContradictionException {
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // } // Path: src/test/java/org/chocosolver/checked/CycleTest.java import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test; package org.chocosolver.checked; public class CycleTest { @Test public void test() throws ContradictionException {
GraphModel m = new GraphModel();
chocoteam/choco-graph
src/test/java/org/chocosolver/checked/CycleTest.java
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // }
import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test;
package org.chocosolver.checked; public class CycleTest { @Test public void test() throws ContradictionException { GraphModel m = new GraphModel(); int n = 4; UndirectedGraph GLB = new UndirectedGraph(m, n, SetType.BITSET, false); UndirectedGraph GUB = new UndirectedGraph(m, n, SetType.BITSET, false); for (int i = 0; i < n; i++) { GUB.addNode(i); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { GUB.addEdge(i, j); } }
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // } // Path: src/test/java/org/chocosolver/checked/CycleTest.java import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test; package org.chocosolver.checked; public class CycleTest { @Test public void test() throws ContradictionException { GraphModel m = new GraphModel(); int n = 4; UndirectedGraph GLB = new UndirectedGraph(m, n, SetType.BITSET, false); UndirectedGraph GUB = new UndirectedGraph(m, n, SetType.BITSET, false); for (int i = 0; i < n; i++) { GUB.addNode(i); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { GUB.addEdge(i, j); } }
UndirectedGraphVar g = m.graphVar("g", GLB, GUB);
chocoteam/choco-graph
src/test/java/org/chocosolver/checked/GraphTest.java
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // }
import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Model; import org.chocosolver.solver.variables.BoolVar; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.chocosolver.util.tools.ArrayUtils; import org.testng.Assert; import org.testng.annotations.Test;
package org.chocosolver.checked; /** * @author Jean-Guillaume Fages * @since 22/11/14 * Created by IntelliJ IDEA. */ public class GraphTest { @Test(groups = "1s") public void test() {
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // } // Path: src/test/java/org/chocosolver/checked/GraphTest.java import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Model; import org.chocosolver.solver.variables.BoolVar; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.chocosolver.util.tools.ArrayUtils; import org.testng.Assert; import org.testng.annotations.Test; package org.chocosolver.checked; /** * @author Jean-Guillaume Fages * @since 22/11/14 * Created by IntelliJ IDEA. */ public class GraphTest { @Test(groups = "1s") public void test() {
final GraphModel model = new GraphModel();
chocoteam/choco-graph
src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java
// Path: src/main/java/org/chocosolver/graphsolver/variables/delta/GraphDelta.java // public class GraphDelta extends TimeStampedObject implements IDelta { // // //NR NE AR AE : NodeRemoved NodeEnforced ArcRemoved ArcEnforced // public final static int NR = 0; // public final static int NE = 1; // public final static int AR_TAIL = 2; // public final static int AR_HEAD = 3; // public final static int AE_TAIL = 4; // public final static int AE_HEAD = 5; // public final static int NB = 6; // // //*********************************************************************************** // // VARIABLES // //*********************************************************************************** // // private IEnumDelta[] deltaOfType; // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // public GraphDelta(IEnvironment environment) { // super(environment); // deltaOfType = new IEnumDelta[NB]; // for (int i = 0; i < NB; i++) { // deltaOfType[i] = new EnumDelta(environment); // } // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // public int getSize(int i) { // return deltaOfType[i].size(); // } // // public void add(int element, int type, ICause cause) { // lazyClear(); // deltaOfType[type].add(element, cause); // } // // public void lazyClear() { // if (needReset()) { // for (int i = 0; i < NB; i++) { // deltaOfType[i].lazyClear(); // } // resetStamp(); // } // } // // public int get(int index, int type) { // return deltaOfType[type].get(index); // } // // public ICause getCause(int index, int type) { // return deltaOfType[type].getCause(index); // } // }
import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.ISet; import org.chocosolver.graphsolver.variables.delta.GraphDelta; import org.chocosolver.solver.ICause; import org.chocosolver.solver.Model;
/* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.variables; public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { //////////////////////////////// GRAPH PART ///////////////////////////////////////// //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** /** * Creates a graph variable * * @param name * @param solver * @param LB * @param UB */ public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { super(name, solver, LB, UB); } //*********************************************************************************** // METHODS //*********************************************************************************** @Override public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { assert cause != null; if (LB.edgeExists(x, y)) { this.contradiction(cause, "remove mandatory arc"); return false; } if (UB.removeEdge(x, y)) { if (reactOnModification) {
// Path: src/main/java/org/chocosolver/graphsolver/variables/delta/GraphDelta.java // public class GraphDelta extends TimeStampedObject implements IDelta { // // //NR NE AR AE : NodeRemoved NodeEnforced ArcRemoved ArcEnforced // public final static int NR = 0; // public final static int NE = 1; // public final static int AR_TAIL = 2; // public final static int AR_HEAD = 3; // public final static int AE_TAIL = 4; // public final static int AE_HEAD = 5; // public final static int NB = 6; // // //*********************************************************************************** // // VARIABLES // //*********************************************************************************** // // private IEnumDelta[] deltaOfType; // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // public GraphDelta(IEnvironment environment) { // super(environment); // deltaOfType = new IEnumDelta[NB]; // for (int i = 0; i < NB; i++) { // deltaOfType[i] = new EnumDelta(environment); // } // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // public int getSize(int i) { // return deltaOfType[i].size(); // } // // public void add(int element, int type, ICause cause) { // lazyClear(); // deltaOfType[type].add(element, cause); // } // // public void lazyClear() { // if (needReset()) { // for (int i = 0; i < NB; i++) { // deltaOfType[i].lazyClear(); // } // resetStamp(); // } // } // // public int get(int index, int type) { // return deltaOfType[type].get(index); // } // // public ICause getCause(int index, int type) { // return deltaOfType[type].getCause(index); // } // } // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.ISet; import org.chocosolver.graphsolver.variables.delta.GraphDelta; import org.chocosolver.solver.ICause; import org.chocosolver.solver.Model; /* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.variables; public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { //////////////////////////////// GRAPH PART ///////////////////////////////////////// //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** /** * Creates a graph variable * * @param name * @param solver * @param LB * @param UB */ public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { super(name, solver, LB, UB); } //*********************************************************************************** // METHODS //*********************************************************************************** @Override public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { assert cause != null; if (LB.edgeExists(x, y)) { this.contradiction(cause, "remove mandatory arc"); return false; } if (UB.removeEdge(x, y)) { if (reactOnModification) {
delta.add(x, GraphDelta.AR_TAIL, cause);
chocoteam/choco-graph
src/test/java/org/chocosolver/checked/NCCTest.java
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // }
import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.BoolVar; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals;
package org.chocosolver.checked; /** * Created by ezulkosk on 5/22/15. */ public class NCCTest { @Test(groups = "10s") public void testConnectedArticulationX() {
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // } // Path: src/test/java/org/chocosolver/checked/NCCTest.java import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.BoolVar; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; package org.chocosolver.checked; /** * Created by ezulkosk on 5/22/15. */ public class NCCTest { @Test(groups = "10s") public void testConnectedArticulationX() {
GraphModel m = new GraphModel();
chocoteam/choco-graph
src/test/java/org/chocosolver/checked/ConnectedTest.java
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // }
import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.BoolVar; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals;
package org.chocosolver.checked; /** * Created by ezulkosk on 5/22/15. */ public class ConnectedTest { @Test(groups = "10s") public void testConnectedArticulationX() {
// Path: src/main/java/org/chocosolver/graphsolver/GraphModel.java // public class GraphModel extends Model implements IGraphVarFactory, IGraphConstraintFactory { // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a model to handle graph variables with Choco Solver // * // * @param name label of the model // */ // public GraphModel(String name) { // super(name, new DefaultSettings() { // @Override // public AbstractStrategy makeDefaultSearch(Model model) { // return GraphSearch.defaultSearch((GraphModel)model); // } // }); // } // // /** // * Creates a model to handle graph variables with Choco Solver // */ // public GraphModel() { // this("Graph Model"); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // /** // * Iterate over the variable of <code>this</code> and build an array that contains the GraphVar only. // * // * @return array of GraphVar in <code>this</code> model // */ // public GraphVar[] retrieveGraphVars() { // ArrayList<GraphVar> gvars = new ArrayList<>(); // for (Variable v : getVars()) { // if ((v.getTypeAndKind() & Variable.KIND) == GraphVar.GRAPH) { // gvars.add((GraphVar) v); // } // } // return gvars.toArray(new GraphVar[gvars.size()]); // } // // @Override // public GraphModel _me() { // return this; // } // } // // Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // } // Path: src/test/java/org/chocosolver/checked/ConnectedTest.java import org.chocosolver.graphsolver.GraphModel; import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.Solver; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.BoolVar; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.SetType; import org.testng.Assert; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; package org.chocosolver.checked; /** * Created by ezulkosk on 5/22/15. */ public class ConnectedTest { @Test(groups = "10s") public void testConnectedArticulationX() {
GraphModel model = new GraphModel();
chocoteam/choco-graph
src/main/java/org/chocosolver/graphsolver/variables/DirectedGraphVar.java
// Path: src/main/java/org/chocosolver/graphsolver/variables/delta/GraphDelta.java // public class GraphDelta extends TimeStampedObject implements IDelta { // // //NR NE AR AE : NodeRemoved NodeEnforced ArcRemoved ArcEnforced // public final static int NR = 0; // public final static int NE = 1; // public final static int AR_TAIL = 2; // public final static int AR_HEAD = 3; // public final static int AE_TAIL = 4; // public final static int AE_HEAD = 5; // public final static int NB = 6; // // //*********************************************************************************** // // VARIABLES // //*********************************************************************************** // // private IEnumDelta[] deltaOfType; // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // public GraphDelta(IEnvironment environment) { // super(environment); // deltaOfType = new IEnumDelta[NB]; // for (int i = 0; i < NB; i++) { // deltaOfType[i] = new EnumDelta(environment); // } // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // public int getSize(int i) { // return deltaOfType[i].size(); // } // // public void add(int element, int type, ICause cause) { // lazyClear(); // deltaOfType[type].add(element, cause); // } // // public void lazyClear() { // if (needReset()) { // for (int i = 0; i < NB; i++) { // deltaOfType[i].lazyClear(); // } // resetStamp(); // } // } // // public int get(int index, int type) { // return deltaOfType[type].get(index); // } // // public ICause getCause(int index, int type) { // return deltaOfType[type].getCause(index); // } // }
import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.DirectedGraph; import org.chocosolver.util.objects.setDataStructures.ISet; import org.chocosolver.graphsolver.variables.delta.GraphDelta; import org.chocosolver.solver.ICause; import org.chocosolver.solver.Model;
/* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.variables; public class DirectedGraphVar extends GraphVar<DirectedGraph> { ////////////////////////////////// GRAPH PART /////////////////////////////////////// //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** /** * Creates a graph variable * * @param name * @param solver * @param LB * @param UB */ public DirectedGraphVar(String name, Model solver, DirectedGraph LB, DirectedGraph UB) { super(name, solver, LB, UB); } //*********************************************************************************** // METHODS //*********************************************************************************** @Override public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { assert cause != null; if (LB.arcExists(x, y)) { this.contradiction(cause, "remove mandatory arc " + x + "->" + y); return false; } if (UB.removeArc(x, y)) { if (reactOnModification) {
// Path: src/main/java/org/chocosolver/graphsolver/variables/delta/GraphDelta.java // public class GraphDelta extends TimeStampedObject implements IDelta { // // //NR NE AR AE : NodeRemoved NodeEnforced ArcRemoved ArcEnforced // public final static int NR = 0; // public final static int NE = 1; // public final static int AR_TAIL = 2; // public final static int AR_HEAD = 3; // public final static int AE_TAIL = 4; // public final static int AE_HEAD = 5; // public final static int NB = 6; // // //*********************************************************************************** // // VARIABLES // //*********************************************************************************** // // private IEnumDelta[] deltaOfType; // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // public GraphDelta(IEnvironment environment) { // super(environment); // deltaOfType = new IEnumDelta[NB]; // for (int i = 0; i < NB; i++) { // deltaOfType[i] = new EnumDelta(environment); // } // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // public int getSize(int i) { // return deltaOfType[i].size(); // } // // public void add(int element, int type, ICause cause) { // lazyClear(); // deltaOfType[type].add(element, cause); // } // // public void lazyClear() { // if (needReset()) { // for (int i = 0; i < NB; i++) { // deltaOfType[i].lazyClear(); // } // resetStamp(); // } // } // // public int get(int index, int type) { // return deltaOfType[type].get(index); // } // // public ICause getCause(int index, int type) { // return deltaOfType[type].getCause(index); // } // } // Path: src/main/java/org/chocosolver/graphsolver/variables/DirectedGraphVar.java import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.DirectedGraph; import org.chocosolver.util.objects.setDataStructures.ISet; import org.chocosolver.graphsolver.variables.delta.GraphDelta; import org.chocosolver.solver.ICause; import org.chocosolver.solver.Model; /* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.variables; public class DirectedGraphVar extends GraphVar<DirectedGraph> { ////////////////////////////////// GRAPH PART /////////////////////////////////////// //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** /** * Creates a graph variable * * @param name * @param solver * @param LB * @param UB */ public DirectedGraphVar(String name, Model solver, DirectedGraph LB, DirectedGraph UB) { super(name, solver, LB, UB); } //*********************************************************************************** // METHODS //*********************************************************************************** @Override public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { assert cause != null; if (LB.arcExists(x, y)) { this.contradiction(cause, "remove mandatory arc " + x + "->" + y); return false; } if (UB.removeArc(x, y)) { if (reactOnModification) {
delta.add(x, GraphDelta.AR_TAIL, cause);
chocoteam/choco-graph
src/main/java/org/chocosolver/graphsolver/cstrs/cost/trees/PropMaxDegVarTree.java
// Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // }
import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.IntVar;
/* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.cstrs.cost.trees; /** * Redundant filtering for a tree for which the max degree of each vertex is restricted: * if dMax(i) = dMax(j) = 1, then edge (i,j) is infeasible * if dMax(k) = 2 and (i,k) is already forced, then (k,j) is infeasible * ... * * @author Jean-Guillaume Fages */ public class PropMaxDegVarTree extends PropMaxDegTree { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected IntVar[] deg; //*********************************************************************************** // CONSTRUCTORS //***********************************************************************************
// Path: src/main/java/org/chocosolver/graphsolver/variables/UndirectedGraphVar.java // public class UndirectedGraphVar extends GraphVar<UndirectedGraph> { // // //////////////////////////////// GRAPH PART ///////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public UndirectedGraphVar(String name, Model solver, UndirectedGraph LB, UndirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.edgeExists(x, y)) { // this.contradiction(cause, "remove mandatory arc"); // return false; // } // if (UB.removeEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.edgeExists(x, y)) { // if (LB.addEdge(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of neighbors of vertex 'idx' in the lower bound graph // * (mandatory incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in LB // */ // public ISet getMandNeighOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of neighbors of vertex 'idx' in the upper bound graph // * (potential incident edges) // * // * @param idx a vertex // * @return The set of neighbors of 'idx' in UB // */ // public ISet getPotNeighOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return false; // } // } // Path: src/main/java/org/chocosolver/graphsolver/cstrs/cost/trees/PropMaxDegVarTree.java import org.chocosolver.graphsolver.variables.UndirectedGraphVar; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.IntVar; /* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.cstrs.cost.trees; /** * Redundant filtering for a tree for which the max degree of each vertex is restricted: * if dMax(i) = dMax(j) = 1, then edge (i,j) is infeasible * if dMax(k) = 2 and (i,k) is already forced, then (k,j) is infeasible * ... * * @author Jean-Guillaume Fages */ public class PropMaxDegVarTree extends PropMaxDegTree { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected IntVar[] deg; //*********************************************************************************** // CONSTRUCTORS //***********************************************************************************
public PropMaxDegVarTree(UndirectedGraphVar g, IntVar[] degrees) {
chocoteam/choco-graph
src/main/java/org/chocosolver/graphsolver/variables/delta/GraphDeltaMonitor.java
// Path: src/main/java/org/chocosolver/graphsolver/variables/GraphEventType.java // public enum GraphEventType implements IEventType { // // VOID(0), // REMOVE_NODE(1), // ADD_NODE(2), // REMOVE_ARC(4), // ADD_ARC(8); // // //*********************************************************************************** // // VARIABLES // //*********************************************************************************** // // private final int mask; // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // GraphEventType(int mask) { // this.mask = mask; // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // public int getMask() { // return mask; // } // // public int getStrengthenedMask() { // return getMask(); // } // // //****************************************************************************************************************** // //****************************************************************************************************************** // // public static boolean isAddNode(int mask) { // return (mask & ADD_NODE.mask) != 0; // } // // public static boolean isAddArc(int mask) { // return (mask & ADD_ARC.mask) != 0; // } // // public static boolean isRemNode(int mask) { // return (mask & REMOVE_NODE.mask) != 0; // } // // public static boolean isRemArc(int mask) { // return (mask & REMOVE_ARC.mask) != 0; // } // }
import org.chocosolver.solver.variables.delta.IDeltaMonitor; import org.chocosolver.util.procedure.IntProcedure; import org.chocosolver.util.procedure.PairProcedure; import org.chocosolver.graphsolver.variables.GraphEventType; import org.chocosolver.solver.ICause; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.search.loop.TimeStampedObject;
if (needReset()) { for (int i = 0; i < 4; i++) { first[i] = 0; } resetStamp(); } for (int i = 0; i < 3; i++) { frozenFirst[i] = first[i]; // freeze indices first[i] = frozenLast[i] = delta.getSize(i); } frozenFirst[3] = first[3]; // freeze indices first[3] = frozenLast[3] = delta.getSize(GraphDelta.AE_TAIL); } @Override public void unfreeze() { delta.lazyClear(); // fix 27/07/12 resetStamp(); for (int i = 0; i < 3; i++) { first[i] = delta.getSize(i); } first[3] = delta.getSize(GraphDelta.AE_TAIL); } /** * Applies proc to every vertex which has just been removed or enforced, depending on evt. * @param proc an incremental procedure over vertices * @param evt either ENFORCENODE or REMOVENODE * @throws ContradictionException if a failure occurs */
// Path: src/main/java/org/chocosolver/graphsolver/variables/GraphEventType.java // public enum GraphEventType implements IEventType { // // VOID(0), // REMOVE_NODE(1), // ADD_NODE(2), // REMOVE_ARC(4), // ADD_ARC(8); // // //*********************************************************************************** // // VARIABLES // //*********************************************************************************** // // private final int mask; // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // GraphEventType(int mask) { // this.mask = mask; // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // public int getMask() { // return mask; // } // // public int getStrengthenedMask() { // return getMask(); // } // // //****************************************************************************************************************** // //****************************************************************************************************************** // // public static boolean isAddNode(int mask) { // return (mask & ADD_NODE.mask) != 0; // } // // public static boolean isAddArc(int mask) { // return (mask & ADD_ARC.mask) != 0; // } // // public static boolean isRemNode(int mask) { // return (mask & REMOVE_NODE.mask) != 0; // } // // public static boolean isRemArc(int mask) { // return (mask & REMOVE_ARC.mask) != 0; // } // } // Path: src/main/java/org/chocosolver/graphsolver/variables/delta/GraphDeltaMonitor.java import org.chocosolver.solver.variables.delta.IDeltaMonitor; import org.chocosolver.util.procedure.IntProcedure; import org.chocosolver.util.procedure.PairProcedure; import org.chocosolver.graphsolver.variables.GraphEventType; import org.chocosolver.solver.ICause; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.search.loop.TimeStampedObject; if (needReset()) { for (int i = 0; i < 4; i++) { first[i] = 0; } resetStamp(); } for (int i = 0; i < 3; i++) { frozenFirst[i] = first[i]; // freeze indices first[i] = frozenLast[i] = delta.getSize(i); } frozenFirst[3] = first[3]; // freeze indices first[3] = frozenLast[3] = delta.getSize(GraphDelta.AE_TAIL); } @Override public void unfreeze() { delta.lazyClear(); // fix 27/07/12 resetStamp(); for (int i = 0; i < 3; i++) { first[i] = delta.getSize(i); } first[3] = delta.getSize(GraphDelta.AE_TAIL); } /** * Applies proc to every vertex which has just been removed or enforced, depending on evt. * @param proc an incremental procedure over vertices * @param evt either ENFORCENODE or REMOVENODE * @throws ContradictionException if a failure occurs */
public void forEachNode(IntProcedure proc, GraphEventType evt) throws ContradictionException {
chocoteam/choco-graph
src/main/java/org/chocosolver/graphsolver/cstrs/cost/trees/lagrangian/AbstractTreeFinder.java
// Path: src/main/java/org/chocosolver/graphsolver/cstrs/cost/GraphLagrangianRelaxation.java // public interface GraphLagrangianRelaxation extends IGraphRelaxation { // // // /** // * @param b true iff the relaxation should not be triggered before a first solution is found // */ // void waitFirstSolution(boolean b); // // // mandatory arcs // boolean isMandatory(int i, int j); // // TIntArrayList getMandatoryArcsList(); // // // get a default minimal value // double getMinArcVal(); // // // some primitives // void contradiction() throws ContradictionException; // // void remove(int i, int j) throws ContradictionException; // // void enforce(int i, int j) throws ContradictionException; // }
import org.chocosolver.util.objects.setDataStructures.SetType; import org.chocosolver.graphsolver.cstrs.cost.GraphLagrangianRelaxation; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph;
/* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.cstrs.cost.trees.lagrangian; public abstract class AbstractTreeFinder { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected final static boolean FILTER = false; // INPUT protected UndirectedGraph g; // graph protected int n; // number of nodes // OUTPUT protected UndirectedGraph Tree; protected double treeCost; // PROPAGATOR
// Path: src/main/java/org/chocosolver/graphsolver/cstrs/cost/GraphLagrangianRelaxation.java // public interface GraphLagrangianRelaxation extends IGraphRelaxation { // // // /** // * @param b true iff the relaxation should not be triggered before a first solution is found // */ // void waitFirstSolution(boolean b); // // // mandatory arcs // boolean isMandatory(int i, int j); // // TIntArrayList getMandatoryArcsList(); // // // get a default minimal value // double getMinArcVal(); // // // some primitives // void contradiction() throws ContradictionException; // // void remove(int i, int j) throws ContradictionException; // // void enforce(int i, int j) throws ContradictionException; // } // Path: src/main/java/org/chocosolver/graphsolver/cstrs/cost/trees/lagrangian/AbstractTreeFinder.java import org.chocosolver.util.objects.setDataStructures.SetType; import org.chocosolver.graphsolver.cstrs.cost.GraphLagrangianRelaxation; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.util.objects.graphs.UndirectedGraph; /* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.cstrs.cost.trees.lagrangian; public abstract class AbstractTreeFinder { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected final static boolean FILTER = false; // INPUT protected UndirectedGraph g; // graph protected int n; // number of nodes // OUTPUT protected UndirectedGraph Tree; protected double treeCost; // PROPAGATOR
protected GraphLagrangianRelaxation propHK;
chocoteam/choco-graph
src/main/java/org/chocosolver/graphsolver/cstrs/tree/PropArborescence.java
// Path: src/main/java/org/chocosolver/graphsolver/variables/DirectedGraphVar.java // public class DirectedGraphVar extends GraphVar<DirectedGraph> { // // ////////////////////////////////// GRAPH PART /////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public DirectedGraphVar(String name, Model solver, DirectedGraph LB, DirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.arcExists(x, y)) { // this.contradiction(cause, "remove mandatory arc " + x + "->" + y); // return false; // } // if (UB.removeArc(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.arcExists(x, y)) { // if (LB.addArc(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of successors of vertex 'idx' in the lower bound graph // * (mandatory outgoing arcs) // * // * @param idx a vertex // * @return The set of successors of 'idx' in LB // */ // public ISet getMandSuccOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of predecessors of vertex 'idx' in the lower bound graph // * (mandatory ingoing arcs) // * // * @param idx a vertex // * @return The set of predecessors of 'idx' in LB // */ // public ISet getMandPredOf(int idx) { // return getMandPredOrNeighOf(idx); // } // // /** // * Get the set of predecessors of vertex 'idx' // * in the upper bound graph (potential ingoing arcs) // * // * @param idx a vertex // * @return The set of predecessors of 'idx' in UB // */ // public ISet getPotPredOf(int idx) { // return getPotPredOrNeighOf(idx); // } // // /** // * Get the set of successors of vertex 'idx' // * in the upper bound graph (potential outgoing arcs) // * // * @param idx a vertex // * @return The set of successors of 'idx' in UB // */ // public ISet getPotSuccOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return true; // } // }
import java.util.BitSet; import org.chocosolver.graphsolver.variables.DirectedGraphVar; import org.chocosolver.solver.exception.ContradictionException;
/* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.cstrs.tree; /** * Arborescence constraint (simplification from tree constraint) based on dominators * * @author Jean-Guillaume Fages */ public class PropArborescence extends PropArborescences { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected final int root; protected final BitSet visited; protected final int[] fifo; //*********************************************************************************** // CONSTRUCTORS //***********************************************************************************
// Path: src/main/java/org/chocosolver/graphsolver/variables/DirectedGraphVar.java // public class DirectedGraphVar extends GraphVar<DirectedGraph> { // // ////////////////////////////////// GRAPH PART /////////////////////////////////////// // // //*********************************************************************************** // // CONSTRUCTORS // //*********************************************************************************** // // /** // * Creates a graph variable // * // * @param name // * @param solver // * @param LB // * @param UB // */ // public DirectedGraphVar(String name, Model solver, DirectedGraph LB, DirectedGraph UB) { // super(name, solver, LB, UB); // } // // //*********************************************************************************** // // METHODS // //*********************************************************************************** // // @Override // public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // if (LB.arcExists(x, y)) { // this.contradiction(cause, "remove mandatory arc " + x + "->" + y); // return false; // } // if (UB.removeArc(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AR_TAIL, cause); // delta.add(y, GraphDelta.AR_HEAD, cause); // } // GraphEventType e = GraphEventType.REMOVE_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // // @Override // public boolean enforceArc(int x, int y, ICause cause) throws ContradictionException { // assert cause != null; // enforceNode(x, cause); // enforceNode(y, cause); // if (UB.arcExists(x, y)) { // if (LB.addArc(x, y)) { // if (reactOnModification) { // delta.add(x, GraphDelta.AE_TAIL, cause); // delta.add(y, GraphDelta.AE_HEAD, cause); // } // GraphEventType e = GraphEventType.ADD_ARC; // notifyPropagators(e, cause); // return true; // } // return false; // } // this.contradiction(cause, "enforce arc which is not in the domain"); // return false; // } // // /** // * Get the set of successors of vertex 'idx' in the lower bound graph // * (mandatory outgoing arcs) // * // * @param idx a vertex // * @return The set of successors of 'idx' in LB // */ // public ISet getMandSuccOf(int idx) { // return getMandSuccOrNeighOf(idx); // } // // /** // * Get the set of predecessors of vertex 'idx' in the lower bound graph // * (mandatory ingoing arcs) // * // * @param idx a vertex // * @return The set of predecessors of 'idx' in LB // */ // public ISet getMandPredOf(int idx) { // return getMandPredOrNeighOf(idx); // } // // /** // * Get the set of predecessors of vertex 'idx' // * in the upper bound graph (potential ingoing arcs) // * // * @param idx a vertex // * @return The set of predecessors of 'idx' in UB // */ // public ISet getPotPredOf(int idx) { // return getPotPredOrNeighOf(idx); // } // // /** // * Get the set of successors of vertex 'idx' // * in the upper bound graph (potential outgoing arcs) // * // * @param idx a vertex // * @return The set of successors of 'idx' in UB // */ // public ISet getPotSuccOf(int idx) { // return getPotSuccOrNeighOf(idx); // } // // @Override // public boolean isDirected() { // return true; // } // } // Path: src/main/java/org/chocosolver/graphsolver/cstrs/tree/PropArborescence.java import java.util.BitSet; import org.chocosolver.graphsolver.variables.DirectedGraphVar; import org.chocosolver.solver.exception.ContradictionException; /* * Copyright (c) 1999-2014, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.graphsolver.cstrs.tree; /** * Arborescence constraint (simplification from tree constraint) based on dominators * * @author Jean-Guillaume Fages */ public class PropArborescence extends PropArborescences { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected final int root; protected final BitSet visited; protected final int[] fifo; //*********************************************************************************** // CONSTRUCTORS //***********************************************************************************
public PropArborescence(DirectedGraphVar graph, int root) {
laurent-clouet/sheepit-client
src/com/sheepit/client/Utils.java
// Path: src/com/sheepit/client/Error.java // public enum ServerCode { // OK(0), // UNKNOWN(999), // // CONFIGURATION_ERROR_NO_CLIENT_VERSION_GIVEN(100), // CONFIGURATION_ERROR_CLIENT_TOO_OLD(101), // CONFIGURATION_ERROR_AUTH_FAILED(102), // CONFIGURATION_ERROR_WEB_SESSION_EXPIRED(103), // CONFIGURATION_ERROR_MISSING_PARAMETER(104), // // JOB_REQUEST_NOJOB(200), // JOB_REQUEST_ERROR_NO_RENDERING_RIGHT(201), // JOB_REQUEST_ERROR_DEAD_SESSION(202), // JOB_REQUEST_ERROR_SESSION_DISABLED(203), // JOB_REQUEST_ERROR_INTERNAL_ERROR(204), // JOB_REQUEST_ERROR_RENDERER_NOT_AVAILABLE(205), // JOB_REQUEST_SERVER_IN_MAINTENANCE(206), // JOB_REQUEST_SERVER_OVERLOADED(207), // // JOB_VALIDATION_ERROR_MISSING_PARAMETER(300), // JOB_VALIDATION_ERROR_BROKEN_MACHINE(301), // in GPU the generated frame is black // JOB_VALIDATION_ERROR_FRAME_IS_NOT_IMAGE(302), // JOB_VALIDATION_ERROR_UPLOAD_FAILED(303), // JOB_VALIDATION_ERROR_SESSION_DISABLED(304), // missing heartbeat or broken machine // JOB_VALIDATION_IMAGE_TOO_LARGE(306), // JOB_VALIDATION_ERROR_IMAGE_WRONG_DIMENSION(308), // // KEEPMEALIVE_STOP_RENDERING(400), // // // internal error handling // ERROR_NO_ROOT(2), ERROR_BAD_RESPONSE(3), ERROR_REQUEST_FAILED(5); // // private final int id; // // private ServerCode(int id) { // this.id = id; // } // // public int getValue() { // return id; // } // // public static ServerCode fromInt(int val) { // ServerCode[] As = ServerCode.values(); // for (ServerCode A : As) { // if (A.getValue() == val) { // return A; // } // } // return ServerCode.UNKNOWN; // } // } // // Path: src/com/sheepit/client/exception/FermeExceptionNoSpaceLeftOnDevice.java // public class FermeExceptionNoSpaceLeftOnDevice extends FermeException { // public FermeExceptionNoSpaceLeftOnDevice() { // super(); // } // // public FermeExceptionNoSpaceLeftOnDevice(String message_) { // super(message_); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.DatatypeConverter; import net.lingala.zip4j.model.UnzipParameters; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.sheepit.client.Error.ServerCode; import com.sheepit.client.exception.FermeExceptionNoSpaceLeftOnDevice;
/* * Copyright (C) 2010-2014 Laurent CLOUET * Author Laurent CLOUET <laurent.clouet@nopnop.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.sheepit.client; public class Utils { public static int unzipFileIntoDirectory(String zipFileName_, String destinationDirectory, String password, Log log)
// Path: src/com/sheepit/client/Error.java // public enum ServerCode { // OK(0), // UNKNOWN(999), // // CONFIGURATION_ERROR_NO_CLIENT_VERSION_GIVEN(100), // CONFIGURATION_ERROR_CLIENT_TOO_OLD(101), // CONFIGURATION_ERROR_AUTH_FAILED(102), // CONFIGURATION_ERROR_WEB_SESSION_EXPIRED(103), // CONFIGURATION_ERROR_MISSING_PARAMETER(104), // // JOB_REQUEST_NOJOB(200), // JOB_REQUEST_ERROR_NO_RENDERING_RIGHT(201), // JOB_REQUEST_ERROR_DEAD_SESSION(202), // JOB_REQUEST_ERROR_SESSION_DISABLED(203), // JOB_REQUEST_ERROR_INTERNAL_ERROR(204), // JOB_REQUEST_ERROR_RENDERER_NOT_AVAILABLE(205), // JOB_REQUEST_SERVER_IN_MAINTENANCE(206), // JOB_REQUEST_SERVER_OVERLOADED(207), // // JOB_VALIDATION_ERROR_MISSING_PARAMETER(300), // JOB_VALIDATION_ERROR_BROKEN_MACHINE(301), // in GPU the generated frame is black // JOB_VALIDATION_ERROR_FRAME_IS_NOT_IMAGE(302), // JOB_VALIDATION_ERROR_UPLOAD_FAILED(303), // JOB_VALIDATION_ERROR_SESSION_DISABLED(304), // missing heartbeat or broken machine // JOB_VALIDATION_IMAGE_TOO_LARGE(306), // JOB_VALIDATION_ERROR_IMAGE_WRONG_DIMENSION(308), // // KEEPMEALIVE_STOP_RENDERING(400), // // // internal error handling // ERROR_NO_ROOT(2), ERROR_BAD_RESPONSE(3), ERROR_REQUEST_FAILED(5); // // private final int id; // // private ServerCode(int id) { // this.id = id; // } // // public int getValue() { // return id; // } // // public static ServerCode fromInt(int val) { // ServerCode[] As = ServerCode.values(); // for (ServerCode A : As) { // if (A.getValue() == val) { // return A; // } // } // return ServerCode.UNKNOWN; // } // } // // Path: src/com/sheepit/client/exception/FermeExceptionNoSpaceLeftOnDevice.java // public class FermeExceptionNoSpaceLeftOnDevice extends FermeException { // public FermeExceptionNoSpaceLeftOnDevice() { // super(); // } // // public FermeExceptionNoSpaceLeftOnDevice(String message_) { // super(message_); // } // } // Path: src/com/sheepit/client/Utils.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.DatatypeConverter; import net.lingala.zip4j.model.UnzipParameters; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.sheepit.client.Error.ServerCode; import com.sheepit.client.exception.FermeExceptionNoSpaceLeftOnDevice; /* * Copyright (C) 2010-2014 Laurent CLOUET * Author Laurent CLOUET <laurent.clouet@nopnop.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.sheepit.client; public class Utils { public static int unzipFileIntoDirectory(String zipFileName_, String destinationDirectory, String password, Log log)
throws FermeExceptionNoSpaceLeftOnDevice {
laurent-clouet/sheepit-client
src/com/sheepit/client/Utils.java
// Path: src/com/sheepit/client/Error.java // public enum ServerCode { // OK(0), // UNKNOWN(999), // // CONFIGURATION_ERROR_NO_CLIENT_VERSION_GIVEN(100), // CONFIGURATION_ERROR_CLIENT_TOO_OLD(101), // CONFIGURATION_ERROR_AUTH_FAILED(102), // CONFIGURATION_ERROR_WEB_SESSION_EXPIRED(103), // CONFIGURATION_ERROR_MISSING_PARAMETER(104), // // JOB_REQUEST_NOJOB(200), // JOB_REQUEST_ERROR_NO_RENDERING_RIGHT(201), // JOB_REQUEST_ERROR_DEAD_SESSION(202), // JOB_REQUEST_ERROR_SESSION_DISABLED(203), // JOB_REQUEST_ERROR_INTERNAL_ERROR(204), // JOB_REQUEST_ERROR_RENDERER_NOT_AVAILABLE(205), // JOB_REQUEST_SERVER_IN_MAINTENANCE(206), // JOB_REQUEST_SERVER_OVERLOADED(207), // // JOB_VALIDATION_ERROR_MISSING_PARAMETER(300), // JOB_VALIDATION_ERROR_BROKEN_MACHINE(301), // in GPU the generated frame is black // JOB_VALIDATION_ERROR_FRAME_IS_NOT_IMAGE(302), // JOB_VALIDATION_ERROR_UPLOAD_FAILED(303), // JOB_VALIDATION_ERROR_SESSION_DISABLED(304), // missing heartbeat or broken machine // JOB_VALIDATION_IMAGE_TOO_LARGE(306), // JOB_VALIDATION_ERROR_IMAGE_WRONG_DIMENSION(308), // // KEEPMEALIVE_STOP_RENDERING(400), // // // internal error handling // ERROR_NO_ROOT(2), ERROR_BAD_RESPONSE(3), ERROR_REQUEST_FAILED(5); // // private final int id; // // private ServerCode(int id) { // this.id = id; // } // // public int getValue() { // return id; // } // // public static ServerCode fromInt(int val) { // ServerCode[] As = ServerCode.values(); // for (ServerCode A : As) { // if (A.getValue() == val) { // return A; // } // } // return ServerCode.UNKNOWN; // } // } // // Path: src/com/sheepit/client/exception/FermeExceptionNoSpaceLeftOnDevice.java // public class FermeExceptionNoSpaceLeftOnDevice extends FermeException { // public FermeExceptionNoSpaceLeftOnDevice() { // super(); // } // // public FermeExceptionNoSpaceLeftOnDevice(String message_) { // super(message_); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.DatatypeConverter; import net.lingala.zip4j.model.UnzipParameters; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.sheepit.client.Error.ServerCode; import com.sheepit.client.exception.FermeExceptionNoSpaceLeftOnDevice;
String data = DatatypeConverter.printHexBinary(md.digest()).toLowerCase(); dis.close(); is.close(); return data; } catch (NoSuchAlgorithmException | IOException e) { return ""; } } public static double lastModificationTime(File directory_) { double max = 0.0; if (directory_.isDirectory()) { File[] list = directory_.listFiles(); if (list != null) { for (File aFile : list) { double max1 = lastModificationTime(aFile); if (max1 > max) { max = max1; } } } } else if (directory_.isFile()) { return directory_.lastModified(); } return max; }
// Path: src/com/sheepit/client/Error.java // public enum ServerCode { // OK(0), // UNKNOWN(999), // // CONFIGURATION_ERROR_NO_CLIENT_VERSION_GIVEN(100), // CONFIGURATION_ERROR_CLIENT_TOO_OLD(101), // CONFIGURATION_ERROR_AUTH_FAILED(102), // CONFIGURATION_ERROR_WEB_SESSION_EXPIRED(103), // CONFIGURATION_ERROR_MISSING_PARAMETER(104), // // JOB_REQUEST_NOJOB(200), // JOB_REQUEST_ERROR_NO_RENDERING_RIGHT(201), // JOB_REQUEST_ERROR_DEAD_SESSION(202), // JOB_REQUEST_ERROR_SESSION_DISABLED(203), // JOB_REQUEST_ERROR_INTERNAL_ERROR(204), // JOB_REQUEST_ERROR_RENDERER_NOT_AVAILABLE(205), // JOB_REQUEST_SERVER_IN_MAINTENANCE(206), // JOB_REQUEST_SERVER_OVERLOADED(207), // // JOB_VALIDATION_ERROR_MISSING_PARAMETER(300), // JOB_VALIDATION_ERROR_BROKEN_MACHINE(301), // in GPU the generated frame is black // JOB_VALIDATION_ERROR_FRAME_IS_NOT_IMAGE(302), // JOB_VALIDATION_ERROR_UPLOAD_FAILED(303), // JOB_VALIDATION_ERROR_SESSION_DISABLED(304), // missing heartbeat or broken machine // JOB_VALIDATION_IMAGE_TOO_LARGE(306), // JOB_VALIDATION_ERROR_IMAGE_WRONG_DIMENSION(308), // // KEEPMEALIVE_STOP_RENDERING(400), // // // internal error handling // ERROR_NO_ROOT(2), ERROR_BAD_RESPONSE(3), ERROR_REQUEST_FAILED(5); // // private final int id; // // private ServerCode(int id) { // this.id = id; // } // // public int getValue() { // return id; // } // // public static ServerCode fromInt(int val) { // ServerCode[] As = ServerCode.values(); // for (ServerCode A : As) { // if (A.getValue() == val) { // return A; // } // } // return ServerCode.UNKNOWN; // } // } // // Path: src/com/sheepit/client/exception/FermeExceptionNoSpaceLeftOnDevice.java // public class FermeExceptionNoSpaceLeftOnDevice extends FermeException { // public FermeExceptionNoSpaceLeftOnDevice() { // super(); // } // // public FermeExceptionNoSpaceLeftOnDevice(String message_) { // super(message_); // } // } // Path: src/com/sheepit/client/Utils.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Paths; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.DatatypeConverter; import net.lingala.zip4j.model.UnzipParameters; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.sheepit.client.Error.ServerCode; import com.sheepit.client.exception.FermeExceptionNoSpaceLeftOnDevice; String data = DatatypeConverter.printHexBinary(md.digest()).toLowerCase(); dis.close(); is.close(); return data; } catch (NoSuchAlgorithmException | IOException e) { return ""; } } public static double lastModificationTime(File directory_) { double max = 0.0; if (directory_.isDirectory()) { File[] list = directory_.listFiles(); if (list != null) { for (File aFile : list) { double max1 = lastModificationTime(aFile); if (max1 > max) { max = max1; } } } } else if (directory_.isFile()) { return directory_.lastModified(); } return max; }
public static ServerCode statusIsOK(Document document_, String rootname_) {
laurent-clouet/sheepit-client
src/com/sheepit/client/os/OS.java
// Path: src/com/sheepit/client/hardware/cpu/CPU.java // public class CPU { // final public static int MIN_RENDERBUCKET_SIZE = 32; // private String name; // private String model; // private String family; // private String arch; // 32 or 64 bits // // public CPU() { // this.name = null; // this.model = null; // this.family = null; // this.generateArch(); // } // // public String name() { // return this.name; // } // // public String model() { // return this.model; // } // // public String family() { // return this.family; // } // // public String arch() { // return this.arch; // } // // public int cores() { // return Runtime.getRuntime().availableProcessors(); // } // // public void setName(String name_) { // this.name = name_; // } // // public void setModel(String model_) { // this.model = model_; // } // // public void setFamily(String family_) { // this.family = family_; // } // // public void setArch(String arch_) { // this.arch = arch_; // } // // public void generateArch() { // String arch = System.getProperty("os.arch").toLowerCase(); // switch (arch) { // case "i386": // case "i686": // case "x86": // this.arch = "32bit"; // break; // case "amd64": // case "x86_64": // this.arch = "64bit"; // break; // default: // this.arch = null; // break; // } // } // // public boolean haveData() { // return this.name != null && this.model != null && this.family != null && this.arch != null; // } // // }
import com.sheepit.client.hardware.cpu.CPU; import java.io.IOException; import java.util.List; import java.util.Map;
/* * Copyright (C) 2010-2014 Laurent CLOUET * Author Laurent CLOUET <laurent.clouet@nopnop.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.sheepit.client.os; public abstract class OS { private static OS instance = null; public abstract String name();
// Path: src/com/sheepit/client/hardware/cpu/CPU.java // public class CPU { // final public static int MIN_RENDERBUCKET_SIZE = 32; // private String name; // private String model; // private String family; // private String arch; // 32 or 64 bits // // public CPU() { // this.name = null; // this.model = null; // this.family = null; // this.generateArch(); // } // // public String name() { // return this.name; // } // // public String model() { // return this.model; // } // // public String family() { // return this.family; // } // // public String arch() { // return this.arch; // } // // public int cores() { // return Runtime.getRuntime().availableProcessors(); // } // // public void setName(String name_) { // this.name = name_; // } // // public void setModel(String model_) { // this.model = model_; // } // // public void setFamily(String family_) { // this.family = family_; // } // // public void setArch(String arch_) { // this.arch = arch_; // } // // public void generateArch() { // String arch = System.getProperty("os.arch").toLowerCase(); // switch (arch) { // case "i386": // case "i686": // case "x86": // this.arch = "32bit"; // break; // case "amd64": // case "x86_64": // this.arch = "64bit"; // break; // default: // this.arch = null; // break; // } // } // // public boolean haveData() { // return this.name != null && this.model != null && this.family != null && this.arch != null; // } // // } // Path: src/com/sheepit/client/os/OS.java import com.sheepit.client.hardware.cpu.CPU; import java.io.IOException; import java.util.List; import java.util.Map; /* * Copyright (C) 2010-2014 Laurent CLOUET * Author Laurent CLOUET <laurent.clouet@nopnop.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.sheepit.client.os; public abstract class OS { private static OS instance = null; public abstract String name();
public abstract CPU getCPU();
dichengsiyu/LightMe
src/com/hellodev/lightme/util/MLisenseMangaer.java
// Path: src/com/hellodev/lightme/FlashApp.java // public class FlashApp extends Application { // private static Context mContext ; // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import java.util.Calendar; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.res.Resources; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import com.hellodev.lightme.FlashApp; import com.hellodev.lightme.R; import com.meizu.mstore.license.ILicensingService; import com.meizu.mstore.license.LicenseCheckHelper; import com.meizu.mstore.license.LicenseResult;
package com.hellodev.lightme.util; public class MLisenseMangaer { private final static String TAG = "MLisenseMangaer"; public final static int STATE_UNKNOWN = 0; public final static int STATE_PURCHASED = 1; public final static int STATE_TRYING = 2; public final static int STATE_EXPIRED = 3; public final static int EXPIRE_DAYS = 3; public final static String APK_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCB4xYVRA7w13J6dBWA+oERVDRnefb8J5N7zeD3e6JfExk76F59YRDbmDVPL+ztwwboy+R3RSQKIHM/DYymqAHnbq4m/tKXCS6BcL9MeH6Cc2xas2dNNfzOjDrb/5oqvzHI+0TPX3gU2ZML3Udsw4Q+QT+jYOgLbMYfbps3OZne5QIDAQAB/wJQnyPGfR72CNv5zR+qA4qjxSMBUSQh55awBgR4Jrwd3G+6/yH540pB/oP+GsTp0Sof/dEFaR85968aEhBGRcnpEl9OITISZRwMp654/LD6kzdsjMBjfPXiYRSLjygcbG//gOVxZbnmU2Nz5pnuFvav8wIDAQAB"; private Context mContext; // 服务的实例对象 private ILicensingService mLicensingService = null; private OnLisenseStateChangeListener mListener; public MLisenseMangaer() { // for local check this(null); } public MLisenseMangaer(OnLisenseStateChangeListener listener) { mListener = listener;
// Path: src/com/hellodev/lightme/FlashApp.java // public class FlashApp extends Application { // private static Context mContext ; // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: src/com/hellodev/lightme/util/MLisenseMangaer.java import java.util.Calendar; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.res.Resources; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import com.hellodev.lightme.FlashApp; import com.hellodev.lightme.R; import com.meizu.mstore.license.ILicensingService; import com.meizu.mstore.license.LicenseCheckHelper; import com.meizu.mstore.license.LicenseResult; package com.hellodev.lightme.util; public class MLisenseMangaer { private final static String TAG = "MLisenseMangaer"; public final static int STATE_UNKNOWN = 0; public final static int STATE_PURCHASED = 1; public final static int STATE_TRYING = 2; public final static int STATE_EXPIRED = 3; public final static int EXPIRE_DAYS = 3; public final static String APK_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCB4xYVRA7w13J6dBWA+oERVDRnefb8J5N7zeD3e6JfExk76F59YRDbmDVPL+ztwwboy+R3RSQKIHM/DYymqAHnbq4m/tKXCS6BcL9MeH6Cc2xas2dNNfzOjDrb/5oqvzHI+0TPX3gU2ZML3Udsw4Q+QT+jYOgLbMYfbps3OZne5QIDAQAB/wJQnyPGfR72CNv5zR+qA4qjxSMBUSQh55awBgR4Jrwd3G+6/yH540pB/oP+GsTp0Sof/dEFaR85968aEhBGRcnpEl9OITISZRwMp654/LD6kzdsjMBjfPXiYRSLjygcbG//gOVxZbnmU2Nz5pnuFvav8wIDAQAB"; private Context mContext; // 服务的实例对象 private ILicensingService mLicensingService = null; private OnLisenseStateChangeListener mListener; public MLisenseMangaer() { // for local check this(null); } public MLisenseMangaer(OnLisenseStateChangeListener listener) { mListener = listener;
mContext = FlashApp.getContext();
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // }
import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener;
package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator)
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener; package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator)
.setTabListener(new MyTabListener<ContactsFragment>(this, "contacts", ContactsFragment.class)));
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // }
import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener;
package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator)
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener; package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator)
.setTabListener(new MyTabListener<ContactsFragment>(this, "contacts", ContactsFragment.class)));
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // }
import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener;
package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator) .setTabListener(new MyTabListener<ContactsFragment>(this, "contacts", ContactsFragment.class))); bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_recent)
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener; package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator) .setTabListener(new MyTabListener<ContactsFragment>(this, "contacts", ContactsFragment.class))); bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_recent)
.setTabListener(new MyTabListener<RecentFragment>(this, "recent", RecentFragment.class)));
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // }
import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener;
package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator) .setTabListener(new MyTabListener<ContactsFragment>(this, "contacts", ContactsFragment.class))); bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_recent) .setTabListener(new MyTabListener<RecentFragment>(this, "recent", RecentFragment.class))); bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_dialer)
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ActionBarTab.java // public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener { // private final Activity mActivity; // private final String mTag; // private final Class<T> mClass; // private final Bundle mArgs; // private Fragment mFragment; // // public MyTabListener(Activity activity, String tag, Class<T> clz) { // this(activity, tag, clz, null); // } // // public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) { // mActivity = activity; // mTag = tag; // mClass = clz; // mArgs = args; // // // Check to see if we already have a fragment for this tab, probably // // from a previously saved state. If so, deactivate it, because our // // initial state is that a tab isn't shown. // mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); // if (mFragment != null && !mFragment.isDetached()) { // FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); // ft.detach(mFragment); // ft.commit(); // } // } // // public void onTabSelected(Tab tab, FragmentTransaction ft) { // if (mFragment == null) { // mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); // ft.add(android.R.id.content, mFragment, mTag); // } else { // ft.attach(mFragment); // } // // mActivity.getActionBar().setTitle(mTag); // } // // public void onTabUnselected(Tab tab, FragmentTransaction ft) { // if (mFragment != null) { // ft.detach(mFragment); // } // } // // public void onTabReselected(Tab tab, FragmentTransaction ft) { // Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); // } // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarStyle.java import android.R.integer; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import com.meizu.smartbar.tab.ActionBarTab.MyTabListener; package com.meizu.smartbar; public class ActionBarStyle extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); // 用户自定义的View,可以像下面这样操作 bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_indicator) .setTabListener(new MyTabListener<ContactsFragment>(this, "contacts", ContactsFragment.class))); bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_recent) .setTabListener(new MyTabListener<RecentFragment>(this, "recent", RecentFragment.class))); bar.addTab(bar.newTab().setCustomView(R.layout.tab_widget_dialer)
.setTabListener(new MyTabListener<DialerFragment>(this, "dialer", DialerFragment.class)));
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarList.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // }
import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView;
package com.meizu.smartbar; /** * ActionBar list navigation mode 以及 Action Item 普通用法的示例。 */ public class ActionBarList extends Activity implements OnNavigationListener { private final static int LIST_INDEX_RECENT = 0; private final static int LIST_INDEX_CONTACTS = 1; private final static int LIST_INDEX_DIALER = 2; private final static int LIST_INDEX_SETTINGS = 3;
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarList.java import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; package com.meizu.smartbar; /** * ActionBar list navigation mode 以及 Action Item 普通用法的示例。 */ public class ActionBarList extends Activity implements OnNavigationListener { private final static int LIST_INDEX_RECENT = 0; private final static int LIST_INDEX_CONTACTS = 1; private final static int LIST_INDEX_DIALER = 2; private final static int LIST_INDEX_SETTINGS = 3;
private final Fragment mRecentFragment = new RecentFragment();
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarList.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // }
import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView;
package com.meizu.smartbar; /** * ActionBar list navigation mode 以及 Action Item 普通用法的示例。 */ public class ActionBarList extends Activity implements OnNavigationListener { private final static int LIST_INDEX_RECENT = 0; private final static int LIST_INDEX_CONTACTS = 1; private final static int LIST_INDEX_DIALER = 2; private final static int LIST_INDEX_SETTINGS = 3; private final Fragment mRecentFragment = new RecentFragment();
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarList.java import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; package com.meizu.smartbar; /** * ActionBar list navigation mode 以及 Action Item 普通用法的示例。 */ public class ActionBarList extends Activity implements OnNavigationListener { private final static int LIST_INDEX_RECENT = 0; private final static int LIST_INDEX_CONTACTS = 1; private final static int LIST_INDEX_DIALER = 2; private final static int LIST_INDEX_SETTINGS = 3; private final Fragment mRecentFragment = new RecentFragment();
private final Fragment mContactsFragment = new ContactsFragment();
dichengsiyu/LightMe
smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarList.java
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // }
import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView;
package com.meizu.smartbar; /** * ActionBar list navigation mode 以及 Action Item 普通用法的示例。 */ public class ActionBarList extends Activity implements OnNavigationListener { private final static int LIST_INDEX_RECENT = 0; private final static int LIST_INDEX_CONTACTS = 1; private final static int LIST_INDEX_DIALER = 2; private final static int LIST_INDEX_SETTINGS = 3; private final Fragment mRecentFragment = new RecentFragment(); private final Fragment mContactsFragment = new ContactsFragment();
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsFragment.java // public class ContactsFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content_contacts, container, false); // EditText text = (EditText) fragmentView.findViewById(android.R.id.text1); // text.setText("Contacts1"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerFragment.java // public class DialerFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Dialer"); // // return fragmentView; // } // // } // // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/RecentFragment.java // public class RecentFragment extends Fragment { // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View fragmentView = inflater.inflate(R.layout.text_content, container, false); // TextView text = (TextView) fragmentView.findViewById(android.R.id.text1); // text.setText("Recent"); // // return fragmentView; // } // // } // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarList.java import com.meizu.smartbar.tab.ContactsFragment; import com.meizu.smartbar.tab.DialerFragment; import com.meizu.smartbar.tab.RecentFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; package com.meizu.smartbar; /** * ActionBar list navigation mode 以及 Action Item 普通用法的示例。 */ public class ActionBarList extends Activity implements OnNavigationListener { private final static int LIST_INDEX_RECENT = 0; private final static int LIST_INDEX_CONTACTS = 1; private final static int LIST_INDEX_DIALER = 2; private final static int LIST_INDEX_SETTINGS = 3; private final Fragment mRecentFragment = new RecentFragment(); private final Fragment mContactsFragment = new ContactsFragment();
private final Fragment mDialerFragment = new DialerFragment();
dichengsiyu/LightMe
src/com/hellodev/lightme/view/GuideViewManager.java
// Path: src/com/hellodev/lightme/FlashApp.java // public class FlashApp extends Application { // private static Context mContext ; // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.graphics.PixelFormat; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import com.hellodev.lightme.FlashApp; import com.hellodev.lightme.R;
package com.hellodev.lightme.view; public class GuideViewManager implements OnClickListener , OnTouchListener{ private WindowManager wm; private LayoutParams winParams; private Context appContext; private Timer timer = new Timer(); private TimerTask autoCloseTask; private View mGuideView; public final static int AUTO_CLOSE_NOT_NEED = 0; private final static int AUTO_CLOSE_MSG = 1; private boolean closeAble; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if( msg.what == AUTO_CLOSE_MSG) { close(); } }; }; public GuideViewManager(WindowManager wm, int windowType) {
// Path: src/com/hellodev/lightme/FlashApp.java // public class FlashApp extends Application { // private static Context mContext ; // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: src/com/hellodev/lightme/view/GuideViewManager.java import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.graphics.PixelFormat; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import com.hellodev.lightme.FlashApp; import com.hellodev.lightme.R; package com.hellodev.lightme.view; public class GuideViewManager implements OnClickListener , OnTouchListener{ private WindowManager wm; private LayoutParams winParams; private Context appContext; private Timer timer = new Timer(); private TimerTask autoCloseTask; private View mGuideView; public final static int AUTO_CLOSE_NOT_NEED = 0; private final static int AUTO_CLOSE_MSG = 1; private boolean closeAble; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if( msg.what == AUTO_CLOSE_MSG) { close(); } }; }; public GuideViewManager(WindowManager wm, int windowType) {
appContext = FlashApp.getContext();