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 |
|---|---|---|---|---|---|---|
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/NoOpCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
| import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext; | package it.nerdammer.spash.shell.command.spi;
/**
* A command that does not do anything.
*
* @author Nicola Ferraro
*/
public class NoOpCommand implements Command {
public NoOpCommand(String commandStr) {}
@Override | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/NoOpCommand.java
import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext;
package it.nerdammer.spash.shell.command.spi;
/**
* A command that does not do anything.
*
* @author Nicola Ferraro
*/
public class NoOpCommand implements Command {
public NoOpCommand(String commandStr) {}
@Override | public CommandResult execute(ExecutionContext ctx) { |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/NoOpCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
| import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext; | package it.nerdammer.spash.shell.command.spi;
/**
* A command that does not do anything.
*
* @author Nicola Ferraro
*/
public class NoOpCommand implements Command {
public NoOpCommand(String commandStr) {}
@Override | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/NoOpCommand.java
import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext;
package it.nerdammer.spash.shell.command.spi;
/**
* A command that does not do anything.
*
* @author Nicola Ferraro
*/
public class NoOpCommand implements Command {
public NoOpCommand(String commandStr) {}
@Override | public CommandResult execute(ExecutionContext ctx) { |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/Spash.java | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/api/spark/SpashSparkSubsystem.java
// public class SpashSparkSubsystem {
//
// private static final SparkFacade FACADE_INSTANCE;
//
// static {
// String master = System.getProperty("spark.master");
// if(master==null) {
// System.setProperty("spark.master", "local");
// }
//
// SparkConf conf = new SparkConf().setAppName("Spash");
// JavaSparkContext sc = new JavaSparkContext(conf);
// FACADE_INSTANCE = new SparkFacadeImpl(sc);
// }
//
// private SpashSparkSubsystem() {
// }
//
// public static SparkFacade get() {
// return FACADE_INSTANCE;
// }
// }
| import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.api.spark.SpashSparkSubsystem;
import org.apache.sshd.server.SshServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; | package it.nerdammer.spash.shell;
/**
* The main class of the application.
*
* @author Nicola Ferraro
*/
public class Spash {
public static void main(String[] args) throws Exception {
Logger logger = LoggerFactory.getLogger(Spash.class);
logger.info("Initializing the file system"); | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/api/spark/SpashSparkSubsystem.java
// public class SpashSparkSubsystem {
//
// private static final SparkFacade FACADE_INSTANCE;
//
// static {
// String master = System.getProperty("spark.master");
// if(master==null) {
// System.setProperty("spark.master", "local");
// }
//
// SparkConf conf = new SparkConf().setAppName("Spash");
// JavaSparkContext sc = new JavaSparkContext(conf);
// FACADE_INSTANCE = new SparkFacadeImpl(sc);
// }
//
// private SpashSparkSubsystem() {
// }
//
// public static SparkFacade get() {
// return FACADE_INSTANCE;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/Spash.java
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.api.spark.SpashSparkSubsystem;
import org.apache.sshd.server.SshServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
package it.nerdammer.spash.shell;
/**
* The main class of the application.
*
* @author Nicola Ferraro
*/
public class Spash {
public static void main(String[] args) throws Exception {
Logger logger = LoggerFactory.getLogger(Spash.class);
logger.info("Initializing the file system"); | SpashFileSystem.get().getFileSystem(); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/Spash.java | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/api/spark/SpashSparkSubsystem.java
// public class SpashSparkSubsystem {
//
// private static final SparkFacade FACADE_INSTANCE;
//
// static {
// String master = System.getProperty("spark.master");
// if(master==null) {
// System.setProperty("spark.master", "local");
// }
//
// SparkConf conf = new SparkConf().setAppName("Spash");
// JavaSparkContext sc = new JavaSparkContext(conf);
// FACADE_INSTANCE = new SparkFacadeImpl(sc);
// }
//
// private SpashSparkSubsystem() {
// }
//
// public static SparkFacade get() {
// return FACADE_INSTANCE;
// }
// }
| import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.api.spark.SpashSparkSubsystem;
import org.apache.sshd.server.SshServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; | package it.nerdammer.spash.shell;
/**
* The main class of the application.
*
* @author Nicola Ferraro
*/
public class Spash {
public static void main(String[] args) throws Exception {
Logger logger = LoggerFactory.getLogger(Spash.class);
logger.info("Initializing the file system");
SpashFileSystem.get().getFileSystem();
logger.info("Initializing Spark by running a simple job"); | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/api/spark/SpashSparkSubsystem.java
// public class SpashSparkSubsystem {
//
// private static final SparkFacade FACADE_INSTANCE;
//
// static {
// String master = System.getProperty("spark.master");
// if(master==null) {
// System.setProperty("spark.master", "local");
// }
//
// SparkConf conf = new SparkConf().setAppName("Spash");
// JavaSparkContext sc = new JavaSparkContext(conf);
// FACADE_INSTANCE = new SparkFacadeImpl(sc);
// }
//
// private SpashSparkSubsystem() {
// }
//
// public static SparkFacade get() {
// return FACADE_INSTANCE;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/Spash.java
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.api.spark.SpashSparkSubsystem;
import org.apache.sshd.server.SshServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
package it.nerdammer.spash.shell;
/**
* The main class of the application.
*
* @author Nicola Ferraro
*/
public class Spash {
public static void main(String[] args) throws Exception {
Logger logger = LoggerFactory.getLogger(Spash.class);
logger.info("Initializing the file system");
SpashFileSystem.get().getFileSystem();
logger.info("Initializing Spark by running a simple job"); | SpashSparkSubsystem.get().parallelize(Arrays.asList(1, 2, 3)).collect(); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/SshServerFactory.java | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
| import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.file.FileSystemFactory;
import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.UserAuth;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.auth.password.UserAuthPasswordFactory;
import org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.util.ArrayList;
import java.util.List; | package it.nerdammer.spash.shell;
/**
* Allows creating {@code SshServer} instances.
*
* @author Nicola Ferraro
*/
public class SshServerFactory {
public static SshServer create() {
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(SpashConfig.getInstance().spashListenPort());
AbstractGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(new File(SpashConfig.getInstance().spashKeyFileName()));
keyProvider.setAlgorithm(SpashConfig.getInstance().spashKeyAlgorithm());
keyProvider.setKeySize(SpashConfig.getInstance().spashKeyLength());
sshd.setKeyPairProvider(keyProvider);
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthPasswordFactory());
sshd.setUserAuthFactories(userAuthFactories);
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
@Override
public boolean authenticate(String username, String password, ServerSession serverSession) throws PasswordChangeRequiredException {
return username!=null && username.length()>0 && username.equals(password);
}
});
sshd.setShellFactory(new SpashShellFactory());
List<NamedFactory<Command>> namedFactoryList = new ArrayList<>();
namedFactoryList.add(new SftpSubsystemFactory());
sshd.setSubsystemFactories(namedFactoryList);
sshd.setCommandFactory(new ScpCommandFactory());
sshd.setFileSystemFactory(new FileSystemFactory() {
@Override
public FileSystem createFileSystem(Session session) throws IOException { | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/SshServerFactory.java
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.file.FileSystemFactory;
import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.UserAuth;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.auth.password.UserAuthPasswordFactory;
import org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.util.ArrayList;
import java.util.List;
package it.nerdammer.spash.shell;
/**
* Allows creating {@code SshServer} instances.
*
* @author Nicola Ferraro
*/
public class SshServerFactory {
public static SshServer create() {
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(SpashConfig.getInstance().spashListenPort());
AbstractGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(new File(SpashConfig.getInstance().spashKeyFileName()));
keyProvider.setAlgorithm(SpashConfig.getInstance().spashKeyAlgorithm());
keyProvider.setKeySize(SpashConfig.getInstance().spashKeyLength());
sshd.setKeyPairProvider(keyProvider);
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthPasswordFactory());
sshd.setUserAuthFactories(userAuthFactories);
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
@Override
public boolean authenticate(String username, String password, ServerSession serverSession) throws PasswordChangeRequiredException {
return username!=null && username.length()>0 && username.equals(password);
}
});
sshd.setShellFactory(new SpashShellFactory());
List<NamedFactory<Command>> namedFactoryList = new ArrayList<>();
namedFactoryList.add(new SftpSubsystemFactory());
sshd.setSubsystemFactories(namedFactoryList);
sshd.setCommandFactory(new ScpCommandFactory());
sshd.setFileSystemFactory(new FileSystemFactory() {
@Override
public FileSystem createFileSystem(Session session) throws IOException { | return SpashFileSystem.get().getFileSystem(); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/api/fs/FileSystemFacadeImpl.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionListAdapter.java
// public class SpashCollectionListAdapter<T> implements SpashCollection<T> {
//
// /**
// * The iterable object.
// */
// private List<T> target;
//
// public SpashCollectionListAdapter(List<T> target) {
// this.target = target;
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// for(T el : target) {
// writer.println(el != null ? el.toString() : "");
// }
// }
//
// @Override
// public <R> SpashCollection<R> map(final SerializableFunction<T, R> f) {
// return new SpashCollectionListAdapter<>(Lambda.convert(target, new Converter<T, R>() {
// @Override
// public R convert(T t) {
// return f.apply(t);
// }
// }));
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return new SpashCollectionUnionAdapter<>(this, coll);
// }
//
// @Override
// public SpashCollection<T> filter(final SerializableFunction<T, Boolean> condition) {
// return new SpashCollectionListAdapter<>(Lambda.filter(new BaseMatcher<T>() {
// @Override
// public boolean matches(Object o) {
// return condition.apply((T) o);
// }
// @Override
// public void describeTo(Description description) {
// }
// }, target));
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.parallelize(this.target);
// }
//
// @Override
// public List<T> collect() {
// return this.target;
// }
// }
| import com.google.common.collect.Lists;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionListAdapter;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.PosixFileAttributes;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | package it.nerdammer.spash.shell.api.fs;
/**
* A file system facade to access HDFS.
*
* @author Nicola Ferraro
*/
public class FileSystemFacadeImpl implements FileSystemFacade {
private String host;
private int port;
public FileSystemFacadeImpl(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public FileSystem getFileSystem() {
return FileSystems.getFileSystem(getURI("/"));
}
@Override | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionListAdapter.java
// public class SpashCollectionListAdapter<T> implements SpashCollection<T> {
//
// /**
// * The iterable object.
// */
// private List<T> target;
//
// public SpashCollectionListAdapter(List<T> target) {
// this.target = target;
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// for(T el : target) {
// writer.println(el != null ? el.toString() : "");
// }
// }
//
// @Override
// public <R> SpashCollection<R> map(final SerializableFunction<T, R> f) {
// return new SpashCollectionListAdapter<>(Lambda.convert(target, new Converter<T, R>() {
// @Override
// public R convert(T t) {
// return f.apply(t);
// }
// }));
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return new SpashCollectionUnionAdapter<>(this, coll);
// }
//
// @Override
// public SpashCollection<T> filter(final SerializableFunction<T, Boolean> condition) {
// return new SpashCollectionListAdapter<>(Lambda.filter(new BaseMatcher<T>() {
// @Override
// public boolean matches(Object o) {
// return condition.apply((T) o);
// }
// @Override
// public void describeTo(Description description) {
// }
// }, target));
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.parallelize(this.target);
// }
//
// @Override
// public List<T> collect() {
// return this.target;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/FileSystemFacadeImpl.java
import com.google.common.collect.Lists;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionListAdapter;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.PosixFileAttributes;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
package it.nerdammer.spash.shell.api.fs;
/**
* A file system facade to access HDFS.
*
* @author Nicola Ferraro
*/
public class FileSystemFacadeImpl implements FileSystemFacade {
private String host;
private int port;
public FileSystemFacadeImpl(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public FileSystem getFileSystem() {
return FileSystems.getFileSystem(getURI("/"));
}
@Override | public SpashCollection<Path> ls(String path) { |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/api/fs/FileSystemFacadeImpl.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionListAdapter.java
// public class SpashCollectionListAdapter<T> implements SpashCollection<T> {
//
// /**
// * The iterable object.
// */
// private List<T> target;
//
// public SpashCollectionListAdapter(List<T> target) {
// this.target = target;
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// for(T el : target) {
// writer.println(el != null ? el.toString() : "");
// }
// }
//
// @Override
// public <R> SpashCollection<R> map(final SerializableFunction<T, R> f) {
// return new SpashCollectionListAdapter<>(Lambda.convert(target, new Converter<T, R>() {
// @Override
// public R convert(T t) {
// return f.apply(t);
// }
// }));
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return new SpashCollectionUnionAdapter<>(this, coll);
// }
//
// @Override
// public SpashCollection<T> filter(final SerializableFunction<T, Boolean> condition) {
// return new SpashCollectionListAdapter<>(Lambda.filter(new BaseMatcher<T>() {
// @Override
// public boolean matches(Object o) {
// return condition.apply((T) o);
// }
// @Override
// public void describeTo(Description description) {
// }
// }, target));
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.parallelize(this.target);
// }
//
// @Override
// public List<T> collect() {
// return this.target;
// }
// }
| import com.google.common.collect.Lists;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionListAdapter;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.PosixFileAttributes;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | package it.nerdammer.spash.shell.api.fs;
/**
* A file system facade to access HDFS.
*
* @author Nicola Ferraro
*/
public class FileSystemFacadeImpl implements FileSystemFacade {
private String host;
private int port;
public FileSystemFacadeImpl(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public FileSystem getFileSystem() {
return FileSystems.getFileSystem(getURI("/"));
}
@Override
public SpashCollection<Path> ls(String path) {
if(path==null || !path.startsWith("/")) {
throw new IllegalArgumentException("Paths must be absolute. Path=" + path);
}
try {
URI uri = getURI(path);
Path dir = Paths.get(uri);
List<Path> children = Lists.newArrayList(Files.newDirectoryStream(dir, new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return true;
}
}));
| // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionListAdapter.java
// public class SpashCollectionListAdapter<T> implements SpashCollection<T> {
//
// /**
// * The iterable object.
// */
// private List<T> target;
//
// public SpashCollectionListAdapter(List<T> target) {
// this.target = target;
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// for(T el : target) {
// writer.println(el != null ? el.toString() : "");
// }
// }
//
// @Override
// public <R> SpashCollection<R> map(final SerializableFunction<T, R> f) {
// return new SpashCollectionListAdapter<>(Lambda.convert(target, new Converter<T, R>() {
// @Override
// public R convert(T t) {
// return f.apply(t);
// }
// }));
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return new SpashCollectionUnionAdapter<>(this, coll);
// }
//
// @Override
// public SpashCollection<T> filter(final SerializableFunction<T, Boolean> condition) {
// return new SpashCollectionListAdapter<>(Lambda.filter(new BaseMatcher<T>() {
// @Override
// public boolean matches(Object o) {
// return condition.apply((T) o);
// }
// @Override
// public void describeTo(Description description) {
// }
// }, target));
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.parallelize(this.target);
// }
//
// @Override
// public List<T> collect() {
// return this.target;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/FileSystemFacadeImpl.java
import com.google.common.collect.Lists;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionListAdapter;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.PosixFileAttributes;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
package it.nerdammer.spash.shell.api.fs;
/**
* A file system facade to access HDFS.
*
* @author Nicola Ferraro
*/
public class FileSystemFacadeImpl implements FileSystemFacade {
private String host;
private int port;
public FileSystemFacadeImpl(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public FileSystem getFileSystem() {
return FileSystems.getFileSystem(getURI("/"));
}
@Override
public SpashCollection<Path> ls(String path) {
if(path==null || !path.startsWith("/")) {
throw new IllegalArgumentException("Paths must be absolute. Path=" + path);
}
try {
URI uri = getURI(path);
Path dir = Paths.get(uri);
List<Path> children = Lists.newArrayList(Files.newDirectoryStream(dir, new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return true;
}
}));
| return new SpashCollectionListAdapter<>(children); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/api/fs/FileSystemFacade.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
| import it.nerdammer.spash.shell.common.SpashCollection;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributes; | package it.nerdammer.spash.shell.api.fs;
/**
* An abstraction for a file system.
*
* @author Nicola Ferraro
*/
public interface FileSystemFacade {
/**
* Returns the defaul filesystem.
*
* @return the filesystem
*/
FileSystem getFileSystem();
/**
* Returns a collection of paths contained in the given path.
*
* @param path the base path
* @return the sub paths
*/ | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/FileSystemFacade.java
import it.nerdammer.spash.shell.common.SpashCollection;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributes;
package it.nerdammer.spash.shell.api.fs;
/**
* An abstraction for a file system.
*
* @author Nicola Ferraro
*/
public interface FileSystemFacade {
/**
* Returns the defaul filesystem.
*
* @return the filesystem
*/
FileSystem getFileSystem();
/**
* Returns a collection of paths contained in the given path.
*
* @param path the base path
* @return the sub paths
*/ | SpashCollection<Path> ls(String path); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/SpashCommandCompleter.java | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandFactory.java
// public class CommandFactory {
//
// private static final CommandFactory INSTANCE = new CommandFactory();
//
// private Map<String, Class<? extends Command>> commands;
//
// private CommandFactory() {
// this.commands = new TreeMap<>();
// commands.put(">", WriteCommand.class);
// commands.put("cat", CatCommand.class);
// commands.put("cd", CdCommand.class);
// commands.put("echo", EchoCommand.class);
// commands.put("exit", ExitCommand.class);
// commands.put("grep", GrepCommand.class);
// commands.put("head", HeadCommand.class);
// commands.put("ls", LsCommand.class);
// commands.put("mkdir", MkDirCommand.class);
// commands.put("pwd", PwdCommand.class);
// commands.put("rm", RmCommand.class);
// commands.put("rmdir", RmDirCommand.class);
// commands.put("test", NoOpCommand.class);
// }
//
// public static CommandFactory getInstance() {
// return INSTANCE;
// }
//
// public Set<String> getAvailableCommands() {
// return this.commands.keySet();
// }
//
// public Command getCommand(String commandStr) {
//
// if(commandStr.trim().equals("")) {
// return new NoOpCommand(commandStr);
// } else {
// String[] args = commandStr.split(" "); // TODO parse
//
// if(commands.containsKey(args[0])) {
// try {
// Class<? extends Command> commandClass = commands.get(args[0]);
// Command c = commandClass.getConstructor(String.class).newInstance(commandStr);
// return c;
// } catch(InvocationTargetException e) {
// Throwable t = e.getCause();
// if(t instanceof RuntimeException) {
// throw (RuntimeException)t;
// } else if(t instanceof Error) {
// throw (Error)t;
// } else {
// throw new IllegalStateException(t);
// }
// } catch(RuntimeException e) {
// throw e;
// } catch(Exception e) {
// throw new IllegalStateException("Unable to create command '" + commandStr + "'", e);
// }
// }
// }
//
// return new UnknownCommand(commandStr);
// }
//
// }
| import ch.lambdaj.Lambda;
import ch.lambdaj.function.convert.DefaultStringConverter;
import ch.lambdaj.function.convert.PropertyExtractor;
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.command.CommandFactory;
import jline.console.completer.Completer;
import jline.internal.Preconditions;
import org.hamcrest.text.StringStartsWith;
import java.nio.file.Path;
import java.util.List;
import java.util.Set; | package it.nerdammer.spash.shell;
/**
* @author Nicola Ferraro
*/
public class SpashCommandCompleter implements Completer {
private Set<String> commands;
private SpashSession session;
public SpashCommandCompleter(SpashSession session) { | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandFactory.java
// public class CommandFactory {
//
// private static final CommandFactory INSTANCE = new CommandFactory();
//
// private Map<String, Class<? extends Command>> commands;
//
// private CommandFactory() {
// this.commands = new TreeMap<>();
// commands.put(">", WriteCommand.class);
// commands.put("cat", CatCommand.class);
// commands.put("cd", CdCommand.class);
// commands.put("echo", EchoCommand.class);
// commands.put("exit", ExitCommand.class);
// commands.put("grep", GrepCommand.class);
// commands.put("head", HeadCommand.class);
// commands.put("ls", LsCommand.class);
// commands.put("mkdir", MkDirCommand.class);
// commands.put("pwd", PwdCommand.class);
// commands.put("rm", RmCommand.class);
// commands.put("rmdir", RmDirCommand.class);
// commands.put("test", NoOpCommand.class);
// }
//
// public static CommandFactory getInstance() {
// return INSTANCE;
// }
//
// public Set<String> getAvailableCommands() {
// return this.commands.keySet();
// }
//
// public Command getCommand(String commandStr) {
//
// if(commandStr.trim().equals("")) {
// return new NoOpCommand(commandStr);
// } else {
// String[] args = commandStr.split(" "); // TODO parse
//
// if(commands.containsKey(args[0])) {
// try {
// Class<? extends Command> commandClass = commands.get(args[0]);
// Command c = commandClass.getConstructor(String.class).newInstance(commandStr);
// return c;
// } catch(InvocationTargetException e) {
// Throwable t = e.getCause();
// if(t instanceof RuntimeException) {
// throw (RuntimeException)t;
// } else if(t instanceof Error) {
// throw (Error)t;
// } else {
// throw new IllegalStateException(t);
// }
// } catch(RuntimeException e) {
// throw e;
// } catch(Exception e) {
// throw new IllegalStateException("Unable to create command '" + commandStr + "'", e);
// }
// }
// }
//
// return new UnknownCommand(commandStr);
// }
//
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashCommandCompleter.java
import ch.lambdaj.Lambda;
import ch.lambdaj.function.convert.DefaultStringConverter;
import ch.lambdaj.function.convert.PropertyExtractor;
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.command.CommandFactory;
import jline.console.completer.Completer;
import jline.internal.Preconditions;
import org.hamcrest.text.StringStartsWith;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
package it.nerdammer.spash.shell;
/**
* @author Nicola Ferraro
*/
public class SpashCommandCompleter implements Completer {
private Set<String> commands;
private SpashSession session;
public SpashCommandCompleter(SpashSession session) { | this.commands = CommandFactory.getInstance().getAvailableCommands(); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/SpashCommandCompleter.java | // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandFactory.java
// public class CommandFactory {
//
// private static final CommandFactory INSTANCE = new CommandFactory();
//
// private Map<String, Class<? extends Command>> commands;
//
// private CommandFactory() {
// this.commands = new TreeMap<>();
// commands.put(">", WriteCommand.class);
// commands.put("cat", CatCommand.class);
// commands.put("cd", CdCommand.class);
// commands.put("echo", EchoCommand.class);
// commands.put("exit", ExitCommand.class);
// commands.put("grep", GrepCommand.class);
// commands.put("head", HeadCommand.class);
// commands.put("ls", LsCommand.class);
// commands.put("mkdir", MkDirCommand.class);
// commands.put("pwd", PwdCommand.class);
// commands.put("rm", RmCommand.class);
// commands.put("rmdir", RmDirCommand.class);
// commands.put("test", NoOpCommand.class);
// }
//
// public static CommandFactory getInstance() {
// return INSTANCE;
// }
//
// public Set<String> getAvailableCommands() {
// return this.commands.keySet();
// }
//
// public Command getCommand(String commandStr) {
//
// if(commandStr.trim().equals("")) {
// return new NoOpCommand(commandStr);
// } else {
// String[] args = commandStr.split(" "); // TODO parse
//
// if(commands.containsKey(args[0])) {
// try {
// Class<? extends Command> commandClass = commands.get(args[0]);
// Command c = commandClass.getConstructor(String.class).newInstance(commandStr);
// return c;
// } catch(InvocationTargetException e) {
// Throwable t = e.getCause();
// if(t instanceof RuntimeException) {
// throw (RuntimeException)t;
// } else if(t instanceof Error) {
// throw (Error)t;
// } else {
// throw new IllegalStateException(t);
// }
// } catch(RuntimeException e) {
// throw e;
// } catch(Exception e) {
// throw new IllegalStateException("Unable to create command '" + commandStr + "'", e);
// }
// }
// }
//
// return new UnknownCommand(commandStr);
// }
//
// }
| import ch.lambdaj.Lambda;
import ch.lambdaj.function.convert.DefaultStringConverter;
import ch.lambdaj.function.convert.PropertyExtractor;
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.command.CommandFactory;
import jline.console.completer.Completer;
import jline.internal.Preconditions;
import org.hamcrest.text.StringStartsWith;
import java.nio.file.Path;
import java.util.List;
import java.util.Set; | package it.nerdammer.spash.shell;
/**
* @author Nicola Ferraro
*/
public class SpashCommandCompleter implements Completer {
private Set<String> commands;
private SpashSession session;
public SpashCommandCompleter(SpashSession session) {
this.commands = CommandFactory.getInstance().getAvailableCommands();
this.session = session;
}
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
Preconditions.checkNotNull(candidates);
String text = contextualBuffer(buffer, cursor);
List<String> commands = Lambda.filter(StringStartsWith.startsWith(text), this.commands);
if(commands.size()>0) {
candidates.addAll(commands);
if(candidates.size()==1) {
candidates.set(0, candidates.get(0) + " ");
}
return candidates.isEmpty() ? -1 : 0;
} else if(text.contains(" ")) {
int insertion = text.lastIndexOf(" ") + 1;
String tailBuffer = text.substring(insertion);
| // Path: core/src/main/java/it/nerdammer/spash/shell/api/fs/SpashFileSystem.java
// public final class SpashFileSystem {
//
// private static final FileSystemFacade FACADE_INSTANCE = new FileSystemFacadeImpl(SpashConfig.getInstance().hdfsHost(), SpashConfig.getInstance().hdfsPort());
//
// private SpashFileSystem() {
// }
//
// public static FileSystemFacade get() {
// return FACADE_INSTANCE;
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandFactory.java
// public class CommandFactory {
//
// private static final CommandFactory INSTANCE = new CommandFactory();
//
// private Map<String, Class<? extends Command>> commands;
//
// private CommandFactory() {
// this.commands = new TreeMap<>();
// commands.put(">", WriteCommand.class);
// commands.put("cat", CatCommand.class);
// commands.put("cd", CdCommand.class);
// commands.put("echo", EchoCommand.class);
// commands.put("exit", ExitCommand.class);
// commands.put("grep", GrepCommand.class);
// commands.put("head", HeadCommand.class);
// commands.put("ls", LsCommand.class);
// commands.put("mkdir", MkDirCommand.class);
// commands.put("pwd", PwdCommand.class);
// commands.put("rm", RmCommand.class);
// commands.put("rmdir", RmDirCommand.class);
// commands.put("test", NoOpCommand.class);
// }
//
// public static CommandFactory getInstance() {
// return INSTANCE;
// }
//
// public Set<String> getAvailableCommands() {
// return this.commands.keySet();
// }
//
// public Command getCommand(String commandStr) {
//
// if(commandStr.trim().equals("")) {
// return new NoOpCommand(commandStr);
// } else {
// String[] args = commandStr.split(" "); // TODO parse
//
// if(commands.containsKey(args[0])) {
// try {
// Class<? extends Command> commandClass = commands.get(args[0]);
// Command c = commandClass.getConstructor(String.class).newInstance(commandStr);
// return c;
// } catch(InvocationTargetException e) {
// Throwable t = e.getCause();
// if(t instanceof RuntimeException) {
// throw (RuntimeException)t;
// } else if(t instanceof Error) {
// throw (Error)t;
// } else {
// throw new IllegalStateException(t);
// }
// } catch(RuntimeException e) {
// throw e;
// } catch(Exception e) {
// throw new IllegalStateException("Unable to create command '" + commandStr + "'", e);
// }
// }
// }
//
// return new UnknownCommand(commandStr);
// }
//
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashCommandCompleter.java
import ch.lambdaj.Lambda;
import ch.lambdaj.function.convert.DefaultStringConverter;
import ch.lambdaj.function.convert.PropertyExtractor;
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.command.CommandFactory;
import jline.console.completer.Completer;
import jline.internal.Preconditions;
import org.hamcrest.text.StringStartsWith;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
package it.nerdammer.spash.shell;
/**
* @author Nicola Ferraro
*/
public class SpashCommandCompleter implements Completer {
private Set<String> commands;
private SpashSession session;
public SpashCommandCompleter(SpashSession session) {
this.commands = CommandFactory.getInstance().getAvailableCommands();
this.session = session;
}
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
Preconditions.checkNotNull(candidates);
String text = contextualBuffer(buffer, cursor);
List<String> commands = Lambda.filter(StringStartsWith.startsWith(text), this.commands);
if(commands.size()>0) {
candidates.addAll(commands);
if(candidates.size()==1) {
candidates.set(0, candidates.get(0) + " ");
}
return candidates.isEmpty() ? -1 : 0;
} else if(text.contains(" ")) {
int insertion = text.lastIndexOf(" ") + 1;
String tailBuffer = text.substring(insertion);
| List<String> files = Lambda.convert(Lambda.convert(SpashFileSystem.get().ls(this.session.getWorkingDir()).collect(), new PropertyExtractor<Object, Path>("fileName")), new DefaultStringConverter()); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/UnknownCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
| import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext; | package it.nerdammer.spash.shell.command.spi;
/**
* @author Nicola Ferraro
*/
public class UnknownCommand implements Command {
public UnknownCommand(String commandString) {
}
@Override | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/UnknownCommand.java
import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext;
package it.nerdammer.spash.shell.command.spi;
/**
* @author Nicola Ferraro
*/
public class UnknownCommand implements Command {
public UnknownCommand(String commandString) {
}
@Override | public CommandResult execute(ExecutionContext ctx) { |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/UnknownCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
| import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext; | package it.nerdammer.spash.shell.command.spi;
/**
* @author Nicola Ferraro
*/
public class UnknownCommand implements Command {
public UnknownCommand(String commandString) {
}
@Override | // Path: core/src/main/java/it/nerdammer/spash/shell/command/Command.java
// public interface Command {
//
// /**
// * Executes the command action.
// *
// * @param ctx the execution context
// * @return the associated {@code CommandResult}
// */
// CommandResult execute(ExecutionContext ctx);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
// public class CommandResult {
//
// /**
// * The executed command.
// */
// private Command command;
//
// /**
// * Indicates whether the command completed successfully.
// */
// private boolean success;
//
// /**
// * An error message explaining the problem when the command failed to execute.
// */
// private String errorMessage;
//
// /**
// * The result of the command.
// */
// private SpashCollection<String> content;
//
// private CommandResult(Command command, boolean success, String errorMessage, SpashCollection<String> content) {
// this.command = command;
// this.success = success;
// this.errorMessage = errorMessage;
// this.content = content;
// }
//
// public static CommandResult success(Command command, SpashCollection<String> content) {
// return new CommandResult(command, true, null, content);
// }
//
// public static CommandResult success(Command command) {
// return new CommandResult(command, true, null, null);
// }
//
// public static CommandResult error(Command command, String errorMessage) {
// return new CommandResult(command, false, errorMessage, null);
// }
//
// public Command getCommand() {
// return command;
// }
//
// public void setCommand(Command command) {
// this.command = command;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public SpashCollection<String> getContent() {
// return content;
// }
//
// public void setContent(SpashCollection<String> content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// return "CommandResult{" +
// "command=" + command +
// ", success=" + success +
// '}';
// }
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/SpashSession.java
// public class SpashSession {
//
// /**
// * The default working directory.
// */
// private static final String DEFAULT_WORKING_DIR = "/";
//
// /**
// * The user connected to this session.
// */
// private String user;
//
// /**
// * The current working directory.
// */
// private String workingDir = DEFAULT_WORKING_DIR;
//
// public SpashSession(String user) {
// this.user = user;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getWorkingDir() {
// return workingDir;
// }
//
// public void setWorkingDir(String workingDir) {
// this.workingDir = workingDir;
// }
//
// @Override
// public String toString() {
// return "SpashSession{" +
// "user='" + user + '\'' +
// '}';
// }
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/command/ExecutionContext.java
// public class ExecutionContext {
//
// private SpashSession session;
//
// private CommandResult previousCommandResult;
//
// public ExecutionContext() {
// }
//
// public ExecutionContext(SpashSession session, CommandResult previousCommandResult) {
// this.session = session;
// this.previousCommandResult = previousCommandResult;
// }
//
// public SpashSession getSession() {
// return session;
// }
//
// public void setSession(SpashSession session) {
// this.session = session;
// }
//
// public CommandResult getPreviousCommandResult() {
// return previousCommandResult;
// }
//
// public void setPreviousCommandResult(CommandResult previousCommandResult) {
// this.previousCommandResult = previousCommandResult;
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/UnknownCommand.java
import it.nerdammer.spash.shell.command.Command;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.SpashSession;
import it.nerdammer.spash.shell.command.ExecutionContext;
package it.nerdammer.spash.shell.command.spi;
/**
* @author Nicola Ferraro
*/
public class UnknownCommand implements Command {
public UnknownCommand(String commandString) {
}
@Override | public CommandResult execute(ExecutionContext ctx) { |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/GrepCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SerializableFunction.java
// public abstract class SerializableFunction<T, R> implements Function<T, R>, Converter<T, R>, Serializable {
//
// @Override
// public R call(T t) throws Exception {
// return apply(t);
// }
//
// @Override
// public R convert(T t) {
// return apply(t);
// }
//
// public abstract R apply(T v1);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionEmptyAdapter.java
// public class SpashCollectionEmptyAdapter<T> implements SpashCollection<T> {
//
// public SpashCollectionEmptyAdapter() {
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// }
//
// @Override
// public <R> SpashCollection<R> map(SerializableFunction<T, R> f) {
// return new SpashCollectionEmptyAdapter<>();
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return coll;
// }
//
// @Override
// public SpashCollection<T> filter(SerializableFunction<T, Boolean> condition) {
// return this;
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.emptyRDD();
// }
//
// @Override
// public List<T> collect() {
// return Collections.emptyList();
// }
// }
| import ch.lambdaj.Lambda;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.command.*;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionEmptyAdapter;
import java.util.List; | package it.nerdammer.spash.shell.command.spi;
/**
* Command to filter collections of data.
*
* @author Nicola Ferraro
*/
public class GrepCommand extends AbstractCommand {
public GrepCommand(String commandString) {
super(commandString, ImmutableMap.<String, Boolean>builder()
.put("v", false)
.put("i", false)
.build());
}
@Override
public CommandResult execute(ExecutionContext ctx) {
List<String> args = this.getArguments();
if(args.size()==0) {
return CommandResult.error(this, "Missing argument");
} else if(args.size()==1) {
// pipe mode | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SerializableFunction.java
// public abstract class SerializableFunction<T, R> implements Function<T, R>, Converter<T, R>, Serializable {
//
// @Override
// public R call(T t) throws Exception {
// return apply(t);
// }
//
// @Override
// public R convert(T t) {
// return apply(t);
// }
//
// public abstract R apply(T v1);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionEmptyAdapter.java
// public class SpashCollectionEmptyAdapter<T> implements SpashCollection<T> {
//
// public SpashCollectionEmptyAdapter() {
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// }
//
// @Override
// public <R> SpashCollection<R> map(SerializableFunction<T, R> f) {
// return new SpashCollectionEmptyAdapter<>();
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return coll;
// }
//
// @Override
// public SpashCollection<T> filter(SerializableFunction<T, Boolean> condition) {
// return this;
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.emptyRDD();
// }
//
// @Override
// public List<T> collect() {
// return Collections.emptyList();
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/GrepCommand.java
import ch.lambdaj.Lambda;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.command.*;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionEmptyAdapter;
import java.util.List;
package it.nerdammer.spash.shell.command.spi;
/**
* Command to filter collections of data.
*
* @author Nicola Ferraro
*/
public class GrepCommand extends AbstractCommand {
public GrepCommand(String commandString) {
super(commandString, ImmutableMap.<String, Boolean>builder()
.put("v", false)
.put("i", false)
.build());
}
@Override
public CommandResult execute(ExecutionContext ctx) {
List<String> args = this.getArguments();
if(args.size()==0) {
return CommandResult.error(this, "Missing argument");
} else if(args.size()==1) {
// pipe mode | SpashCollection<String> prev = ctx.getPreviousCommandResult() != null ? ctx.getPreviousCommandResult().getContent() : null; |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/GrepCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SerializableFunction.java
// public abstract class SerializableFunction<T, R> implements Function<T, R>, Converter<T, R>, Serializable {
//
// @Override
// public R call(T t) throws Exception {
// return apply(t);
// }
//
// @Override
// public R convert(T t) {
// return apply(t);
// }
//
// public abstract R apply(T v1);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionEmptyAdapter.java
// public class SpashCollectionEmptyAdapter<T> implements SpashCollection<T> {
//
// public SpashCollectionEmptyAdapter() {
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// }
//
// @Override
// public <R> SpashCollection<R> map(SerializableFunction<T, R> f) {
// return new SpashCollectionEmptyAdapter<>();
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return coll;
// }
//
// @Override
// public SpashCollection<T> filter(SerializableFunction<T, Boolean> condition) {
// return this;
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.emptyRDD();
// }
//
// @Override
// public List<T> collect() {
// return Collections.emptyList();
// }
// }
| import ch.lambdaj.Lambda;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.command.*;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionEmptyAdapter;
import java.util.List; | package it.nerdammer.spash.shell.command.spi;
/**
* Command to filter collections of data.
*
* @author Nicola Ferraro
*/
public class GrepCommand extends AbstractCommand {
public GrepCommand(String commandString) {
super(commandString, ImmutableMap.<String, Boolean>builder()
.put("v", false)
.put("i", false)
.build());
}
@Override
public CommandResult execute(ExecutionContext ctx) {
List<String> args = this.getArguments();
if(args.size()==0) {
return CommandResult.error(this, "Missing argument");
} else if(args.size()==1) {
// pipe mode
SpashCollection<String> prev = ctx.getPreviousCommandResult() != null ? ctx.getPreviousCommandResult().getContent() : null;
if(prev==null) { | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SerializableFunction.java
// public abstract class SerializableFunction<T, R> implements Function<T, R>, Converter<T, R>, Serializable {
//
// @Override
// public R call(T t) throws Exception {
// return apply(t);
// }
//
// @Override
// public R convert(T t) {
// return apply(t);
// }
//
// public abstract R apply(T v1);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionEmptyAdapter.java
// public class SpashCollectionEmptyAdapter<T> implements SpashCollection<T> {
//
// public SpashCollectionEmptyAdapter() {
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// }
//
// @Override
// public <R> SpashCollection<R> map(SerializableFunction<T, R> f) {
// return new SpashCollectionEmptyAdapter<>();
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return coll;
// }
//
// @Override
// public SpashCollection<T> filter(SerializableFunction<T, Boolean> condition) {
// return this;
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.emptyRDD();
// }
//
// @Override
// public List<T> collect() {
// return Collections.emptyList();
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/GrepCommand.java
import ch.lambdaj.Lambda;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.command.*;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionEmptyAdapter;
import java.util.List;
package it.nerdammer.spash.shell.command.spi;
/**
* Command to filter collections of data.
*
* @author Nicola Ferraro
*/
public class GrepCommand extends AbstractCommand {
public GrepCommand(String commandString) {
super(commandString, ImmutableMap.<String, Boolean>builder()
.put("v", false)
.put("i", false)
.build());
}
@Override
public CommandResult execute(ExecutionContext ctx) {
List<String> args = this.getArguments();
if(args.size()==0) {
return CommandResult.error(this, "Missing argument");
} else if(args.size()==1) {
// pipe mode
SpashCollection<String> prev = ctx.getPreviousCommandResult() != null ? ctx.getPreviousCommandResult().getContent() : null;
if(prev==null) { | prev = new SpashCollectionEmptyAdapter<>(); |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/GrepCommand.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SerializableFunction.java
// public abstract class SerializableFunction<T, R> implements Function<T, R>, Converter<T, R>, Serializable {
//
// @Override
// public R call(T t) throws Exception {
// return apply(t);
// }
//
// @Override
// public R convert(T t) {
// return apply(t);
// }
//
// public abstract R apply(T v1);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionEmptyAdapter.java
// public class SpashCollectionEmptyAdapter<T> implements SpashCollection<T> {
//
// public SpashCollectionEmptyAdapter() {
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// }
//
// @Override
// public <R> SpashCollection<R> map(SerializableFunction<T, R> f) {
// return new SpashCollectionEmptyAdapter<>();
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return coll;
// }
//
// @Override
// public SpashCollection<T> filter(SerializableFunction<T, Boolean> condition) {
// return this;
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.emptyRDD();
// }
//
// @Override
// public List<T> collect() {
// return Collections.emptyList();
// }
// }
| import ch.lambdaj.Lambda;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.command.*;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionEmptyAdapter;
import java.util.List; | if(prev==null) {
prev = new SpashCollectionEmptyAdapter<>();
}
return execute(ctx, prev);
} else {
// cat mode
String catCmdString = "cat " + Lambda.join(args.subList(1, args.size()), " ");
Command cat = CommandFactory.getInstance().getCommand(catCmdString);
CommandResult res = cat.execute(ctx);
if(!res.isSuccess()) {
return CommandResult.error(this, res.getErrorMessage());
}
return execute(ctx, res.getContent());
}
}
protected CommandResult execute(ExecutionContext ctx, SpashCollection<String> source) {
String filter = this.getArguments().get(0);
boolean reverse = this.getOptions().containsKey("v");
boolean insensitive = this.getOptions().containsKey("i");
SpashCollection<String> content = source.filter(new FilterFunction(filter, reverse, insensitive));
return CommandResult.success(this, content);
}
| // Path: core/src/main/java/it/nerdammer/spash/shell/common/SerializableFunction.java
// public abstract class SerializableFunction<T, R> implements Function<T, R>, Converter<T, R>, Serializable {
//
// @Override
// public R call(T t) throws Exception {
// return apply(t);
// }
//
// @Override
// public R convert(T t) {
// return apply(t);
// }
//
// public abstract R apply(T v1);
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
//
// Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollectionEmptyAdapter.java
// public class SpashCollectionEmptyAdapter<T> implements SpashCollection<T> {
//
// public SpashCollectionEmptyAdapter() {
// }
//
// @Override
// public void mkString(PrintWriter writer) {
// }
//
// @Override
// public <R> SpashCollection<R> map(SerializableFunction<T, R> f) {
// return new SpashCollectionEmptyAdapter<>();
// }
//
// @Override
// public SpashCollection<T> union(SpashCollection<T> coll) {
// return coll;
// }
//
// @Override
// public SpashCollection<T> filter(SerializableFunction<T, Boolean> condition) {
// return this;
// }
//
// @Override
// public JavaRDD<T> toRDD(JavaSparkContext sc) {
// return sc.emptyRDD();
// }
//
// @Override
// public List<T> collect() {
// return Collections.emptyList();
// }
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/spi/GrepCommand.java
import ch.lambdaj.Lambda;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.command.*;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionEmptyAdapter;
import java.util.List;
if(prev==null) {
prev = new SpashCollectionEmptyAdapter<>();
}
return execute(ctx, prev);
} else {
// cat mode
String catCmdString = "cat " + Lambda.join(args.subList(1, args.size()), " ");
Command cat = CommandFactory.getInstance().getCommand(catCmdString);
CommandResult res = cat.execute(ctx);
if(!res.isSuccess()) {
return CommandResult.error(this, res.getErrorMessage());
}
return execute(ctx, res.getContent());
}
}
protected CommandResult execute(ExecutionContext ctx, SpashCollection<String> source) {
String filter = this.getArguments().get(0);
boolean reverse = this.getOptions().containsKey("v");
boolean insensitive = this.getOptions().containsKey("i");
SpashCollection<String> content = source.filter(new FilterFunction(filter, reverse, insensitive));
return CommandResult.success(this, content);
}
| static class FilterFunction extends SerializableFunction<String, Boolean> { |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
| import it.nerdammer.spash.shell.common.SpashCollection; | package it.nerdammer.spash.shell.command;
/**
* Defines the result of the execution of a command.
*
* @author Nicola Ferraro
*/
public class CommandResult {
/**
* The executed command.
*/
private Command command;
/**
* Indicates whether the command completed successfully.
*/
private boolean success;
/**
* An error message explaining the problem when the command failed to execute.
*/
private String errorMessage;
/**
* The result of the command.
*/ | // Path: core/src/main/java/it/nerdammer/spash/shell/common/SpashCollection.java
// public interface SpashCollection<T> extends Serializable {
//
// /**
// * Prints the whole collection to the given writer.
// *
// * @param writer the writer on which the collection will be printed on.
// */
// void mkString(PrintWriter writer);
//
// /**
// * Tranforms every element of the collection into another element.
// *
// * @param f the transformation function
// * @param <R> the new type
// * @return the transformed collection
// */
// <R> SpashCollection<R> map(SerializableFunction<T, R> f);
//
// /**
// * Merges this collection to the one provided as input.
// *
// * @param coll the collection to merge
// * @return the union of the two collections
// */
// SpashCollection<T> union(SpashCollection<T> coll);
//
// /**
// * Filters a collection retaining only elements respecting the given condition.
// *
// * @param condition the condition that must evaluate to true for retained elements
// * @return te resulting collection
// */
// SpashCollection<T> filter(SerializableFunction<T, Boolean> condition);
//
// /**
// * Converts this collection to a Spark {@code JavaRDD}.
// *
// * @param sc the current Spark context
// * @return a RDD corresponding to this collection
// */
// JavaRDD<T> toRDD(JavaSparkContext sc);
//
// /**
// * Collects the whole collection into a {@code List}.
// *
// * @return the elements of the collection
// */
// List<T> collect();
//
// }
// Path: core/src/main/java/it/nerdammer/spash/shell/command/CommandResult.java
import it.nerdammer.spash.shell.common.SpashCollection;
package it.nerdammer.spash.shell.command;
/**
* Defines the result of the execution of a command.
*
* @author Nicola Ferraro
*/
public class CommandResult {
/**
* The executed command.
*/
private Command command;
/**
* Indicates whether the command completed successfully.
*/
private boolean success;
/**
* An error message explaining the problem when the command failed to execute.
*/
private String errorMessage;
/**
* The result of the command.
*/ | private SpashCollection<String> content; |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/reload/CachedConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload;
/**
* A {@link ConfigurationSource} that caches configuration between calls to the {@link #reload(Environment)} method.
*/
public class CachedConfigurationSource implements ConfigurationSource {
private final Map<String, Properties> cachedConfigurationPerEnvironment;
private final ConfigurationSource underlyingSource;
/**
* Create a new cached configuration source backed by {@code underlyingSource}.
*
* @param underlyingSource source used to load data into cache.
*/
public CachedConfigurationSource(ConfigurationSource underlyingSource) {
this.underlyingSource = requireNonNull(underlyingSource);
cachedConfigurationPerEnvironment = new HashMap<>();
}
/**
* Get configuration set for a given {@code environment} from the cache. For cache to be seeded
* you have to call the {@link #reload(Environment)} method before calling this method. Otherwise
* the method will throw {@link MissingEnvironmentException}.
*
* @param environment environment to use
* @return configuration set for {@code environment}
* @throws MissingEnvironmentException when there's no config for the given environment in the cache
*/
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/CachedConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload;
/**
* A {@link ConfigurationSource} that caches configuration between calls to the {@link #reload(Environment)} method.
*/
public class CachedConfigurationSource implements ConfigurationSource {
private final Map<String, Properties> cachedConfigurationPerEnvironment;
private final ConfigurationSource underlyingSource;
/**
* Create a new cached configuration source backed by {@code underlyingSource}.
*
* @param underlyingSource source used to load data into cache.
*/
public CachedConfigurationSource(ConfigurationSource underlyingSource) {
this.underlyingSource = requireNonNull(underlyingSource);
cachedConfigurationPerEnvironment = new HashMap<>();
}
/**
* Get configuration set for a given {@code environment} from the cache. For cache to be seeded
* you have to call the {@link #reload(Environment)} method before calling this method. Otherwise
* the method will throw {@link MissingEnvironmentException}.
*
* @param environment environment to use
* @return configuration set for {@code environment}
* @throws MissingEnvironmentException when there's no config for the given environment in the cache
*/
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/reload/CachedConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload;
/**
* A {@link ConfigurationSource} that caches configuration between calls to the {@link #reload(Environment)} method.
*/
public class CachedConfigurationSource implements ConfigurationSource {
private final Map<String, Properties> cachedConfigurationPerEnvironment;
private final ConfigurationSource underlyingSource;
/**
* Create a new cached configuration source backed by {@code underlyingSource}.
*
* @param underlyingSource source used to load data into cache.
*/
public CachedConfigurationSource(ConfigurationSource underlyingSource) {
this.underlyingSource = requireNonNull(underlyingSource);
cachedConfigurationPerEnvironment = new HashMap<>();
}
/**
* Get configuration set for a given {@code environment} from the cache. For cache to be seeded
* you have to call the {@link #reload(Environment)} method before calling this method. Otherwise
* the method will throw {@link MissingEnvironmentException}.
*
* @param environment environment to use
* @return configuration set for {@code environment}
* @throws MissingEnvironmentException when there's no config for the given environment in the cache
*/
@Override
public Properties getConfiguration(Environment environment) {
if (cachedConfigurationPerEnvironment.containsKey(environment.getName())) {
return cachedConfigurationPerEnvironment.get(environment.getName());
} else { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/CachedConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload;
/**
* A {@link ConfigurationSource} that caches configuration between calls to the {@link #reload(Environment)} method.
*/
public class CachedConfigurationSource implements ConfigurationSource {
private final Map<String, Properties> cachedConfigurationPerEnvironment;
private final ConfigurationSource underlyingSource;
/**
* Create a new cached configuration source backed by {@code underlyingSource}.
*
* @param underlyingSource source used to load data into cache.
*/
public CachedConfigurationSource(ConfigurationSource underlyingSource) {
this.underlyingSource = requireNonNull(underlyingSource);
cachedConfigurationPerEnvironment = new HashMap<>();
}
/**
* Get configuration set for a given {@code environment} from the cache. For cache to be seeded
* you have to call the {@link #reload(Environment)} method before calling this method. Otherwise
* the method will throw {@link MissingEnvironmentException}.
*
* @param environment environment to use
* @return configuration set for {@code environment}
* @throws MissingEnvironmentException when there's no config for the given environment in the cache
*/
@Override
public Properties getConfiguration(Environment environment) {
if (cachedConfigurationPerEnvironment.containsKey(environment.getName())) {
return cachedConfigurationPerEnvironment.get(environment.getName());
} else { | throw new MissingEnvironmentException(environment.getName()); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithClasspathIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/classpath/ClasspathConfigurationSource.java
// public class ClasspathConfigurationSource implements ConfigurationSource {
//
// private final ConfigFilesProvider configFilesProvider;
// private final PropertiesProviderSelector propertiesProviderSelector;
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. Uses "application.properties" file
// * located in the path specified by the {@link Environment} provided to {@link #getConfiguration(Environment)}
// * calls (see corresponding javadoc for detail).
// */
// public ClasspathConfigurationSource() {
// this(() -> Collections.singletonList(
// Paths.get("application.properties")
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail). Configuration
// * file type is detected using file extension (see {@link PropertiesProviderSelector}).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider) {
// this(configFilesProvider, new PropertiesProviderSelector(
// new PropertyBasedPropertiesProvider(), new YamlBasedPropertiesProvider(), new JsonBasedPropertiesProvider()
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// * @param propertiesProviderSelector selector used for choosing {@link PropertiesProvider} based on a configuration file extension
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider, PropertiesProviderSelector propertiesProviderSelector) {
// this.configFilesProvider = requireNonNull(configFilesProvider);
// this.propertiesProviderSelector = requireNonNull(propertiesProviderSelector);
// }
//
// /**
// * Get configuration from classpath. See the class-level javadoc for detail on environment resolution.
// *
// * @param environment environment to fetch configuration for
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// @Override
// public Properties getConfiguration(Environment environment) {
// Properties properties = new Properties();
//
// Path pathPrefix = Paths.get(environment.getName());
//
// URL url = getClass().getClassLoader().getResource(pathPrefix.toString());
// if (url == null && !environment.getName().isEmpty()) {
// throw new MissingEnvironmentException("Directory doesn't exist: " + environment.getName());
// }
//
// List<Path> paths = new ArrayList<>();
// for (Path path : configFilesProvider.getConfigFiles()) {
// paths.add(pathPrefix.resolve(path));
// }
//
// for (Path path : paths) {
// try (InputStream input = getClass().getClassLoader().getResourceAsStream(path.toString())) {
//
// if (input == null) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path);
// }
//
// PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString());
// properties.putAll(provider.getProperties(input));
//
// } catch (IOException e) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path, e);
// }
// }
//
// return properties;
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "ClasspathConfigurationSource{" +
// "configFilesProvider=" + configFilesProvider +
// '}';
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.classpath.ClasspathConfigurationSource;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Collections; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithClasspathIntegrationTest {
@Test
void readsYamlBooleans() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlBooleans.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Boolean.class)).isTrue();
}
@Test
void readsYamlIntegers() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlIntegers.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Integer.class)).isEqualTo(42);
}
private ConfigurationProvider getConfigurationProvider(final String path) { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/classpath/ClasspathConfigurationSource.java
// public class ClasspathConfigurationSource implements ConfigurationSource {
//
// private final ConfigFilesProvider configFilesProvider;
// private final PropertiesProviderSelector propertiesProviderSelector;
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. Uses "application.properties" file
// * located in the path specified by the {@link Environment} provided to {@link #getConfiguration(Environment)}
// * calls (see corresponding javadoc for detail).
// */
// public ClasspathConfigurationSource() {
// this(() -> Collections.singletonList(
// Paths.get("application.properties")
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail). Configuration
// * file type is detected using file extension (see {@link PropertiesProviderSelector}).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider) {
// this(configFilesProvider, new PropertiesProviderSelector(
// new PropertyBasedPropertiesProvider(), new YamlBasedPropertiesProvider(), new JsonBasedPropertiesProvider()
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// * @param propertiesProviderSelector selector used for choosing {@link PropertiesProvider} based on a configuration file extension
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider, PropertiesProviderSelector propertiesProviderSelector) {
// this.configFilesProvider = requireNonNull(configFilesProvider);
// this.propertiesProviderSelector = requireNonNull(propertiesProviderSelector);
// }
//
// /**
// * Get configuration from classpath. See the class-level javadoc for detail on environment resolution.
// *
// * @param environment environment to fetch configuration for
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// @Override
// public Properties getConfiguration(Environment environment) {
// Properties properties = new Properties();
//
// Path pathPrefix = Paths.get(environment.getName());
//
// URL url = getClass().getClassLoader().getResource(pathPrefix.toString());
// if (url == null && !environment.getName().isEmpty()) {
// throw new MissingEnvironmentException("Directory doesn't exist: " + environment.getName());
// }
//
// List<Path> paths = new ArrayList<>();
// for (Path path : configFilesProvider.getConfigFiles()) {
// paths.add(pathPrefix.resolve(path));
// }
//
// for (Path path : paths) {
// try (InputStream input = getClass().getClassLoader().getResourceAsStream(path.toString())) {
//
// if (input == null) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path);
// }
//
// PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString());
// properties.putAll(provider.getProperties(input));
//
// } catch (IOException e) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path, e);
// }
// }
//
// return properties;
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "ClasspathConfigurationSource{" +
// "configFilesProvider=" + configFilesProvider +
// '}';
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithClasspathIntegrationTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.classpath.ClasspathConfigurationSource;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Collections;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithClasspathIntegrationTest {
@Test
void readsYamlBooleans() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlBooleans.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Boolean.class)).isTrue();
}
@Test
void readsYamlIntegers() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlIntegers.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Integer.class)).isEqualTo(42);
}
private ConfigurationProvider getConfigurationProvider(final String path) { | ConfigurationSource source = new ClasspathConfigurationSource(() -> Collections.singleton(Paths.get(path))); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithClasspathIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/classpath/ClasspathConfigurationSource.java
// public class ClasspathConfigurationSource implements ConfigurationSource {
//
// private final ConfigFilesProvider configFilesProvider;
// private final PropertiesProviderSelector propertiesProviderSelector;
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. Uses "application.properties" file
// * located in the path specified by the {@link Environment} provided to {@link #getConfiguration(Environment)}
// * calls (see corresponding javadoc for detail).
// */
// public ClasspathConfigurationSource() {
// this(() -> Collections.singletonList(
// Paths.get("application.properties")
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail). Configuration
// * file type is detected using file extension (see {@link PropertiesProviderSelector}).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider) {
// this(configFilesProvider, new PropertiesProviderSelector(
// new PropertyBasedPropertiesProvider(), new YamlBasedPropertiesProvider(), new JsonBasedPropertiesProvider()
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// * @param propertiesProviderSelector selector used for choosing {@link PropertiesProvider} based on a configuration file extension
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider, PropertiesProviderSelector propertiesProviderSelector) {
// this.configFilesProvider = requireNonNull(configFilesProvider);
// this.propertiesProviderSelector = requireNonNull(propertiesProviderSelector);
// }
//
// /**
// * Get configuration from classpath. See the class-level javadoc for detail on environment resolution.
// *
// * @param environment environment to fetch configuration for
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// @Override
// public Properties getConfiguration(Environment environment) {
// Properties properties = new Properties();
//
// Path pathPrefix = Paths.get(environment.getName());
//
// URL url = getClass().getClassLoader().getResource(pathPrefix.toString());
// if (url == null && !environment.getName().isEmpty()) {
// throw new MissingEnvironmentException("Directory doesn't exist: " + environment.getName());
// }
//
// List<Path> paths = new ArrayList<>();
// for (Path path : configFilesProvider.getConfigFiles()) {
// paths.add(pathPrefix.resolve(path));
// }
//
// for (Path path : paths) {
// try (InputStream input = getClass().getClassLoader().getResourceAsStream(path.toString())) {
//
// if (input == null) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path);
// }
//
// PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString());
// properties.putAll(provider.getProperties(input));
//
// } catch (IOException e) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path, e);
// }
// }
//
// return properties;
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "ClasspathConfigurationSource{" +
// "configFilesProvider=" + configFilesProvider +
// '}';
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.classpath.ClasspathConfigurationSource;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Collections; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithClasspathIntegrationTest {
@Test
void readsYamlBooleans() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlBooleans.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Boolean.class)).isTrue();
}
@Test
void readsYamlIntegers() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlIntegers.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Integer.class)).isEqualTo(42);
}
private ConfigurationProvider getConfigurationProvider(final String path) { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/classpath/ClasspathConfigurationSource.java
// public class ClasspathConfigurationSource implements ConfigurationSource {
//
// private final ConfigFilesProvider configFilesProvider;
// private final PropertiesProviderSelector propertiesProviderSelector;
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. Uses "application.properties" file
// * located in the path specified by the {@link Environment} provided to {@link #getConfiguration(Environment)}
// * calls (see corresponding javadoc for detail).
// */
// public ClasspathConfigurationSource() {
// this(() -> Collections.singletonList(
// Paths.get("application.properties")
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail). Configuration
// * file type is detected using file extension (see {@link PropertiesProviderSelector}).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider) {
// this(configFilesProvider, new PropertiesProviderSelector(
// new PropertyBasedPropertiesProvider(), new YamlBasedPropertiesProvider(), new JsonBasedPropertiesProvider()
// ));
// }
//
// /**
// * Construct {@link ConfigurationSource} backed by classpath files. File paths should by provided by
// * {@link ConfigFilesProvider} and will be treated as relative paths to the environment provided in
// * {@link #getConfiguration(Environment)} calls (see corresponding javadoc for detail).
// *
// * @param configFilesProvider {@link ConfigFilesProvider} supplying a list of configuration files to use
// * @param propertiesProviderSelector selector used for choosing {@link PropertiesProvider} based on a configuration file extension
// */
// public ClasspathConfigurationSource(ConfigFilesProvider configFilesProvider, PropertiesProviderSelector propertiesProviderSelector) {
// this.configFilesProvider = requireNonNull(configFilesProvider);
// this.propertiesProviderSelector = requireNonNull(propertiesProviderSelector);
// }
//
// /**
// * Get configuration from classpath. See the class-level javadoc for detail on environment resolution.
// *
// * @param environment environment to fetch configuration for
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// @Override
// public Properties getConfiguration(Environment environment) {
// Properties properties = new Properties();
//
// Path pathPrefix = Paths.get(environment.getName());
//
// URL url = getClass().getClassLoader().getResource(pathPrefix.toString());
// if (url == null && !environment.getName().isEmpty()) {
// throw new MissingEnvironmentException("Directory doesn't exist: " + environment.getName());
// }
//
// List<Path> paths = new ArrayList<>();
// for (Path path : configFilesProvider.getConfigFiles()) {
// paths.add(pathPrefix.resolve(path));
// }
//
// for (Path path : paths) {
// try (InputStream input = getClass().getClassLoader().getResourceAsStream(path.toString())) {
//
// if (input == null) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path);
// }
//
// PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString());
// properties.putAll(provider.getProperties(input));
//
// } catch (IOException e) {
// throw new IllegalStateException("Unable to load properties from classpath: " + path, e);
// }
// }
//
// return properties;
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "ClasspathConfigurationSource{" +
// "configFilesProvider=" + configFilesProvider +
// '}';
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithClasspathIntegrationTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.classpath.ClasspathConfigurationSource;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Collections;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithClasspathIntegrationTest {
@Test
void readsYamlBooleans() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlBooleans.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Boolean.class)).isTrue();
}
@Test
void readsYamlIntegers() {
String path = "org/cfg4j/provider/SimpleConfigurationProviderIntegrationTest_readsYamlIntegers.yaml";
ConfigurationProvider provider = getConfigurationProvider(path);
assertThat(provider.getProperty("someSetting", Integer.class)).isEqualTo(42);
}
private ConfigurationProvider getConfigurationProvider(final String path) { | ConfigurationSource source = new ClasspathConfigurationSource(() -> Collections.singleton(Paths.get(path))); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.empty;
class EmptyConfigurationSourceTest {
private EmptyConfigurationSource source;
@BeforeEach
void setUp() {
source = new EmptyConfigurationSource();
source.init();
}
@Test
void returnsEmptyConfiguration() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.empty;
class EmptyConfigurationSourceTest {
private EmptyConfigurationSource source;
@BeforeEach
void setUp() {
source = new EmptyConfigurationSource();
source.init();
}
@Test
void returnsEmptyConfiguration() { | assertThat(source.getConfiguration(new DefaultEnvironment())).isEmpty(); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.empty;
class EmptyConfigurationSourceTest {
private EmptyConfigurationSource source;
@BeforeEach
void setUp() {
source = new EmptyConfigurationSource();
source.init();
}
@Test
void returnsEmptyConfiguration() {
assertThat(source.getConfiguration(new DefaultEnvironment())).isEmpty();
}
@Test
void returnsEmptyConfigurationForAnyEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.empty;
class EmptyConfigurationSourceTest {
private EmptyConfigurationSource source;
@BeforeEach
void setUp() {
source = new EmptyConfigurationSource();
source.init();
}
@Test
void returnsEmptyConfiguration() {
assertThat(source.getConfiguration(new DefaultEnvironment())).isEmpty();
}
@Test
void returnsEmptyConfigurationForAnyEnvironment() { | assertThat(source.getConfiguration(mock(Environment.class))).isEmpty(); |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/reload/strategy/ImmediateReloadStrategy.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
/**
* {@link ReloadStrategy} that reloads the resource only once - the moment the {@link #register(Reloadable)} is called.
*/
public class ImmediateReloadStrategy implements ReloadStrategy {
private static final Logger LOG = LoggerFactory.getLogger(ImmediateReloadStrategy.class);
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/strategy/ImmediateReloadStrategy.java
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
/**
* {@link ReloadStrategy} that reloads the resource only once - the moment the {@link #register(Reloadable)} is called.
*/
public class ImmediateReloadStrategy implements ReloadStrategy {
private static final Logger LOG = LoggerFactory.getLogger(ImmediateReloadStrategy.class);
@Override | public void register(Reloadable resource) { |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock | private ConfigurationSource delegateSource; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock
private ConfigurationSource delegateSource;
private CachedConfigurationSource cachedConfigurationSource;
@BeforeEach
void setUp() {
cachedConfigurationSource = new CachedConfigurationSource(delegateSource);
}
@Test
void initPropagatesMissingEnvExceptions() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock
private ConfigurationSource delegateSource;
private CachedConfigurationSource cachedConfigurationSource;
@BeforeEach
void setUp() {
cachedConfigurationSource = new CachedConfigurationSource(delegateSource);
}
@Test
void initPropagatesMissingEnvExceptions() { | doThrow(new MissingEnvironmentException("")).when(delegateSource).init(); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock
private ConfigurationSource delegateSource;
private CachedConfigurationSource cachedConfigurationSource;
@BeforeEach
void setUp() {
cachedConfigurationSource = new CachedConfigurationSource(delegateSource);
}
@Test
void initPropagatesMissingEnvExceptions() {
doThrow(new MissingEnvironmentException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void initPropagatesIllegalStateExceptions() {
doThrow(new IllegalStateException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void getConfigurationThrowsOnMissingEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock
private ConfigurationSource delegateSource;
private CachedConfigurationSource cachedConfigurationSource;
@BeforeEach
void setUp() {
cachedConfigurationSource = new CachedConfigurationSource(delegateSource);
}
@Test
void initPropagatesMissingEnvExceptions() {
doThrow(new MissingEnvironmentException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void initPropagatesIllegalStateExceptions() {
doThrow(new IllegalStateException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void getConfigurationThrowsOnMissingEnvironment() { | assertThatThrownBy(() -> cachedConfigurationSource.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(MissingEnvironmentException.class); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock
private ConfigurationSource delegateSource;
private CachedConfigurationSource cachedConfigurationSource;
@BeforeEach
void setUp() {
cachedConfigurationSource = new CachedConfigurationSource(delegateSource);
}
@Test
void initPropagatesMissingEnvExceptions() {
doThrow(new MissingEnvironmentException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void initPropagatesIllegalStateExceptions() {
doThrow(new IllegalStateException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void getConfigurationThrowsOnMissingEnvironment() {
assertThatThrownBy(() -> cachedConfigurationSource.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationReturnsReloadResult() {
Properties properties = new Properties(); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/reload/CachedConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
package org.cfg4j.source.reload;
@ExtendWith(MockitoExtension.class)
class CachedConfigurationSourceTest {
@Mock
private ConfigurationSource delegateSource;
private CachedConfigurationSource cachedConfigurationSource;
@BeforeEach
void setUp() {
cachedConfigurationSource = new CachedConfigurationSource(delegateSource);
}
@Test
void initPropagatesMissingEnvExceptions() {
doThrow(new MissingEnvironmentException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void initPropagatesIllegalStateExceptions() {
doThrow(new IllegalStateException("")).when(delegateSource).init();
assertThatThrownBy(() -> cachedConfigurationSource.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void getConfigurationThrowsOnMissingEnvironment() {
assertThatThrownBy(() -> cachedConfigurationSource.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationReturnsReloadResult() {
Properties properties = new Properties(); | when(delegateSource.getConfiguration(any(Environment.class))).thenReturn(properties); |
cfg4j/cfg4j | cfg4j-git/src/main/java/org/cfg4j/source/git/FirstTokenBranchResolver.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import org.cfg4j.source.context.environment.Environment; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
/**
* Adapter for {@link Environment} to provide git branch resolution through {@link BranchResolver} interface.
* The adaptation process works as follows:
* <ul>
* <li>the environment name is split into tokens divided by "/"</li>
* <li>first token is treated as a branch name</li>
* <li>if the branch name is empty ("", or contains only whitespaces) then the "master" branch is used</li>
* </ul>
*/
public class FirstTokenBranchResolver implements BranchResolver {
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-git/src/main/java/org/cfg4j/source/git/FirstTokenBranchResolver.java
import org.cfg4j.source.context.environment.Environment;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
/**
* Adapter for {@link Environment} to provide git branch resolution through {@link BranchResolver} interface.
* The adaptation process works as follows:
* <ul>
* <li>the environment name is split into tokens divided by "/"</li>
* <li>first token is treated as a branch name</li>
* <li>if the branch name is empty ("", or contains only whitespaces) then the "master" branch is used</li>
* </ul>
*/
public class FirstTokenBranchResolver implements BranchResolver {
@Override | public String getBranchNameFor(Environment environment) { |
cfg4j/cfg4j | cfg4j-consul/src/main/java/org/cfg4j/source/consul/ConsulConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import java.util.Properties;
import static java.util.Objects.requireNonNull;
import com.google.common.net.HostAndPort;
import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;
import com.orbitz.consul.model.kv.Value;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.consul;
/**
* Note: use {@link ConsulConfigurationSourceBuilder} for building instances of this class.
* <p>
* Read configuration from the Consul K-V store.
*/
public class ConsulConfigurationSource implements ConfigurationSource {
private static final Logger LOG = LoggerFactory.getLogger(ConsulConfigurationSource.class);
private KeyValueClient kvClient;
private Map<String, String> consulValues;
private final String host;
private final int port;
private boolean initialized;
/**
* Note: use {@link ConsulConfigurationSourceBuilder} for building instances of this class.
* <p>
* Read configuration from the Consul K-V store located at {@code host}:{@code port}.
*
* @param host Consul host to connect to
* @param port Consul port to connect to
*/
ConsulConfigurationSource(String host, int port) {
this.host = requireNonNull(host);
this.port = port;
initialized = false;
}
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-consul/src/main/java/org/cfg4j/source/consul/ConsulConfigurationSource.java
import java.util.Properties;
import static java.util.Objects.requireNonNull;
import com.google.common.net.HostAndPort;
import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;
import com.orbitz.consul.model.kv.Value;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.consul;
/**
* Note: use {@link ConsulConfigurationSourceBuilder} for building instances of this class.
* <p>
* Read configuration from the Consul K-V store.
*/
public class ConsulConfigurationSource implements ConfigurationSource {
private static final Logger LOG = LoggerFactory.getLogger(ConsulConfigurationSource.class);
private KeyValueClient kvClient;
private Map<String, String> consulValues;
private final String host;
private final int port;
private boolean initialized;
/**
* Note: use {@link ConsulConfigurationSourceBuilder} for building instances of this class.
* <p>
* Read configuration from the Consul K-V store located at {@code host}:{@code port}.
*
* @param host Consul host to connect to
* @param port Consul port to connect to
*/
ConsulConfigurationSource(String host, int port) {
this.host = requireNonNull(host);
this.port = port;
initialized = false;
}
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-consul/src/main/java/org/cfg4j/source/consul/ConsulConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import java.util.Properties;
import static java.util.Objects.requireNonNull;
import com.google.common.net.HostAndPort;
import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;
import com.orbitz.consul.model.kv.Value;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map; |
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.length() > 0 && !path.endsWith("/")) {
path = path + "/";
}
for (Map.Entry<String, String> entry : consulValues.entrySet()) {
if (entry.getKey().startsWith(path)) {
properties.put(entry.getKey().substring(path.length()).replace("/", "."), entry.getValue());
}
}
return properties;
}
/**
* @throws SourceCommunicationException when unable to connect to Consul client
*/
@Override
public void init() {
try {
LOG.info("Connecting to Consul client at " + host + ":" + port);
Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromParts(host, port)).build();
kvClient = consul.keyValueClient();
} catch (Exception e) { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-consul/src/main/java/org/cfg4j/source/consul/ConsulConfigurationSource.java
import java.util.Properties;
import static java.util.Objects.requireNonNull;
import com.google.common.net.HostAndPort;
import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;
import com.orbitz.consul.model.kv.Value;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.length() > 0 && !path.endsWith("/")) {
path = path + "/";
}
for (Map.Entry<String, String> entry : consulValues.entrySet()) {
if (entry.getKey().startsWith(path)) {
properties.put(entry.getKey().substring(path.length()).replace("/", "."), entry.getValue());
}
}
return properties;
}
/**
* @throws SourceCommunicationException when unable to connect to Consul client
*/
@Override
public void init() {
try {
LOG.info("Connecting to Consul client at " + host + ":" + port);
Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromParts(host, port)).build();
kvClient = consul.keyValueClient();
} catch (Exception e) { | throw new SourceCommunicationException("Can't connect to host " + host + ":" + port, e); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/system/SystemPropertiesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class SystemPropertiesConfigurationSourceTest {
private SystemPropertiesConfigurationSource source;
@BeforeEach
void setUp() {
source = new SystemPropertiesConfigurationSource();
source.init();
}
@Test
void returnsOSName() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/system/SystemPropertiesConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class SystemPropertiesConfigurationSourceTest {
private SystemPropertiesConfigurationSource source;
@BeforeEach
void setUp() {
source = new SystemPropertiesConfigurationSource();
source.init();
}
@Test
void returnsOSName() { | assertThat(source.getConfiguration(new DefaultEnvironment())).containsKey("os.name"); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/system/SystemPropertiesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class SystemPropertiesConfigurationSourceTest {
private SystemPropertiesConfigurationSource source;
@BeforeEach
void setUp() {
source = new SystemPropertiesConfigurationSource();
source.init();
}
@Test
void returnsOSName() {
assertThat(source.getConfiguration(new DefaultEnvironment())).containsKey("os.name");
}
@Test
void returnsOsNameForAnyEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/system/SystemPropertiesConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class SystemPropertiesConfigurationSourceTest {
private SystemPropertiesConfigurationSource source;
@BeforeEach
void setUp() {
source = new SystemPropertiesConfigurationSource();
source.init();
}
@Test
void returnsOSName() {
assertThat(source.getConfiguration(new DefaultEnvironment())).containsKey("os.name");
}
@Test
void returnsOsNameForAnyEnvironment() { | assertThat(source.getConfiguration(mock(Environment.class))).containsKey("os.name"); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo; | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo; | private ConfigFilesProvider configFilesProvider; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() { | Environment environment = new ImmutableEnvironment("otherApplicationConfigs"); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() { | Environment environment = new ImmutableEnvironment("otherApplicationConfigs"); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment("otherApplicationConfigs");
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationDisallowsLeadingSlashInClasspathLocation() {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs");
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment("otherApplicationConfigs");
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationDisallowsLeadingSlashInClasspathLocation() {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs");
| assertThatThrownBy(() -> source.getConfiguration(environment)).isExactlyInstanceOf(MissingEnvironmentException.class); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; | source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment("otherApplicationConfigs");
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationDisallowsLeadingSlashInClasspathLocation() {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs");
assertThatThrownBy(() -> source.getConfiguration(environment)).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationReadsFromGivenFiles() {
configFilesProvider = () -> Arrays.asList(
Paths.get("application.properties"),
Paths.get("otherConfig.properties")
);
source = new ClasspathConfigurationSource(configFilesProvider); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment("otherApplicationConfigs");
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationDisallowsLeadingSlashInClasspathLocation() {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs");
assertThatThrownBy(() -> source.getConfiguration(environment)).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationReadsFromGivenFiles() {
configFilesProvider = () -> Arrays.asList(
Paths.get("application.properties"),
Paths.get("otherConfig.properties")
);
source = new ClasspathConfigurationSource(configFilesProvider); | assertThat(source.getConfiguration(new DefaultEnvironment())).containsOnlyKeys("some.setting", "otherConfig.setting"); |
cfg4j/cfg4j | cfg4j-git/src/main/java/org/cfg4j/source/git/AllButFirstTokenPathResolver.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import org.cfg4j.source.context.environment.Environment;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Arrays; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
/**
* Adapter for {@link Environment} to provide git path resolution through {@link PathResolver} interface.
* The adaptation process works as follows:
* <ul>
* <li>the environment name is split into tokens divided by "/"</li>
* <li>first token is discarded</li>
* <li>remaining tokens are re-combined and used as a path</li>
* </ul>
*/
public class AllButFirstTokenPathResolver implements PathResolver {
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-git/src/main/java/org/cfg4j/source/git/AllButFirstTokenPathResolver.java
import org.cfg4j.source.context.environment.Environment;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Arrays;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
/**
* Adapter for {@link Environment} to provide git path resolution through {@link PathResolver} interface.
* The adaptation process works as follows:
* <ul>
* <li>the environment name is split into tokens divided by "/"</li>
* <li>first token is discarded</li>
* <li>remaining tokens are re-combined and used as a path</li>
* </ul>
*/
public class AllButFirstTokenPathResolver implements PathResolver {
@Override | public Path getPathFor(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/inmemory/InMemoryConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.inmemory;
class InMemoryConfigurationSourceTest {
private InMemoryConfigurationSource source;
private Properties properties;
@BeforeEach
void setUp() {
properties = new Properties();
properties.put("sample.setting", "value");
source = new InMemoryConfigurationSource(properties);
source.init();
}
@Test
void returnsSourceProperties() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/inmemory/InMemoryConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.inmemory;
class InMemoryConfigurationSourceTest {
private InMemoryConfigurationSource source;
private Properties properties;
@BeforeEach
void setUp() {
properties = new Properties();
properties.put("sample.setting", "value");
source = new InMemoryConfigurationSource(properties);
source.init();
}
@Test
void returnsSourceProperties() { | assertThat(source.getConfiguration(new DefaultEnvironment())).isEqualTo(properties); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithMeteredSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/inmemory/InMemoryConfigurationSource.java
// public class InMemoryConfigurationSource implements ConfigurationSource {
//
// private final Properties properties;
//
// /**
// * Create in-memory configuration source with given {@code properties}.
// *
// * @param properties properties to seed source.
// */
// public InMemoryConfigurationSource(Properties properties) {
// this.properties = requireNonNull(properties);
// }
//
// @Override
// public Properties getConfiguration(Environment environment) {
// return (Properties) properties.clone();
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "InMemoryConfigurationSource{" +
// "properties=" + properties +
// '}';
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import com.codahale.metrics.MetricRegistry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.inmemory.InMemoryConfigurationSource;
import org.junit.jupiter.api.Test;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithMeteredSourceIntegrationTest {
private MetricRegistry metricRegistry = new MetricRegistry();
@Test
void emitsMetrics() {
ConfigurationProvider provider = getConfigurationProvider();
provider.getProperty("some.setting", Boolean.class);
assertThat(metricRegistry.getTimers()).containsOnlyKeys(
"testService.allConfigurationAsProperties",
"testService.getProperty",
"testService.getPropertyGeneric",
"testService.bind",
"testService.source.getConfiguration",
"testService.source.init",
"testService.reloadable.reload"
);
}
private ConfigurationProvider getConfigurationProvider() {
Properties properties = new Properties();
properties.put("some.setting", "true");
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/inmemory/InMemoryConfigurationSource.java
// public class InMemoryConfigurationSource implements ConfigurationSource {
//
// private final Properties properties;
//
// /**
// * Create in-memory configuration source with given {@code properties}.
// *
// * @param properties properties to seed source.
// */
// public InMemoryConfigurationSource(Properties properties) {
// this.properties = requireNonNull(properties);
// }
//
// @Override
// public Properties getConfiguration(Environment environment) {
// return (Properties) properties.clone();
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "InMemoryConfigurationSource{" +
// "properties=" + properties +
// '}';
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithMeteredSourceIntegrationTest.java
import static org.assertj.core.api.Assertions.assertThat;
import com.codahale.metrics.MetricRegistry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.inmemory.InMemoryConfigurationSource;
import org.junit.jupiter.api.Test;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithMeteredSourceIntegrationTest {
private MetricRegistry metricRegistry = new MetricRegistry();
@Test
void emitsMetrics() {
ConfigurationProvider provider = getConfigurationProvider();
provider.getProperty("some.setting", Boolean.class);
assertThat(metricRegistry.getTimers()).containsOnlyKeys(
"testService.allConfigurationAsProperties",
"testService.getProperty",
"testService.getPropertyGeneric",
"testService.bind",
"testService.source.getConfiguration",
"testService.source.init",
"testService.reloadable.reload"
);
}
private ConfigurationProvider getConfigurationProvider() {
Properties properties = new Properties();
properties.put("some.setting", "true");
| ConfigurationSource source = new InMemoryConfigurationSource(properties); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithMeteredSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/inmemory/InMemoryConfigurationSource.java
// public class InMemoryConfigurationSource implements ConfigurationSource {
//
// private final Properties properties;
//
// /**
// * Create in-memory configuration source with given {@code properties}.
// *
// * @param properties properties to seed source.
// */
// public InMemoryConfigurationSource(Properties properties) {
// this.properties = requireNonNull(properties);
// }
//
// @Override
// public Properties getConfiguration(Environment environment) {
// return (Properties) properties.clone();
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "InMemoryConfigurationSource{" +
// "properties=" + properties +
// '}';
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import com.codahale.metrics.MetricRegistry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.inmemory.InMemoryConfigurationSource;
import org.junit.jupiter.api.Test;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithMeteredSourceIntegrationTest {
private MetricRegistry metricRegistry = new MetricRegistry();
@Test
void emitsMetrics() {
ConfigurationProvider provider = getConfigurationProvider();
provider.getProperty("some.setting", Boolean.class);
assertThat(metricRegistry.getTimers()).containsOnlyKeys(
"testService.allConfigurationAsProperties",
"testService.getProperty",
"testService.getPropertyGeneric",
"testService.bind",
"testService.source.getConfiguration",
"testService.source.init",
"testService.reloadable.reload"
);
}
private ConfigurationProvider getConfigurationProvider() {
Properties properties = new Properties();
properties.put("some.setting", "true");
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/inmemory/InMemoryConfigurationSource.java
// public class InMemoryConfigurationSource implements ConfigurationSource {
//
// private final Properties properties;
//
// /**
// * Create in-memory configuration source with given {@code properties}.
// *
// * @param properties properties to seed source.
// */
// public InMemoryConfigurationSource(Properties properties) {
// this.properties = requireNonNull(properties);
// }
//
// @Override
// public Properties getConfiguration(Environment environment) {
// return (Properties) properties.clone();
// }
//
// @Override
// public void init() {
// // NOP
// }
//
// @Override
// public String toString() {
// return "InMemoryConfigurationSource{" +
// "properties=" + properties +
// '}';
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderWithMeteredSourceIntegrationTest.java
import static org.assertj.core.api.Assertions.assertThat;
import com.codahale.metrics.MetricRegistry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.inmemory.InMemoryConfigurationSource;
import org.junit.jupiter.api.Test;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderWithMeteredSourceIntegrationTest {
private MetricRegistry metricRegistry = new MetricRegistry();
@Test
void emitsMetrics() {
ConfigurationProvider provider = getConfigurationProvider();
provider.getProperty("some.setting", Boolean.class);
assertThat(metricRegistry.getTimers()).containsOnlyKeys(
"testService.allConfigurationAsProperties",
"testService.getProperty",
"testService.getPropertyGeneric",
"testService.bind",
"testService.source.getConfiguration",
"testService.source.init",
"testService.reloadable.reload"
);
}
private ConfigurationProvider getConfigurationProvider() {
Properties properties = new Properties();
properties.put("some.setting", "true");
| ConfigurationSource source = new InMemoryConfigurationSource(properties); |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/AllButFirstTokenPathResolverTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
@ExtendWith(MockitoExtension.class)
class AllButFirstTokenPathResolverTest {
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/AllButFirstTokenPathResolverTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
@ExtendWith(MockitoExtension.class)
class AllButFirstTokenPathResolverTest {
@Mock | private Environment environment; |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path; | remoteRepo.changeProperty(Paths.get("otherConfig.properties"), "otherConfig.setting", "masterValue");
remoteRepo.changeProperty(Paths.get("malformed.properties"), "otherConfig.setting", "\\uzzzzz");
remoteRepo.changeProperty(Paths.get("otherApplicationConfigs/application.properties"), "some.setting", "otherAppSetting");
remoteRepo.changeBranchTo(TEST_ENV_BRANCH);
remoteRepo.changeProperty(Paths.get("application.properties"), "some.setting", "testValue");
remoteRepo.changeBranchTo(DEFAULT_BRANCH);
}
@AfterEach
void tearDown() {
remoteRepo.remove();
}
@Test
void initThrowsWhenUnableToCreateLocalCloneOnNoTempDir() {
assertThatThrownBy(() ->
getSourceBuilderForRemoteRepoWithDefaults()
.withTmpPath(Paths.get("/someNonexistentDir/lkfjalfcz"))
.withTmpRepoPrefix("existing-path")
.build()
.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initThrowsOnInvalidRemote() {
assertThatThrownBy(() -> new GitConfigurationSourceBuilder()
.withRepositoryURI("")
.build() | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
remoteRepo.changeProperty(Paths.get("otherConfig.properties"), "otherConfig.setting", "masterValue");
remoteRepo.changeProperty(Paths.get("malformed.properties"), "otherConfig.setting", "\\uzzzzz");
remoteRepo.changeProperty(Paths.get("otherApplicationConfigs/application.properties"), "some.setting", "otherAppSetting");
remoteRepo.changeBranchTo(TEST_ENV_BRANCH);
remoteRepo.changeProperty(Paths.get("application.properties"), "some.setting", "testValue");
remoteRepo.changeBranchTo(DEFAULT_BRANCH);
}
@AfterEach
void tearDown() {
remoteRepo.remove();
}
@Test
void initThrowsWhenUnableToCreateLocalCloneOnNoTempDir() {
assertThatThrownBy(() ->
getSourceBuilderForRemoteRepoWithDefaults()
.withTmpPath(Paths.get("/someNonexistentDir/lkfjalfcz"))
.withTmpRepoPrefix("existing-path")
.build()
.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initThrowsOnInvalidRemote() {
assertThatThrownBy(() -> new GitConfigurationSourceBuilder()
.withRepositoryURI("")
.build() | .init()).isExactlyInstanceOf(SourceCommunicationException.class); |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path; | }
@AfterEach
void tearDown() {
remoteRepo.remove();
}
@Test
void initThrowsWhenUnableToCreateLocalCloneOnNoTempDir() {
assertThatThrownBy(() ->
getSourceBuilderForRemoteRepoWithDefaults()
.withTmpPath(Paths.get("/someNonexistentDir/lkfjalfcz"))
.withTmpRepoPrefix("existing-path")
.build()
.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initThrowsOnInvalidRemote() {
assertThatThrownBy(() -> new GitConfigurationSourceBuilder()
.withRepositoryURI("")
.build()
.init()).isExactlyInstanceOf(SourceCommunicationException.class);
}
@Test
void getConfigurationUsesBranchResolver() throws Exception {
class Resolver implements BranchResolver {
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
}
@AfterEach
void tearDown() {
remoteRepo.remove();
}
@Test
void initThrowsWhenUnableToCreateLocalCloneOnNoTempDir() {
assertThatThrownBy(() ->
getSourceBuilderForRemoteRepoWithDefaults()
.withTmpPath(Paths.get("/someNonexistentDir/lkfjalfcz"))
.withTmpRepoPrefix("existing-path")
.build()
.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initThrowsOnInvalidRemote() {
assertThatThrownBy(() -> new GitConfigurationSourceBuilder()
.withRepositoryURI("")
.build()
.init()).isExactlyInstanceOf(SourceCommunicationException.class);
}
@Test
void getConfigurationUsesBranchResolver() throws Exception {
class Resolver implements BranchResolver {
@Override | public String getBranchNameFor(Environment environment) { |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path; |
@Test
void initThrowsWhenUnableToCreateLocalCloneOnNoTempDir() {
assertThatThrownBy(() ->
getSourceBuilderForRemoteRepoWithDefaults()
.withTmpPath(Paths.get("/someNonexistentDir/lkfjalfcz"))
.withTmpRepoPrefix("existing-path")
.build()
.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initThrowsOnInvalidRemote() {
assertThatThrownBy(() -> new GitConfigurationSourceBuilder()
.withRepositoryURI("")
.build()
.init()).isExactlyInstanceOf(SourceCommunicationException.class);
}
@Test
void getConfigurationUsesBranchResolver() throws Exception {
class Resolver implements BranchResolver {
@Override
public String getBranchNameFor(Environment environment) {
return TEST_ENV_BRANCH;
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithBranchResolver(new Resolver())) { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
@Test
void initThrowsWhenUnableToCreateLocalCloneOnNoTempDir() {
assertThatThrownBy(() ->
getSourceBuilderForRemoteRepoWithDefaults()
.withTmpPath(Paths.get("/someNonexistentDir/lkfjalfcz"))
.withTmpRepoPrefix("existing-path")
.build()
.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initThrowsOnInvalidRemote() {
assertThatThrownBy(() -> new GitConfigurationSourceBuilder()
.withRepositoryURI("")
.build()
.init()).isExactlyInstanceOf(SourceCommunicationException.class);
}
@Test
void getConfigurationUsesBranchResolver() throws Exception {
class Resolver implements BranchResolver {
@Override
public String getBranchNameFor(Environment environment) {
return TEST_ENV_BRANCH;
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithBranchResolver(new Resolver())) { | Environment environment = new ImmutableEnvironment("ignoreMePlease"); |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path; | }
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithBranchResolver(new Resolver())) {
Environment environment = new ImmutableEnvironment("ignoreMePlease");
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "testValue"));
}
}
@Test
void getConfigurationReadsConfigFromGivenBranch() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
Environment environment = new ImmutableEnvironment(TEST_ENV_BRANCH);
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "testValue"));
}
}
@Test
void getConfigurationUsesPathResolver() throws Exception {
class Resolver implements PathResolver {
@Override
public Path getPathFor(Environment environment) {
return Paths.get("otherApplicationConfigs");
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithPathResolver(new Resolver())) { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithBranchResolver(new Resolver())) {
Environment environment = new ImmutableEnvironment("ignoreMePlease");
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "testValue"));
}
}
@Test
void getConfigurationReadsConfigFromGivenBranch() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
Environment environment = new ImmutableEnvironment(TEST_ENV_BRANCH);
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "testValue"));
}
}
@Test
void getConfigurationUsesPathResolver() throws Exception {
class Resolver implements PathResolver {
@Override
public Path getPathFor(Environment environment) {
return Paths.get("otherApplicationConfigs");
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithPathResolver(new Resolver())) { | Environment environment = new DefaultEnvironment(); |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path; | }
@Test
void getConfigurationUsesPathResolver() throws Exception {
class Resolver implements PathResolver {
@Override
public Path getPathFor(Environment environment) {
return Paths.get("otherApplicationConfigs");
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithPathResolver(new Resolver())) {
Environment environment = new DefaultEnvironment();
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenPath() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs/");
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenFiles() throws Exception { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
}
@Test
void getConfigurationUsesPathResolver() throws Exception {
class Resolver implements PathResolver {
@Override
public Path getPathFor(Environment environment) {
return Paths.get("otherApplicationConfigs");
}
}
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithPathResolver(new Resolver())) {
Environment environment = new DefaultEnvironment();
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenPath() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs/");
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenFiles() throws Exception { | ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("application.properties"), Paths.get("otherConfig.properties")); |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path; | Environment environment = new DefaultEnvironment();
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenPath() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs/");
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenFiles() throws Exception {
ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("application.properties"), Paths.get("otherConfig.properties"));
Environment environment = new DefaultEnvironment();
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithFilesProvider(configFilesProvider)) {
assertThat(gitConfigurationSource.getConfiguration(environment)).containsKeys("some.setting", "otherConfig.setting");
}
}
@Test
void getConfigurationThrowsOnMissingBranch() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
assertThatThrownBy(() -> gitConfigurationSource.getConfiguration(new ImmutableEnvironment("nonExistentBranch"))) | // Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/GitConfigurationSourceIntegrationTest.java
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
Environment environment = new DefaultEnvironment();
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenPath() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs/");
assertThat(gitConfigurationSource.getConfiguration(environment)).contains(MapEntry.entry("some.setting", "otherAppSetting"));
}
}
@Test
void getConfigurationReadsFromGivenFiles() throws Exception {
ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("application.properties"), Paths.get("otherConfig.properties"));
Environment environment = new DefaultEnvironment();
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithFilesProvider(configFilesProvider)) {
assertThat(gitConfigurationSource.getConfiguration(environment)).containsKeys("some.setting", "otherConfig.setting");
}
}
@Test
void getConfigurationThrowsOnMissingBranch() throws Exception {
try (GitConfigurationSource gitConfigurationSource = getSourceForRemoteRepoWithDefaults()) {
assertThatThrownBy(() -> gitConfigurationSource.getConfiguration(new ImmutableEnvironment("nonExistentBranch"))) | .isExactlyInstanceOf(MissingEnvironmentException.class); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/reload/strategy/PeriodicalReloadStrategyTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.concurrent.TimeUnit; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
@ExtendWith(MockitoExtension.class)
class PeriodicalReloadStrategyTest {
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/reload/strategy/PeriodicalReloadStrategyTest.java
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.concurrent.TimeUnit;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
@ExtendWith(MockitoExtension.class)
class PeriodicalReloadStrategyTest {
@Mock | private Reloadable reloadable; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderGetPropertyTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderGetPropertyTest extends SimpleConfigurationProviderAbstractTest {
@Test
void allConfigurationAsPropertiesThrowsWhenUnableToFetchConfiguration() {
when(configurationSource.getConfiguration(anyEnvironment())).thenThrow(new IllegalStateException());
assertThatThrownBy(() -> simpleConfigurationProvider.allConfigurationAsProperties()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void allConfigurationAsPropertiesThrowsWhenMissingEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderGetPropertyTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class SimpleConfigurationProviderGetPropertyTest extends SimpleConfigurationProviderAbstractTest {
@Test
void allConfigurationAsPropertiesThrowsWhenUnableToFetchConfiguration() {
when(configurationSource.getConfiguration(anyEnvironment())).thenThrow(new IllegalStateException());
assertThatThrownBy(() -> simpleConfigurationProvider.allConfigurationAsProperties()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void allConfigurationAsPropertiesThrowsWhenMissingEnvironment() { | when(configurationSource.getConfiguration(anyEnvironment())).thenThrow(new MissingEnvironmentException("")); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/reload/strategy/ImmediateReloadStrategyTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
@ExtendWith(MockitoExtension.class)
class ImmediateReloadStrategyTest {
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/reload/strategy/ImmediateReloadStrategyTest.java
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
@ExtendWith(MockitoExtension.class)
class ImmediateReloadStrategyTest {
@Mock | private Reloadable resource; |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/inmemory/InMemoryConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.inmemory;
/**
* Simple in-memory {@link ConfigurationSource}.
*/
public class InMemoryConfigurationSource implements ConfigurationSource {
private final Properties properties;
/**
* Create in-memory configuration source with given {@code properties}.
*
* @param properties properties to seed source.
*/
public InMemoryConfigurationSource(Properties properties) {
this.properties = requireNonNull(properties);
}
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/inmemory/InMemoryConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.inmemory;
/**
* Simple in-memory {@link ConfigurationSource}.
*/
public class InMemoryConfigurationSource implements ConfigurationSource {
private final Properties properties;
/**
* Create in-memory configuration source with given {@code properties}.
*
* @param properties properties to seed source.
*/
public InMemoryConfigurationSource(Properties properties) {
this.properties = requireNonNull(properties);
}
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/FirstTokenBranchResolverTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
@ExtendWith(MockitoExtension.class)
class FirstTokenBranchResolverTest {
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-git/src/test/java/org/cfg4j/source/git/FirstTokenBranchResolverTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
@ExtendWith(MockitoExtension.class)
class FirstTokenBranchResolverTest {
@Mock | private Environment environment; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class FallbackConfigurationSourceTest {
private static final int NUMBER_OF_SOURCES = 5;
private static final int LAST_SOURCE_INDEX = NUMBER_OF_SOURCES - 1;
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class FallbackConfigurationSourceTest {
private static final int NUMBER_OF_SOURCES = 5;
private static final int LAST_SOURCE_INDEX = NUMBER_OF_SOURCES - 1;
| private ConfigurationSource[] underlyingSources; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class FallbackConfigurationSourceTest {
private static final int NUMBER_OF_SOURCES = 5;
private static final int LAST_SOURCE_INDEX = NUMBER_OF_SOURCES - 1;
private ConfigurationSource[] underlyingSources;
private FallbackConfigurationSource fallbackConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
}
fallbackConfigurationSource = new FallbackConfigurationSource(underlyingSources);
fallbackConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenAllSourcesThrowOnMissingEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class FallbackConfigurationSourceTest {
private static final int NUMBER_OF_SOURCES = 5;
private static final int LAST_SOURCE_INDEX = NUMBER_OF_SOURCES - 1;
private ConfigurationSource[] underlyingSources;
private FallbackConfigurationSource fallbackConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
}
fallbackConfigurationSource = new FallbackConfigurationSource(underlyingSources);
fallbackConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenAllSourcesThrowOnMissingEnvironment() { | makeAllSourcesThrow(new MissingEnvironmentException("")); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class FallbackConfigurationSourceTest {
private static final int NUMBER_OF_SOURCES = 5;
private static final int LAST_SOURCE_INDEX = NUMBER_OF_SOURCES - 1;
private ConfigurationSource[] underlyingSources;
private FallbackConfigurationSource fallbackConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
}
fallbackConfigurationSource = new FallbackConfigurationSource(underlyingSources);
fallbackConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenAllSourcesThrowOnMissingEnvironment() {
makeAllSourcesThrow(new MissingEnvironmentException(""));
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class FallbackConfigurationSourceTest {
private static final int NUMBER_OF_SOURCES = 5;
private static final int LAST_SOURCE_INDEX = NUMBER_OF_SOURCES - 1;
private ConfigurationSource[] underlyingSources;
private FallbackConfigurationSource fallbackConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
}
fallbackConfigurationSource = new FallbackConfigurationSource(underlyingSources);
fallbackConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenAllSourcesThrowOnMissingEnvironment() {
makeAllSourcesThrow(new MissingEnvironmentException(""));
| assertThatThrownBy(() -> fallbackConfigurationSource.getConfiguration(mock(Environment.class))).isExactlyInstanceOf(MissingEnvironmentException.class); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException; | when(underlyingSources[LAST_SOURCE_INDEX].getConfiguration(any(Environment.class))).thenReturn(getProps("prop1", "value1")[0]);
assertThat(fallbackConfigurationSource.getConfiguration(mock(Environment.class)))
.containsOnly(MapEntry.entry("prop1", "value1"));
}
@Test
void initInitializesAllSources() {
for (ConfigurationSource underlyingSource : underlyingSources) {
verify(underlyingSource, atLeastOnce()).init();
}
}
@Test
void initThrowsWhenAllSourcesThrow() {
makeAllSourcesThrow(new IllegalStateException());
assertThatThrownBy(() -> fallbackConfigurationSource.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initIgnoresIllegalStateExceptionsIfAtLeastOneSourceSucceeds() {
makeAllSourcesThrow(new IllegalStateException());
doNothing().when(underlyingSources[LAST_SOURCE_INDEX]).init();
fallbackConfigurationSource.init();
}
@Test
void initIgnoresSourceCommunicationExceptionsIfAtLeastOneSourceSucceeds() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/FallbackConfigurationSourceTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
when(underlyingSources[LAST_SOURCE_INDEX].getConfiguration(any(Environment.class))).thenReturn(getProps("prop1", "value1")[0]);
assertThat(fallbackConfigurationSource.getConfiguration(mock(Environment.class)))
.containsOnly(MapEntry.entry("prop1", "value1"));
}
@Test
void initInitializesAllSources() {
for (ConfigurationSource underlyingSource : underlyingSources) {
verify(underlyingSource, atLeastOnce()).init();
}
}
@Test
void initThrowsWhenAllSourcesThrow() {
makeAllSourcesThrow(new IllegalStateException());
assertThatThrownBy(() -> fallbackConfigurationSource.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initIgnoresIllegalStateExceptionsIfAtLeastOneSourceSucceeds() {
makeAllSourcesThrow(new IllegalStateException());
doNothing().when(underlyingSources[LAST_SOURCE_INDEX]).init();
fallbackConfigurationSource.init();
}
@Test
void initIgnoresSourceCommunicationExceptionsIfAtLeastOneSourceSucceeds() { | makeAllSourcesThrow(new SourceCommunicationException("", null)); |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/system/EnvironmentVariablesConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
/**
* {@link ConfigurationSource} providing all environment variables under the specified {@link Environment}
* namespace prefix.
*/
public class EnvironmentVariablesConfigurationSource implements ConfigurationSource {
private static final Logger LOG = LoggerFactory.getLogger(EnvironmentVariablesConfigurationSource.class);
private final static char ENV_DELIMITER = '_';
private final static char PROPERTIES_DELIMITER = '.';
private Map<String, String> environmentVariables = new HashMap<>();
private boolean initialized = false;
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/system/EnvironmentVariablesConfigurationSource.java
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
/**
* {@link ConfigurationSource} providing all environment variables under the specified {@link Environment}
* namespace prefix.
*/
public class EnvironmentVariablesConfigurationSource implements ConfigurationSource {
private static final Logger LOG = LoggerFactory.getLogger(EnvironmentVariablesConfigurationSource.class);
private final static char ENV_DELIMITER = '_';
private final static char PROPERTIES_DELIMITER = '.';
private Map<String, String> environmentVariables = new HashMap<>();
private boolean initialized = false;
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/reload/strategy/PeriodicalReloadStrategy.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
/**
* {@link ReloadStrategy} that reloads resources periodically. Supports multiple resources. It spawns a tread.
*/
public class PeriodicalReloadStrategy implements ReloadStrategy {
private static final Logger LOG = LoggerFactory.getLogger(PeriodicalReloadStrategy.class);
private final long duration;
private final TimeUnit timeUnit;
private final Timer timer; | // Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/strategy/PeriodicalReloadStrategy.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.reload.strategy;
/**
* {@link ReloadStrategy} that reloads resources periodically. Supports multiple resources. It spawns a tread.
*/
public class PeriodicalReloadStrategy implements ReloadStrategy {
private static final Logger LOG = LoggerFactory.getLogger(PeriodicalReloadStrategy.class);
private final long duration;
private final TimeUnit timeUnit;
private final Timer timer; | private final Map<Reloadable, TimerTask> tasks; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/ConfigurationProviderBuilderTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class ConfigurationProviderBuilderTest {
private ConfigurationProviderBuilder builder;
@BeforeEach
void setUp() {
builder = new ConfigurationProviderBuilder();
}
@Test
void initializesStrategyOnBuild() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/ConfigurationProviderBuilderTest.java
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class ConfigurationProviderBuilderTest {
private ConfigurationProviderBuilder builder;
@BeforeEach
void setUp() {
builder = new ConfigurationProviderBuilder();
}
@Test
void initializesStrategyOnBuild() { | ReloadStrategy reloadStrategy = mock(ReloadStrategy.class); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/ConfigurationProviderBuilderTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class ConfigurationProviderBuilderTest {
private ConfigurationProviderBuilder builder;
@BeforeEach
void setUp() {
builder = new ConfigurationProviderBuilder();
}
@Test
void initializesStrategyOnBuild() {
ReloadStrategy reloadStrategy = mock(ReloadStrategy.class);
builder
.withReloadStrategy(reloadStrategy) | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/ConfigurationProviderBuilderTest.java
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class ConfigurationProviderBuilderTest {
private ConfigurationProviderBuilder builder;
@BeforeEach
void setUp() {
builder = new ConfigurationProviderBuilder();
}
@Test
void initializesStrategyOnBuild() {
ReloadStrategy reloadStrategy = mock(ReloadStrategy.class);
builder
.withReloadStrategy(reloadStrategy) | .withEnvironment(new DefaultEnvironment()) |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/ConfigurationProviderBuilderTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
| import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class ConfigurationProviderBuilderTest {
private ConfigurationProviderBuilder builder;
@BeforeEach
void setUp() {
builder = new ConfigurationProviderBuilder();
}
@Test
void initializesStrategyOnBuild() {
ReloadStrategy reloadStrategy = mock(ReloadStrategy.class);
builder
.withReloadStrategy(reloadStrategy)
.withEnvironment(new DefaultEnvironment())
.build();
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/ReloadStrategy.java
// public interface ReloadStrategy {
//
// /**
// * Register a {@link Reloadable} resource with this strategy. It should take control of reloading the {@code resource}. Strategy should
// * invoke {@link Reloadable#reload()} method to reload the resource.
// *
// * @param resource resource to be registered
// */
// void register(Reloadable resource);
//
// /**
// * De-register {@link Reloadable} resource from this strategy. Call to this method indicates that the resource
// * should not be reloaded anymore by this strategy.
// *
// * @param resource resource to be deregistered
// */
// void deregister(Reloadable resource);
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/reload/Reloadable.java
// public interface Reloadable {
//
// /**
// * Request resource reload. Resource should be fully reloaded before this method returns.
// *
// * @throws IllegalStateException when unable to reload resource
// */
// void reload();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/ConfigurationProviderBuilderTest.java
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.reload.ReloadStrategy;
import org.cfg4j.source.reload.Reloadable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
class ConfigurationProviderBuilderTest {
private ConfigurationProviderBuilder builder;
@BeforeEach
void setUp() {
builder = new ConfigurationProviderBuilder();
}
@Test
void initializesStrategyOnBuild() {
ReloadStrategy reloadStrategy = mock(ReloadStrategy.class);
builder
.withReloadStrategy(reloadStrategy)
.withEnvironment(new DefaultEnvironment())
.build();
| verify(reloadStrategy, times(1)).register(any(Reloadable.class)); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/system/EnvironmentVariablesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class EnvironmentVariablesConfigurationSourceTest {
private EnvironmentVariablesConfigurationSource source;
@BeforeEach
void setUp() {
source = new EnvironmentVariablesConfigurationSource();
source.init();
}
@Test
void returnsPath() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/system/EnvironmentVariablesConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class EnvironmentVariablesConfigurationSourceTest {
private EnvironmentVariablesConfigurationSource source;
@BeforeEach
void setUp() {
source = new EnvironmentVariablesConfigurationSource();
source.init();
}
@Test
void returnsPath() { | assertThat(source.getConfiguration(new DefaultEnvironment())).containsKey("PATH"); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/system/EnvironmentVariablesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class EnvironmentVariablesConfigurationSourceTest {
private EnvironmentVariablesConfigurationSource source;
@BeforeEach
void setUp() {
source = new EnvironmentVariablesConfigurationSource();
source.init();
}
@Test
void returnsPath() {
assertThat(source.getConfiguration(new DefaultEnvironment())).containsKey("PATH");
}
@Test
void returnsPathForAnyEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/system/EnvironmentVariablesConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
class EnvironmentVariablesConfigurationSourceTest {
private EnvironmentVariablesConfigurationSource source;
@BeforeEach
void setUp() {
source = new EnvironmentVariablesConfigurationSource();
source.init();
}
@Test
void returnsPath() {
assertThat(source.getConfiguration(new DefaultEnvironment())).containsKey("PATH");
}
@Test
void returnsPathForAnyEnvironment() { | assertThat(source.getConfiguration(mock(Environment.class))).containsKey("PATH"); |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/metered/MeteredConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static java.util.Objects.requireNonNull;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
/**
* Decorator for {@link ConfigurationSource} that emits execution metrics. It emits the following metrics (each of those prefixed
* with a string passed at construction time):
* <ul>
* <li>source.getConfiguration</li>
* <li>source.init</li>
* </ul>
* Each of those metrics is of {@link Timer} type (i.e. includes execution time percentiles, execution count, etc.)
*/
public class MeteredConfigurationSource implements ConfigurationSource {
private final ConfigurationSource delegate;
private final Timer getConfigurationTimer;
private final Timer initTimer;
/**
* Create decorator for given {@code delegate} and using {@code metricRegistry} for constructing metrics. Each metric will
* be prefixed with {@code metricPrefix}.
*
* @param metricRegistry metric registry to hold execution metrics
* @param metricPrefix prefix for metric names (trailing dot will be added to it)
* @param delegate configuration provider to monitor
*/
public MeteredConfigurationSource(MetricRegistry metricRegistry, String metricPrefix, ConfigurationSource delegate) {
requireNonNull(metricRegistry);
requireNonNull(metricPrefix);
this.delegate = requireNonNull(delegate);
getConfigurationTimer = metricRegistry.timer(metricPrefix + "source.getConfiguration");
initTimer = metricRegistry.timer(metricPrefix + "source.init");
}
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/metered/MeteredConfigurationSource.java
import static java.util.Objects.requireNonNull;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
/**
* Decorator for {@link ConfigurationSource} that emits execution metrics. It emits the following metrics (each of those prefixed
* with a string passed at construction time):
* <ul>
* <li>source.getConfiguration</li>
* <li>source.init</li>
* </ul>
* Each of those metrics is of {@link Timer} type (i.e. includes execution time percentiles, execution count, etc.)
*/
public class MeteredConfigurationSource implements ConfigurationSource {
private final ConfigurationSource delegate;
private final Timer getConfigurationTimer;
private final Timer initTimer;
/**
* Create decorator for given {@code delegate} and using {@code metricRegistry} for constructing metrics. Each metric will
* be prefixed with {@code metricPrefix}.
*
* @param metricRegistry metric registry to hold execution metrics
* @param metricPrefix prefix for metric names (trailing dot will be added to it)
* @param delegate configuration provider to monitor
*/
public MeteredConfigurationSource(MetricRegistry metricRegistry, String metricPrefix, ConfigurationSource delegate) {
requireNonNull(metricRegistry);
requireNonNull(metricPrefix);
this.delegate = requireNonNull(delegate);
getConfigurationTimer = metricRegistry.timer(metricPrefix + "source.getConfiguration");
initTimer = metricRegistry.timer(metricPrefix + "source.init");
}
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo; | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo; | private ConfigFilesProvider configFilesProvider; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo;
private ConfigFilesProvider configFilesProvider;
private FilesConfigurationSource source; | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo;
private ConfigFilesProvider configFilesProvider;
private FilesConfigurationSource source; | private Environment environment; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo;
private ConfigFilesProvider configFilesProvider;
private FilesConfigurationSource source;
private Environment environment;
@BeforeEach
void setUp() throws Exception {
fileRepo = new TempConfigurationFileRepo("org.cfg4j-test-repo");
fileRepo.changeProperty(Paths.get("application.properties"), "some.setting", "masterValue");
fileRepo.changeProperty(Paths.get("otherConfig.properties"), "otherConfig.setting", "masterValue");
fileRepo.changeProperty(Paths.get("malformed.properties"), "otherConfig.setting", "\\uzzzzz");
fileRepo.changeProperty(Paths.get("otherApplicationConfigs/application.properties"), "some.setting", "otherAppSetting");
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo;
private ConfigFilesProvider configFilesProvider;
private FilesConfigurationSource source;
private Environment environment;
@BeforeEach
void setUp() throws Exception {
fileRepo = new TempConfigurationFileRepo("org.cfg4j-test-repo");
fileRepo.changeProperty(Paths.get("application.properties"), "some.setting", "masterValue");
fileRepo.changeProperty(Paths.get("otherConfig.properties"), "otherConfig.setting", "masterValue");
fileRepo.changeProperty(Paths.get("malformed.properties"), "otherConfig.setting", "\\uzzzzz");
fileRepo.changeProperty(Paths.get("otherApplicationConfigs/application.properties"), "some.setting", "otherAppSetting");
| environment = new ImmutableEnvironment(fileRepo.dirPath.toString()); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo;
private ConfigFilesProvider configFilesProvider;
private FilesConfigurationSource source;
private Environment environment;
@BeforeEach
void setUp() throws Exception {
fileRepo = new TempConfigurationFileRepo("org.cfg4j-test-repo");
fileRepo.changeProperty(Paths.get("application.properties"), "some.setting", "masterValue");
fileRepo.changeProperty(Paths.get("otherConfig.properties"), "otherConfig.setting", "masterValue");
fileRepo.changeProperty(Paths.get("malformed.properties"), "otherConfig.setting", "\\uzzzzz");
fileRepo.changeProperty(Paths.get("otherApplicationConfigs/application.properties"), "some.setting", "otherAppSetting");
environment = new ImmutableEnvironment(fileRepo.dirPath.toString());
source = new FilesConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
fileRepo.remove();
}
@Test
void getConfigurationReadsFromDefaultFile() {
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "masterValue"));
}
@Test
void getConfigurationReadsFromHomeForDefaultEnvironment() {
System.setProperty("user.home", fileRepo.dirPath.resolve("otherApplicationConfigs").toString()); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
class FilesConfigurationSourceTest {
private TempConfigurationFileRepo fileRepo;
private ConfigFilesProvider configFilesProvider;
private FilesConfigurationSource source;
private Environment environment;
@BeforeEach
void setUp() throws Exception {
fileRepo = new TempConfigurationFileRepo("org.cfg4j-test-repo");
fileRepo.changeProperty(Paths.get("application.properties"), "some.setting", "masterValue");
fileRepo.changeProperty(Paths.get("otherConfig.properties"), "otherConfig.setting", "masterValue");
fileRepo.changeProperty(Paths.get("malformed.properties"), "otherConfig.setting", "\\uzzzzz");
fileRepo.changeProperty(Paths.get("otherApplicationConfigs/application.properties"), "some.setting", "otherAppSetting");
environment = new ImmutableEnvironment(fileRepo.dirPath.toString());
source = new FilesConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
fileRepo.remove();
}
@Test
void getConfigurationReadsFromDefaultFile() {
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "masterValue"));
}
@Test
void getConfigurationReadsFromHomeForDefaultEnvironment() {
System.setProperty("user.home", fileRepo.dirPath.resolve("otherApplicationConfigs").toString()); | assertThat(source.getConfiguration(new DefaultEnvironment())).containsOnly(MapEntry.entry("some.setting", "otherAppSetting")); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
| import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays; | void getConfigurationReadsFromDefaultFile() {
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "masterValue"));
}
@Test
void getConfigurationReadsFromHomeForDefaultEnvironment() {
System.setProperty("user.home", fileRepo.dirPath.resolve("otherApplicationConfigs").toString());
assertThat(source.getConfiguration(new DefaultEnvironment())).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment(fileRepo.dirPath.resolve("otherApplicationConfigs").toString());
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationReadsFromGivenFiles() {
configFilesProvider = () -> Arrays.asList(
Paths.get("application.properties"),
Paths.get("otherConfig.properties")
);
source = new FilesConfigurationSource(configFilesProvider);
assertThat(source.getConfiguration(environment)).containsOnlyKeys("some.setting", "otherConfig.setting");
}
@Test
void getConfigurationThrowsOnMissingEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/filesprovider/ConfigFilesProvider.java
// public interface ConfigFilesProvider {
//
// /**
// * Provide a list of configuration files to use.
// * @return {@link Iterable} of configuration {@link File}s to use
// */
// Iterable<Path> getConfigFiles();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/files/FilesConfigurationSourceTest.java
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.Arrays;
void getConfigurationReadsFromDefaultFile() {
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "masterValue"));
}
@Test
void getConfigurationReadsFromHomeForDefaultEnvironment() {
System.setProperty("user.home", fileRepo.dirPath.resolve("otherApplicationConfigs").toString());
assertThat(source.getConfiguration(new DefaultEnvironment())).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment(fileRepo.dirPath.resolve("otherApplicationConfigs").toString());
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationReadsFromGivenFiles() {
configFilesProvider = () -> Arrays.asList(
Paths.get("application.properties"),
Paths.get("otherConfig.properties")
);
source = new FilesConfigurationSource(configFilesProvider);
assertThat(source.getConfiguration(environment)).containsOnlyKeys("some.setting", "otherConfig.setting");
}
@Test
void getConfigurationThrowsOnMissingEnvironment() { | assertThatThrownBy(() -> source.getConfiguration(new ImmutableEnvironment("awlerijawoetinawwerlkjn"))).isExactlyInstanceOf(MissingEnvironmentException.class); |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/provider/SimpleConfigurationProvider.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/validator/BindingValidator.java
// public class BindingValidator {
//
// private static final Logger LOG = LoggerFactory.getLogger(BindingValidator.class);
//
// /**
// * Validate if the {@code configurationBean} object was bound successfully
// *
// * @param configurationBean configurationBean to validate
// * @param type interface used to access {@code configurationBean}
// * @param <T> type of the validated bean
// * @throws IllegalStateException when unable to access one of the methods
// * @throws NoSuchElementException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link NoSuchElementException}
// * @throws IllegalArgumentException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link IllegalArgumentException}
// */
// public <T> void validate(T configurationBean, Class<T> type) {
// LOG.debug("Validating configuration bean of type " + type);
//
// for (Method declaredMethod : type.getDeclaredMethods()) {
// try {
// LOG.debug("Validating method: " + declaredMethod.getName());
//
// declaredMethod.invoke(configurationBean);
//
// } catch (InvocationTargetException e) {
//
// if (e.getCause() != null) {
// if (e.getCause() instanceof NoSuchElementException) {
// throw (NoSuchElementException) e.getCause();
// }
//
// if (e.getCause() instanceof IllegalArgumentException) {
// throw (IllegalArgumentException) e.getCause();
// }
// }
//
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
//
// } catch (IllegalAccessException e) {
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
// }
// }
// }
// }
| import static java.util.Objects.requireNonNull;
import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
/**
* Basic implementation of {@link ConfigurationProvider}. To construct this provider use {@link ConfigurationProviderBuilder}.
*/
class SimpleConfigurationProvider implements ConfigurationProvider {
private final ConfigurationSource configurationSource; | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/validator/BindingValidator.java
// public class BindingValidator {
//
// private static final Logger LOG = LoggerFactory.getLogger(BindingValidator.class);
//
// /**
// * Validate if the {@code configurationBean} object was bound successfully
// *
// * @param configurationBean configurationBean to validate
// * @param type interface used to access {@code configurationBean}
// * @param <T> type of the validated bean
// * @throws IllegalStateException when unable to access one of the methods
// * @throws NoSuchElementException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link NoSuchElementException}
// * @throws IllegalArgumentException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link IllegalArgumentException}
// */
// public <T> void validate(T configurationBean, Class<T> type) {
// LOG.debug("Validating configuration bean of type " + type);
//
// for (Method declaredMethod : type.getDeclaredMethods()) {
// try {
// LOG.debug("Validating method: " + declaredMethod.getName());
//
// declaredMethod.invoke(configurationBean);
//
// } catch (InvocationTargetException e) {
//
// if (e.getCause() != null) {
// if (e.getCause() instanceof NoSuchElementException) {
// throw (NoSuchElementException) e.getCause();
// }
//
// if (e.getCause() instanceof IllegalArgumentException) {
// throw (IllegalArgumentException) e.getCause();
// }
// }
//
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
//
// } catch (IllegalAccessException e) {
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
// }
// }
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/provider/SimpleConfigurationProvider.java
import static java.util.Objects.requireNonNull;
import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
/**
* Basic implementation of {@link ConfigurationProvider}. To construct this provider use {@link ConfigurationProviderBuilder}.
*/
class SimpleConfigurationProvider implements ConfigurationProvider {
private final ConfigurationSource configurationSource; | private final Environment environment; |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/provider/SimpleConfigurationProvider.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/validator/BindingValidator.java
// public class BindingValidator {
//
// private static final Logger LOG = LoggerFactory.getLogger(BindingValidator.class);
//
// /**
// * Validate if the {@code configurationBean} object was bound successfully
// *
// * @param configurationBean configurationBean to validate
// * @param type interface used to access {@code configurationBean}
// * @param <T> type of the validated bean
// * @throws IllegalStateException when unable to access one of the methods
// * @throws NoSuchElementException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link NoSuchElementException}
// * @throws IllegalArgumentException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link IllegalArgumentException}
// */
// public <T> void validate(T configurationBean, Class<T> type) {
// LOG.debug("Validating configuration bean of type " + type);
//
// for (Method declaredMethod : type.getDeclaredMethods()) {
// try {
// LOG.debug("Validating method: " + declaredMethod.getName());
//
// declaredMethod.invoke(configurationBean);
//
// } catch (InvocationTargetException e) {
//
// if (e.getCause() != null) {
// if (e.getCause() instanceof NoSuchElementException) {
// throw (NoSuchElementException) e.getCause();
// }
//
// if (e.getCause() instanceof IllegalArgumentException) {
// throw (IllegalArgumentException) e.getCause();
// }
// }
//
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
//
// } catch (IllegalAccessException e) {
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
// }
// }
// }
// }
| import static java.util.Objects.requireNonNull;
import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
/**
* Basic implementation of {@link ConfigurationProvider}. To construct this provider use {@link ConfigurationProviderBuilder}.
*/
class SimpleConfigurationProvider implements ConfigurationProvider {
private final ConfigurationSource configurationSource;
private final Environment environment;
/**
* {@link ConfigurationProvider} backed by provided {@link ConfigurationSource} and using {@code environment}
* to select environment. To construct this provider use {@link ConfigurationProviderBuilder}.
*
* @param configurationSource source for configuration
* @param environment {@link Environment} to use
*/
SimpleConfigurationProvider(ConfigurationSource configurationSource, Environment environment) {
this.configurationSource = requireNonNull(configurationSource);
this.environment = requireNonNull(environment);
}
@Override
public Properties allConfigurationAsProperties() {
try {
return configurationSource.getConfiguration(environment); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/validator/BindingValidator.java
// public class BindingValidator {
//
// private static final Logger LOG = LoggerFactory.getLogger(BindingValidator.class);
//
// /**
// * Validate if the {@code configurationBean} object was bound successfully
// *
// * @param configurationBean configurationBean to validate
// * @param type interface used to access {@code configurationBean}
// * @param <T> type of the validated bean
// * @throws IllegalStateException when unable to access one of the methods
// * @throws NoSuchElementException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link NoSuchElementException}
// * @throws IllegalArgumentException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link IllegalArgumentException}
// */
// public <T> void validate(T configurationBean, Class<T> type) {
// LOG.debug("Validating configuration bean of type " + type);
//
// for (Method declaredMethod : type.getDeclaredMethods()) {
// try {
// LOG.debug("Validating method: " + declaredMethod.getName());
//
// declaredMethod.invoke(configurationBean);
//
// } catch (InvocationTargetException e) {
//
// if (e.getCause() != null) {
// if (e.getCause() instanceof NoSuchElementException) {
// throw (NoSuchElementException) e.getCause();
// }
//
// if (e.getCause() instanceof IllegalArgumentException) {
// throw (IllegalArgumentException) e.getCause();
// }
// }
//
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
//
// } catch (IllegalAccessException e) {
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
// }
// }
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/provider/SimpleConfigurationProvider.java
import static java.util.Objects.requireNonNull;
import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
/**
* Basic implementation of {@link ConfigurationProvider}. To construct this provider use {@link ConfigurationProviderBuilder}.
*/
class SimpleConfigurationProvider implements ConfigurationProvider {
private final ConfigurationSource configurationSource;
private final Environment environment;
/**
* {@link ConfigurationProvider} backed by provided {@link ConfigurationSource} and using {@code environment}
* to select environment. To construct this provider use {@link ConfigurationProviderBuilder}.
*
* @param configurationSource source for configuration
* @param environment {@link Environment} to use
*/
SimpleConfigurationProvider(ConfigurationSource configurationSource, Environment environment) {
this.configurationSource = requireNonNull(configurationSource);
this.environment = requireNonNull(environment);
}
@Override
public Properties allConfigurationAsProperties() {
try {
return configurationSource.getConfiguration(environment); | } catch (IllegalStateException | MissingEnvironmentException e) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/provider/SimpleConfigurationProvider.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/validator/BindingValidator.java
// public class BindingValidator {
//
// private static final Logger LOG = LoggerFactory.getLogger(BindingValidator.class);
//
// /**
// * Validate if the {@code configurationBean} object was bound successfully
// *
// * @param configurationBean configurationBean to validate
// * @param type interface used to access {@code configurationBean}
// * @param <T> type of the validated bean
// * @throws IllegalStateException when unable to access one of the methods
// * @throws NoSuchElementException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link NoSuchElementException}
// * @throws IllegalArgumentException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link IllegalArgumentException}
// */
// public <T> void validate(T configurationBean, Class<T> type) {
// LOG.debug("Validating configuration bean of type " + type);
//
// for (Method declaredMethod : type.getDeclaredMethods()) {
// try {
// LOG.debug("Validating method: " + declaredMethod.getName());
//
// declaredMethod.invoke(configurationBean);
//
// } catch (InvocationTargetException e) {
//
// if (e.getCause() != null) {
// if (e.getCause() instanceof NoSuchElementException) {
// throw (NoSuchElementException) e.getCause();
// }
//
// if (e.getCause() instanceof IllegalArgumentException) {
// throw (IllegalArgumentException) e.getCause();
// }
// }
//
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
//
// } catch (IllegalAccessException e) {
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
// }
// }
// }
// }
| import static java.util.Objects.requireNonNull;
import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties; |
} catch (IllegalStateException e) {
throw new IllegalStateException("Couldn't fetch configuration from configuration source for key: " + key, e);
}
}
@Override
public <T> T bind(String prefix, Class<T> type) {
return bind(this, prefix, type);
}
/**
* Create an instance of a given {@code type} that will be bound to the {@code configurationProvider}. Each time configuration changes the
* bound object will be updated with the new values. Use {@code prefix} to specify the relative path to configuration
* values. Please note that each method of returned object can throw runtime exceptions. For details see javadoc for
* {@link BindInvocationHandler#invoke(Object, Method, Object[])}.
*
* @param <T> interface describing configuration object to bind
* @param prefix relative path to configuration values (e.g. "myContext" will map settings "myContext.someSetting",
* "myContext.someOtherSetting")
* @param type {@link Class} for {@code <T>}
* @return configuration object bound to this {@link ConfigurationProvider}
* @throws NoSuchElementException when the provided {@code key} doesn't have a corresponding config value
* @throws IllegalArgumentException when property can't be coverted to {@code type}
* @throws IllegalStateException when provider is unable to fetch configuration value for the given {@code key}
*/
<T> T bind(ConfigurationProvider configurationProvider, String prefix, Class<T> type) {
@SuppressWarnings("unchecked")
T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, new BindInvocationHandler(configurationProvider, prefix));
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/validator/BindingValidator.java
// public class BindingValidator {
//
// private static final Logger LOG = LoggerFactory.getLogger(BindingValidator.class);
//
// /**
// * Validate if the {@code configurationBean} object was bound successfully
// *
// * @param configurationBean configurationBean to validate
// * @param type interface used to access {@code configurationBean}
// * @param <T> type of the validated bean
// * @throws IllegalStateException when unable to access one of the methods
// * @throws NoSuchElementException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link NoSuchElementException}
// * @throws IllegalArgumentException when an invocation of one of the {@code configurationBean} methods failed with an
// * underlying exception of type {@link IllegalArgumentException}
// */
// public <T> void validate(T configurationBean, Class<T> type) {
// LOG.debug("Validating configuration bean of type " + type);
//
// for (Method declaredMethod : type.getDeclaredMethods()) {
// try {
// LOG.debug("Validating method: " + declaredMethod.getName());
//
// declaredMethod.invoke(configurationBean);
//
// } catch (InvocationTargetException e) {
//
// if (e.getCause() != null) {
// if (e.getCause() instanceof NoSuchElementException) {
// throw (NoSuchElementException) e.getCause();
// }
//
// if (e.getCause() instanceof IllegalArgumentException) {
// throw (IllegalArgumentException) e.getCause();
// }
// }
//
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
//
// } catch (IllegalAccessException e) {
// throw new IllegalStateException("Can't bind method " + declaredMethod.getName(), e);
// }
// }
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/provider/SimpleConfigurationProvider.java
import static java.util.Objects.requireNonNull;
import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties;
} catch (IllegalStateException e) {
throw new IllegalStateException("Couldn't fetch configuration from configuration source for key: " + key, e);
}
}
@Override
public <T> T bind(String prefix, Class<T> type) {
return bind(this, prefix, type);
}
/**
* Create an instance of a given {@code type} that will be bound to the {@code configurationProvider}. Each time configuration changes the
* bound object will be updated with the new values. Use {@code prefix} to specify the relative path to configuration
* values. Please note that each method of returned object can throw runtime exceptions. For details see javadoc for
* {@link BindInvocationHandler#invoke(Object, Method, Object[])}.
*
* @param <T> interface describing configuration object to bind
* @param prefix relative path to configuration values (e.g. "myContext" will map settings "myContext.someSetting",
* "myContext.someOtherSetting")
* @param type {@link Class} for {@code <T>}
* @return configuration object bound to this {@link ConfigurationProvider}
* @throws NoSuchElementException when the provided {@code key} doesn't have a corresponding config value
* @throws IllegalArgumentException when property can't be coverted to {@code type}
* @throws IllegalStateException when provider is unable to fetch configuration value for the given {@code key}
*/
<T> T bind(ConfigurationProvider configurationProvider, String prefix, Class<T> type) {
@SuppressWarnings("unchecked")
T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, new BindInvocationHandler(configurationProvider, prefix));
| new BindingValidator().validate(proxy, type); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/files/TempConfigurationFileRepo.java | // Path: cfg4j-core/src/main/java/org/cfg4j/utils/FileUtils.java
// public class FileUtils {
//
// /**
// * Delete directory or file.
// *
// * @param directory directory to delete
// * @throws IOException when directory can't be deleted
// */
// public void deleteDir(Path directory) throws IOException {
// Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// Files.delete(file);
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult postVisitDirectory(Path dir, IOException exception) throws IOException {
// Files.delete(dir);
// return FileVisitResult.CONTINUE;
// }
// });
// }
// }
| import org.cfg4j.utils.FileUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
/**
* Temporary local file repository that contains configuration files.
*/
public class TempConfigurationFileRepo {
public Path dirPath;
/**
* Create temporary, local file repository. When you're done using it remove it by invoking {@link #remove()}
* method.
*
* @throws IOException when unable to create local directories
*/
public TempConfigurationFileRepo(String dirName) throws IOException {
dirPath = Files.createTempDirectory(dirName);
}
/**
* Change the {@code key} property to {@code value} and store it in a {@code propFilePath} properties file
*
* @param propFilePath relative path to the properties file in this repository
* @param key property key
* @param value property value
* @throws IOException when unable to modify properties file
*/
public void changeProperty(Path propFilePath, String key, String value) throws IOException {
Files.createDirectories(dirPath.resolve(propFilePath).getParent());
writePropertyToFile(propFilePath, key, value);
}
/**
* Delete file from this repository.
*
* @param filePath relative file path to delete
*/
public void deleteFile(Path filePath) throws IOException { | // Path: cfg4j-core/src/main/java/org/cfg4j/utils/FileUtils.java
// public class FileUtils {
//
// /**
// * Delete directory or file.
// *
// * @param directory directory to delete
// * @throws IOException when directory can't be deleted
// */
// public void deleteDir(Path directory) throws IOException {
// Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// Files.delete(file);
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult postVisitDirectory(Path dir, IOException exception) throws IOException {
// Files.delete(dir);
// return FileVisitResult.CONTINUE;
// }
// });
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/files/TempConfigurationFileRepo.java
import org.cfg4j.utils.FileUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.files;
/**
* Temporary local file repository that contains configuration files.
*/
public class TempConfigurationFileRepo {
public Path dirPath;
/**
* Create temporary, local file repository. When you're done using it remove it by invoking {@link #remove()}
* method.
*
* @throws IOException when unable to create local directories
*/
public TempConfigurationFileRepo(String dirName) throws IOException {
dirPath = Files.createTempDirectory(dirName);
}
/**
* Change the {@code key} property to {@code value} and store it in a {@code propFilePath} properties file
*
* @param propFilePath relative path to the properties file in this repository
* @param key property key
* @param value property value
* @throws IOException when unable to modify properties file
*/
public void changeProperty(Path propFilePath, String key, String value) throws IOException {
Files.createDirectories(dirPath.resolve(propFilePath).getParent());
writePropertyToFile(propFilePath, key, value);
}
/**
* Delete file from this repository.
*
* @param filePath relative file path to delete
*/
public void deleteFile(Path filePath) throws IOException { | new FileUtils().deleteDir(dirPath.resolve(filePath)); |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/system/SystemPropertiesConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
/**
* {@link ConfigurationSource} providing all system properties.
*/
public class SystemPropertiesConfigurationSource implements ConfigurationSource {
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/system/SystemPropertiesConfigurationSource.java
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.system;
/**
* {@link ConfigurationSource} providing all system properties.
*/
public class SystemPropertiesConfigurationSource implements ConfigurationSource {
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/compose/MergeConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
/**
* Merges multiple {@link ConfigurationSource}s. In case of key collision last-match wins merge strategy is used.
*/
public class MergeConfigurationSource implements ConfigurationSource {
private final ConfigurationSource[] sources;
/**
* Create a merge of provided {@link ConfigurationSource}s
*
* @param sources configuration sources to merge
*/
public MergeConfigurationSource(ConfigurationSource... sources) {
this.sources = requireNonNull(sources);
for (ConfigurationSource source : sources) {
requireNonNull(source);
}
}
/**
* Get configuration set for a given {@code environment} from this source in a form of {@link Properties}. The configuration
* set is a result of a merge of provided {@link ConfigurationSource} configurations. In case of key collision
* last-match wins merge strategy is used.
*
* @param environment environment to use
* @return configuration set for {@code environment}
* @throws MissingEnvironmentException when requested environment couldn't be found
* @throws IllegalStateException when unable to fetch configuration from one of the underlying sources
*/
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/compose/MergeConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
/**
* Merges multiple {@link ConfigurationSource}s. In case of key collision last-match wins merge strategy is used.
*/
public class MergeConfigurationSource implements ConfigurationSource {
private final ConfigurationSource[] sources;
/**
* Create a merge of provided {@link ConfigurationSource}s
*
* @param sources configuration sources to merge
*/
public MergeConfigurationSource(ConfigurationSource... sources) {
this.sources = requireNonNull(sources);
for (ConfigurationSource source : sources) {
requireNonNull(source);
}
}
/**
* Get configuration set for a given {@code environment} from this source in a form of {@link Properties}. The configuration
* set is a result of a merge of provided {@link ConfigurationSource} configurations. In case of key collision
* last-match wins merge strategy is used.
*
* @param environment environment to use
* @return configuration set for {@code environment}
* @throws MissingEnvironmentException when requested environment couldn't be found
* @throws IllegalStateException when unable to fetch configuration from one of the underlying sources
*/
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/empty/EmptyConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.empty;
/**
* Empty {@link ConfigurationSource}
*/
public class EmptyConfigurationSource implements ConfigurationSource {
private static final Properties properties = new Properties();
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/empty/EmptyConfigurationSource.java
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.empty;
/**
* Empty {@link ConfigurationSource}
*/
public class EmptyConfigurationSource implements ConfigurationSource {
private static final Properties properties = new Properties();
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderAbstractTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.mockito.ArgumentMatchers.any;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
@ExtendWith(MockitoExtension.class)
abstract class SimpleConfigurationProviderAbstractTest {
SimpleConfigurationProvider simpleConfigurationProvider;
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderAbstractTest.java
import static org.mockito.ArgumentMatchers.any;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
@ExtendWith(MockitoExtension.class)
abstract class SimpleConfigurationProviderAbstractTest {
SimpleConfigurationProvider simpleConfigurationProvider;
@Mock | protected ConfigurationSource configurationSource; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderAbstractTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
| import static org.mockito.ArgumentMatchers.any;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
@ExtendWith(MockitoExtension.class)
abstract class SimpleConfigurationProviderAbstractTest {
SimpleConfigurationProvider simpleConfigurationProvider;
@Mock
protected ConfigurationSource configurationSource;
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/provider/SimpleConfigurationProviderAbstractTest.java
import static org.mockito.ArgumentMatchers.any;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.provider;
@ExtendWith(MockitoExtension.class)
abstract class SimpleConfigurationProviderAbstractTest {
SimpleConfigurationProvider simpleConfigurationProvider;
@Mock
protected ConfigurationSource configurationSource;
@Mock | protected Environment environment; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/MergeConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.mockito.ArgumentMatchers;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class MergeConfigurationSourceTest {
private ConfigurationSource[] underlyingSources;
private MergeConfigurationSource mergeConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/MergeConfigurationSourceTest.java
import org.mockito.ArgumentMatchers;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class MergeConfigurationSourceTest {
private ConfigurationSource[] underlyingSources;
private MergeConfigurationSource mergeConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class); | when(underlyingSources[i].getConfiguration(any(Environment.class))).thenReturn(new Properties()); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/MergeConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.mockito.ArgumentMatchers;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class MergeConfigurationSourceTest {
private ConfigurationSource[] underlyingSources;
private MergeConfigurationSource mergeConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
when(underlyingSources[i].getConfiguration(any(Environment.class))).thenReturn(new Properties());
}
mergeConfigurationSource = new MergeConfigurationSource(underlyingSources);
mergeConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenOneOfSourcesThrowsOnMissingEnvironment() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/MergeConfigurationSourceTest.java
import org.mockito.ArgumentMatchers;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class MergeConfigurationSourceTest {
private ConfigurationSource[] underlyingSources;
private MergeConfigurationSource mergeConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
when(underlyingSources[i].getConfiguration(any(Environment.class))).thenReturn(new Properties());
}
mergeConfigurationSource = new MergeConfigurationSource(underlyingSources);
mergeConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenOneOfSourcesThrowsOnMissingEnvironment() { | when(underlyingSources[1].getConfiguration(ArgumentMatchers.any())).thenThrow(new MissingEnvironmentException("")); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/compose/MergeConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import org.mockito.ArgumentMatchers;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class MergeConfigurationSourceTest {
private ConfigurationSource[] underlyingSources;
private MergeConfigurationSource mergeConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
when(underlyingSources[i].getConfiguration(any(Environment.class))).thenReturn(new Properties());
}
mergeConfigurationSource = new MergeConfigurationSource(underlyingSources);
mergeConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenOneOfSourcesThrowsOnMissingEnvironment() {
when(underlyingSources[1].getConfiguration(ArgumentMatchers.any())).thenThrow(new MissingEnvironmentException(""));
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/ImmutableEnvironment.java
// public class ImmutableEnvironment implements Environment {
//
// private final String envName;
//
// /**
// * Construct environment named {@code envName}. This name never changes.
// *
// * @param envName environment name to use
// */
// public ImmutableEnvironment(String envName) {
// this.envName = requireNonNull(envName);
// }
//
// @Override
// public String getName() {
// return envName;
// }
//
// @Override
// public String toString() {
// return "ImmutableEnvironment{" +
// "envName='" + envName + '\'' +
// '}';
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/compose/MergeConfigurationSourceTest.java
import org.mockito.ArgumentMatchers;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
class MergeConfigurationSourceTest {
private ConfigurationSource[] underlyingSources;
private MergeConfigurationSource mergeConfigurationSource;
@BeforeEach
void setUp() {
underlyingSources = new ConfigurationSource[5];
for (int i = 0; i < underlyingSources.length; i++) {
underlyingSources[i] = mock(ConfigurationSource.class);
when(underlyingSources[i].getConfiguration(any(Environment.class))).thenReturn(new Properties());
}
mergeConfigurationSource = new MergeConfigurationSource(underlyingSources);
mergeConfigurationSource.init();
}
@Test
void getConfigurationThrowsWhenOneOfSourcesThrowsOnMissingEnvironment() {
when(underlyingSources[1].getConfiguration(ArgumentMatchers.any())).thenThrow(new MissingEnvironmentException(""));
| assertThatThrownBy(() -> mergeConfigurationSource.getConfiguration(new ImmutableEnvironment("test"))).isExactlyInstanceOf(MissingEnvironmentException.class); |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/compose/FallbackConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
/**
* Combines multiple {@link ConfigurationSource}s in a fallback chain. When one of the sources is not available
* another one is used for providing configuration.
*/
public class FallbackConfigurationSource implements ConfigurationSource {
private final ConfigurationSource[] sources;
/**
* Create a fallback chain of {@link ConfigurationSource}s
*
* @param sources configuration sources to use
*/
public FallbackConfigurationSource(ConfigurationSource... sources) {
this.sources = requireNonNull(sources);
for (ConfigurationSource source : sources) {
requireNonNull(source);
}
}
/**
* Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
* The configuration set is a result of the first {@link ConfigurationSource#getConfiguration(Environment)}
* call to underlying sources that succeeds. Sources are called in a provided order.
*
* @param environment environment to use
* @return configuration set for {@code environment} from the first source that works
* @throws MissingEnvironmentException when requested environment couldn't be found in any of the underlying source
* @throws IllegalStateException when unable to fetch configuration from any of the underlying sources
*/
@Override | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/compose/FallbackConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
/**
* Combines multiple {@link ConfigurationSource}s in a fallback chain. When one of the sources is not available
* another one is used for providing configuration.
*/
public class FallbackConfigurationSource implements ConfigurationSource {
private final ConfigurationSource[] sources;
/**
* Create a fallback chain of {@link ConfigurationSource}s
*
* @param sources configuration sources to use
*/
public FallbackConfigurationSource(ConfigurationSource... sources) {
this.sources = requireNonNull(sources);
for (ConfigurationSource source : sources) {
requireNonNull(source);
}
}
/**
* Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
* The configuration set is a result of the first {@link ConfigurationSource#getConfiguration(Environment)}
* call to underlying sources that succeeds. Sources are called in a provided order.
*
* @param environment environment to use
* @return configuration set for {@code environment} from the first source that works
* @throws MissingEnvironmentException when requested environment couldn't be found in any of the underlying source
* @throws IllegalStateException when unable to fetch configuration from any of the underlying sources
*/
@Override | public Properties getConfiguration(Environment environment) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/compose/FallbackConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
/**
* Combines multiple {@link ConfigurationSource}s in a fallback chain. When one of the sources is not available
* another one is used for providing configuration.
*/
public class FallbackConfigurationSource implements ConfigurationSource {
private final ConfigurationSource[] sources;
/**
* Create a fallback chain of {@link ConfigurationSource}s
*
* @param sources configuration sources to use
*/
public FallbackConfigurationSource(ConfigurationSource... sources) {
this.sources = requireNonNull(sources);
for (ConfigurationSource source : sources) {
requireNonNull(source);
}
}
/**
* Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
* The configuration set is a result of the first {@link ConfigurationSource#getConfiguration(Environment)}
* call to underlying sources that succeeds. Sources are called in a provided order.
*
* @param environment environment to use
* @return configuration set for {@code environment} from the first source that works
* @throws MissingEnvironmentException when requested environment couldn't be found in any of the underlying source
* @throws IllegalStateException when unable to fetch configuration from any of the underlying sources
*/
@Override
public Properties getConfiguration(Environment environment) {
boolean allMissEnvironment = true;
for (ConfigurationSource source : sources) {
try {
return source.getConfiguration(environment); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/compose/FallbackConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.compose;
/**
* Combines multiple {@link ConfigurationSource}s in a fallback chain. When one of the sources is not available
* another one is used for providing configuration.
*/
public class FallbackConfigurationSource implements ConfigurationSource {
private final ConfigurationSource[] sources;
/**
* Create a fallback chain of {@link ConfigurationSource}s
*
* @param sources configuration sources to use
*/
public FallbackConfigurationSource(ConfigurationSource... sources) {
this.sources = requireNonNull(sources);
for (ConfigurationSource source : sources) {
requireNonNull(source);
}
}
/**
* Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
* The configuration set is a result of the first {@link ConfigurationSource#getConfiguration(Environment)}
* call to underlying sources that succeeds. Sources are called in a provided order.
*
* @param environment environment to use
* @return configuration set for {@code environment} from the first source that works
* @throws MissingEnvironmentException when requested environment couldn't be found in any of the underlying source
* @throws IllegalStateException when unable to fetch configuration from any of the underlying sources
*/
@Override
public Properties getConfiguration(Environment environment) {
boolean allMissEnvironment = true;
for (ConfigurationSource source : sources) {
try {
return source.getConfiguration(environment); | } catch (MissingEnvironmentException e) { |
cfg4j/cfg4j | cfg4j-core/src/main/java/org/cfg4j/source/compose/FallbackConfigurationSource.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties; | @Override
public Properties getConfiguration(Environment environment) {
boolean allMissEnvironment = true;
for (ConfigurationSource source : sources) {
try {
return source.getConfiguration(environment);
} catch (MissingEnvironmentException e) {
// NOP
} catch (IllegalStateException e) {
allMissEnvironment = false;
}
}
if (allMissEnvironment) {
throw new MissingEnvironmentException(environment.getName());
}
throw new IllegalStateException();
}
@Override
public void init() {
boolean atLeastOneSuccess = false;
for (ConfigurationSource source : sources) {
try {
source.init();
atLeastOneSuccess = true; | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/main/java/org/cfg4j/source/compose/FallbackConfigurationSource.java
import static java.util.Objects.requireNonNull;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import java.util.Arrays;
import java.util.Properties;
@Override
public Properties getConfiguration(Environment environment) {
boolean allMissEnvironment = true;
for (ConfigurationSource source : sources) {
try {
return source.getConfiguration(environment);
} catch (MissingEnvironmentException e) {
// NOP
} catch (IllegalStateException e) {
allMissEnvironment = false;
}
}
if (allMissEnvironment) {
throw new MissingEnvironmentException(environment.getName());
}
throw new IllegalStateException();
}
@Override
public void init() {
boolean atLeastOneSuccess = false;
for (ConfigurationSource source : sources) {
try {
source.init();
atLeastOneSuccess = true; | } catch (IllegalStateException | SourceCommunicationException e) { |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock | private ConfigurationSource delegate; |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock
private ConfigurationSource delegate;
@Mock
private MetricRegistry metricRegistry;
private MeteredConfigurationSource source;
@BeforeEach
void setUp() {
Timer timer = mock(Timer.class);
when(timer.time()).thenReturn(mock(Timer.Context.class));
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
source.init();
}
@Test
void getConfigurationCallsDelegate() {
Properties properties = new Properties(); | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock
private ConfigurationSource delegate;
@Mock
private MetricRegistry metricRegistry;
private MeteredConfigurationSource source;
@BeforeEach
void setUp() {
Timer timer = mock(Timer.class);
when(timer.time()).thenReturn(mock(Timer.Context.class));
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
source.init();
}
@Test
void getConfigurationCallsDelegate() {
Properties properties = new Properties(); | when(delegate.getConfiguration(any(Environment.class))).thenReturn(properties); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock
private ConfigurationSource delegate;
@Mock
private MetricRegistry metricRegistry;
private MeteredConfigurationSource source;
@BeforeEach
void setUp() {
Timer timer = mock(Timer.class);
when(timer.time()).thenReturn(mock(Timer.Context.class));
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
source.init();
}
@Test
void getConfigurationCallsDelegate() {
Properties properties = new Properties();
when(delegate.getConfiguration(any(Environment.class))).thenReturn(properties);
| // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock
private ConfigurationSource delegate;
@Mock
private MetricRegistry metricRegistry;
private MeteredConfigurationSource source;
@BeforeEach
void setUp() {
Timer timer = mock(Timer.class);
when(timer.time()).thenReturn(mock(Timer.Context.class));
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
source.init();
}
@Test
void getConfigurationCallsDelegate() {
Properties properties = new Properties();
when(delegate.getConfiguration(any(Environment.class))).thenReturn(properties);
| assertThat(source.getConfiguration(new DefaultEnvironment())).isEqualTo(properties); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock
private ConfigurationSource delegate;
@Mock
private MetricRegistry metricRegistry;
private MeteredConfigurationSource source;
@BeforeEach
void setUp() {
Timer timer = mock(Timer.class);
when(timer.time()).thenReturn(mock(Timer.Context.class));
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
source.init();
}
@Test
void getConfigurationCallsDelegate() {
Properties properties = new Properties();
when(delegate.getConfiguration(any(Environment.class))).thenReturn(properties);
assertThat(source.getConfiguration(new DefaultEnvironment())).isEqualTo(properties);
}
@Test
void getConfigurationPropagatesMissingEnvironmentExceptions() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
/*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.metered;
@ExtendWith(MockitoExtension.class)
class MeteredConfigurationSourceTest {
@Mock
private ConfigurationSource delegate;
@Mock
private MetricRegistry metricRegistry;
private MeteredConfigurationSource source;
@BeforeEach
void setUp() {
Timer timer = mock(Timer.class);
when(timer.time()).thenReturn(mock(Timer.Context.class));
when(metricRegistry.timer(anyString())).thenReturn(timer);
source = new MeteredConfigurationSource(metricRegistry, "configSource", delegate);
source.init();
}
@Test
void getConfigurationCallsDelegate() {
Properties properties = new Properties();
when(delegate.getConfiguration(any(Environment.class))).thenReturn(properties);
assertThat(source.getConfiguration(new DefaultEnvironment())).isEqualTo(properties);
}
@Test
void getConfigurationPropagatesMissingEnvironmentExceptions() { | when(delegate.getConfiguration(any(Environment.class))).thenThrow(new MissingEnvironmentException("")); |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties; | }
@Test
void getConfigurationPropagatesMissingEnvironmentExceptions() {
when(delegate.getConfiguration(any(Environment.class))).thenThrow(new MissingEnvironmentException(""));
assertThatThrownBy(() -> source.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationPropagatesIllegalStateExceptions() {
when(delegate.getConfiguration(any(Environment.class))).thenThrow(new IllegalStateException(""));
assertThatThrownBy(() -> source.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initCallsDelegate() {
verify(delegate, times(1)).init();
}
@Test
void initPropagatesIllegalStateExceptions() {
doThrow(new IllegalStateException("")).when(delegate).init();
assertThatThrownBy(() -> delegate.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initPropagatesSourceCommunicationExceptions() { | // Path: cfg4j-core/src/main/java/org/cfg4j/source/ConfigurationSource.java
// public interface ConfigurationSource {
//
// /**
// * Get configuration set for a given {@code environment} from this source in a form of {@link Properties}.
// * Provided {@link Environment} will be used to determine which environment to use.
// *
// * @param environment environment to use
// * @return configuration set for {@code environment}
// * @throws MissingEnvironmentException when requested environment couldn't be found
// * @throws IllegalStateException when unable to fetch configuration
// */
// Properties getConfiguration(Environment environment);
//
// /**
// * Initialize this source. This method has to be called before any other method of this instance.
// *
// * @throws IllegalStateException when source was improperly configured
// * @throws SourceCommunicationException when unable to communicate with source
// */
// void init();
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/SourceCommunicationException.java
// public class SourceCommunicationException extends RuntimeException {
//
// /**
// * Indicates problem when communicating with {@link ConfigurationSource}.
// *
// * @param msg the detail message
// * @param e the cause
// */
// public SourceCommunicationException(String msg, Exception e) {
// super("Unable to communicate with configuration source: " + msg, e);
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/DefaultEnvironment.java
// public class DefaultEnvironment extends ImmutableEnvironment {
// /**
// * Constructs environment named "" (empty string).
// */
// public DefaultEnvironment() {
// super("");
// }
//
// @Override
// public String toString() {
// return "DefaultEnvironment{}";
// }
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/Environment.java
// public interface Environment {
//
// /**
// * Name of the environment. Should not be null.
// *
// * @return environment name. Not null.
// */
// String getName();
//
// }
//
// Path: cfg4j-core/src/main/java/org/cfg4j/source/context/environment/MissingEnvironmentException.java
// public class MissingEnvironmentException extends RuntimeException {
//
// private static final String MISSING_ENV_MSG = "Missing environment: ";
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// */
// public MissingEnvironmentException(String envName) {
// super(MISSING_ENV_MSG + envName);
// }
//
// /**
// * Environment named {@code envName} is missing.
// *
// * @param envName environment name
// * @param cause root cause
// */
// public MissingEnvironmentException(String envName, Throwable cause) {
// super(MISSING_ENV_MSG + envName, cause);
// }
// }
// Path: cfg4j-core/src/test/java/org/cfg4j/source/metered/MeteredConfigurationSourceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.SourceCommunicationException;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Properties;
}
@Test
void getConfigurationPropagatesMissingEnvironmentExceptions() {
when(delegate.getConfiguration(any(Environment.class))).thenThrow(new MissingEnvironmentException(""));
assertThatThrownBy(() -> source.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationPropagatesIllegalStateExceptions() {
when(delegate.getConfiguration(any(Environment.class))).thenThrow(new IllegalStateException(""));
assertThatThrownBy(() -> source.getConfiguration(new DefaultEnvironment())).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initCallsDelegate() {
verify(delegate, times(1)).init();
}
@Test
void initPropagatesIllegalStateExceptions() {
doThrow(new IllegalStateException("")).when(delegate).init();
assertThatThrownBy(() -> delegate.init()).isExactlyInstanceOf(IllegalStateException.class);
}
@Test
void initPropagatesSourceCommunicationExceptions() { | doThrow(new SourceCommunicationException("", null)).when(delegate).init(); |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/services/CipService.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/CipResponseException.java
// public class CipResponseException extends Exception {
//
// private final int generalStatus;
// private final int[] additionalStatus;
//
// public CipResponseException(int generalStatus, int[] additionalStatus) {
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
//
// sb.append(String.format("status=0x%02X", generalStatus));
//
// CipStatusCodes.getName(generalStatus).ifPresent(name -> sb.append(" [").append(name).append("] "));
//
// List<String> as = Arrays.stream(additionalStatus)
// .mapToObj(a -> String.format("0x%04X", a))
// .collect(Collectors.toList());
//
// String additional = "[" + String.join(",", as) + "]";
//
// sb.append(", additional=").append(additional);
//
// return sb.toString();
// }
//
// /**
// * If {@code ex} is a {@link CipResponseException}, or if a {@link CipResponseException} can be found by walking
// * the exception cause chain, return it.
// *
// * @param ex the {@link Throwable} to extract from.
// * @return a {@link CipResponseException} if one was present in the exception chain.
// */
// public static Optional<CipResponseException> extract(Throwable ex) {
// if (ex instanceof CipResponseException) {
// return Optional.of((CipResponseException) ex);
// } else {
// Throwable cause = ex.getCause();
// return cause != null ?
// extract(cause) : Optional.empty();
// }
// }
//
// }
| import com.digitalpetri.enip.cip.CipResponseException;
import io.netty.buffer.ByteBuf; | package com.digitalpetri.enip.cip.services;
public interface CipService<T> {
void encodeRequest(ByteBuf buffer);
| // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/CipResponseException.java
// public class CipResponseException extends Exception {
//
// private final int generalStatus;
// private final int[] additionalStatus;
//
// public CipResponseException(int generalStatus, int[] additionalStatus) {
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
//
// sb.append(String.format("status=0x%02X", generalStatus));
//
// CipStatusCodes.getName(generalStatus).ifPresent(name -> sb.append(" [").append(name).append("] "));
//
// List<String> as = Arrays.stream(additionalStatus)
// .mapToObj(a -> String.format("0x%04X", a))
// .collect(Collectors.toList());
//
// String additional = "[" + String.join(",", as) + "]";
//
// sb.append(", additional=").append(additional);
//
// return sb.toString();
// }
//
// /**
// * If {@code ex} is a {@link CipResponseException}, or if a {@link CipResponseException} can be found by walking
// * the exception cause chain, return it.
// *
// * @param ex the {@link Throwable} to extract from.
// * @return a {@link CipResponseException} if one was present in the exception chain.
// */
// public static Optional<CipResponseException> extract(Throwable ex) {
// if (ex instanceof CipResponseException) {
// return Optional.of((CipResponseException) ex);
// } else {
// Throwable cause = ex.getCause();
// return cause != null ?
// extract(cause) : Optional.empty();
// }
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/services/CipService.java
import com.digitalpetri.enip.cip.CipResponseException;
import io.netty.buffer.ByteBuf;
package com.digitalpetri.enip.cip.services;
public interface CipService<T> {
void encodeRequest(ByteBuf buffer);
| T decodeResponse(ByteBuf buffer) throws CipResponseException, PartialResponseException; |
digitalpetri/ethernet-ip | enip-core/src/main/java/com/digitalpetri/enip/commands/SendUnitData.java | // Path: enip-core/src/main/java/com/digitalpetri/enip/cpf/CpfPacket.java
// public final class CpfPacket {
//
// private final CpfItem[] items;
//
// public CpfPacket(CpfItem... items) {
// this.items = items;
// }
//
// public CpfItem[] getItems() {
// return items;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CpfPacket cpfPacket = (CpfPacket) o;
//
// return Arrays.equals(items, cpfPacket.items);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(items);
// }
//
// public static ByteBuf encode(CpfPacket packet, ByteBuf buffer) {
// buffer.writeShort(packet.getItems().length);
//
// for (CpfItem item : packet.getItems()) {
// CpfItem.encode(item, buffer);
// }
//
// return buffer;
// }
//
// public static CpfPacket decode(ByteBuf buffer) {
// int itemCount = buffer.readUnsignedShort();
// CpfItem[] items = new CpfItem[itemCount];
//
// for (int i = 0; i < itemCount; i++) {
// items[i] = CpfItem.decode(buffer);
// }
//
// return new CpfPacket(items);
// }
// }
| import com.digitalpetri.enip.cpf.CpfPacket;
import io.netty.buffer.ByteBuf; | package com.digitalpetri.enip.commands;
public final class SendUnitData extends Command {
public static final long DEFAULT_INTERFACE_HANDLE = 0;
public static final int DEFAULT_TIMEOUT = 0;
private final long interfaceHandle;
private final int timeout; | // Path: enip-core/src/main/java/com/digitalpetri/enip/cpf/CpfPacket.java
// public final class CpfPacket {
//
// private final CpfItem[] items;
//
// public CpfPacket(CpfItem... items) {
// this.items = items;
// }
//
// public CpfItem[] getItems() {
// return items;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CpfPacket cpfPacket = (CpfPacket) o;
//
// return Arrays.equals(items, cpfPacket.items);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(items);
// }
//
// public static ByteBuf encode(CpfPacket packet, ByteBuf buffer) {
// buffer.writeShort(packet.getItems().length);
//
// for (CpfItem item : packet.getItems()) {
// CpfItem.encode(item, buffer);
// }
//
// return buffer;
// }
//
// public static CpfPacket decode(ByteBuf buffer) {
// int itemCount = buffer.readUnsignedShort();
// CpfItem[] items = new CpfItem[itemCount];
//
// for (int i = 0; i < itemCount; i++) {
// items[i] = CpfItem.decode(buffer);
// }
//
// return new CpfPacket(items);
// }
// }
// Path: enip-core/src/main/java/com/digitalpetri/enip/commands/SendUnitData.java
import com.digitalpetri.enip.cpf.CpfPacket;
import io.netty.buffer.ByteBuf;
package com.digitalpetri.enip.commands;
public final class SendUnitData extends Command {
public static final long DEFAULT_INTERFACE_HANDLE = 0;
public static final int DEFAULT_TIMEOUT = 0;
private final long interfaceHandle;
private final int timeout; | private final CpfPacket packet; |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/services/GetAttributeSingleService.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/CipResponseException.java
// public class CipResponseException extends Exception {
//
// private final int generalStatus;
// private final int[] additionalStatus;
//
// public CipResponseException(int generalStatus, int[] additionalStatus) {
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
//
// sb.append(String.format("status=0x%02X", generalStatus));
//
// CipStatusCodes.getName(generalStatus).ifPresent(name -> sb.append(" [").append(name).append("] "));
//
// List<String> as = Arrays.stream(additionalStatus)
// .mapToObj(a -> String.format("0x%04X", a))
// .collect(Collectors.toList());
//
// String additional = "[" + String.join(",", as) + "]";
//
// sb.append(", additional=").append(additional);
//
// return sb.toString();
// }
//
// /**
// * If {@code ex} is a {@link CipResponseException}, or if a {@link CipResponseException} can be found by walking
// * the exception cause chain, return it.
// *
// * @param ex the {@link Throwable} to extract from.
// * @return a {@link CipResponseException} if one was present in the exception chain.
// */
// public static Optional<CipResponseException> extract(Throwable ex) {
// if (ex instanceof CipResponseException) {
// return Optional.of((CipResponseException) ex);
// } else {
// Throwable cause = ex.getCause();
// return cause != null ?
// extract(cause) : Optional.empty();
// }
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterRequest.java
// public class MessageRouterRequest {
//
// private final int serviceCode;
// private final EPath.PaddedEPath requestPath;
// private final Consumer<ByteBuf> dataEncoder;
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, ByteBuf requestData) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = (buffer) -> buffer.writeBytes(requestData);
// }
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, Consumer<ByteBuf> dataEncoder) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = dataEncoder;
// }
//
// public static void encode(MessageRouterRequest request, ByteBuf buffer) {
// buffer.writeByte(request.serviceCode);
// EPath.encode(request.requestPath, buffer);
// request.dataEncoder.accept(buffer);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterResponse.java
// public class MessageRouterResponse {
//
// private final int serviceCode;
// private final int generalStatus;
// private final int[] additionalStatus;
//
// private final ByteBuf data;
//
// public MessageRouterResponse(int serviceCode,
// int generalStatus,
// int[] additionalStatus,
// @Nonnull ByteBuf data) {
//
// this.serviceCode = serviceCode;
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// this.data = data;
// }
//
// public int getServiceCode() {
// return serviceCode;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Nonnull
// public ByteBuf getData() {
// return data;
// }
//
// public static MessageRouterResponse decode(ByteBuf buffer) {
// int serviceCode = buffer.readUnsignedByte();
// buffer.skipBytes(1); // reserved
// int generalStatus = buffer.readUnsignedByte();
//
// int count = buffer.readUnsignedByte();
// int[] additionalStatus = new int[count];
// for (int i = 0; i < count; i++) {
// additionalStatus[i] = buffer.readShort();
// }
//
// ByteBuf data = buffer.isReadable() ?
// buffer.readSlice(buffer.readableBytes()).retain() : Unpooled.EMPTY_BUFFER;
//
// return new MessageRouterResponse(serviceCode, generalStatus, additionalStatus, data);
// }
//
// }
| import com.digitalpetri.enip.cip.CipResponseException;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.cip.structs.MessageRouterRequest;
import com.digitalpetri.enip.cip.structs.MessageRouterResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil; | package com.digitalpetri.enip.cip.services;
public class GetAttributeSingleService implements CipService<ByteBuf> {
public static final int SERVICE_CODE = 0x0E;
| // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/CipResponseException.java
// public class CipResponseException extends Exception {
//
// private final int generalStatus;
// private final int[] additionalStatus;
//
// public CipResponseException(int generalStatus, int[] additionalStatus) {
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
//
// sb.append(String.format("status=0x%02X", generalStatus));
//
// CipStatusCodes.getName(generalStatus).ifPresent(name -> sb.append(" [").append(name).append("] "));
//
// List<String> as = Arrays.stream(additionalStatus)
// .mapToObj(a -> String.format("0x%04X", a))
// .collect(Collectors.toList());
//
// String additional = "[" + String.join(",", as) + "]";
//
// sb.append(", additional=").append(additional);
//
// return sb.toString();
// }
//
// /**
// * If {@code ex} is a {@link CipResponseException}, or if a {@link CipResponseException} can be found by walking
// * the exception cause chain, return it.
// *
// * @param ex the {@link Throwable} to extract from.
// * @return a {@link CipResponseException} if one was present in the exception chain.
// */
// public static Optional<CipResponseException> extract(Throwable ex) {
// if (ex instanceof CipResponseException) {
// return Optional.of((CipResponseException) ex);
// } else {
// Throwable cause = ex.getCause();
// return cause != null ?
// extract(cause) : Optional.empty();
// }
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterRequest.java
// public class MessageRouterRequest {
//
// private final int serviceCode;
// private final EPath.PaddedEPath requestPath;
// private final Consumer<ByteBuf> dataEncoder;
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, ByteBuf requestData) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = (buffer) -> buffer.writeBytes(requestData);
// }
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, Consumer<ByteBuf> dataEncoder) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = dataEncoder;
// }
//
// public static void encode(MessageRouterRequest request, ByteBuf buffer) {
// buffer.writeByte(request.serviceCode);
// EPath.encode(request.requestPath, buffer);
// request.dataEncoder.accept(buffer);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterResponse.java
// public class MessageRouterResponse {
//
// private final int serviceCode;
// private final int generalStatus;
// private final int[] additionalStatus;
//
// private final ByteBuf data;
//
// public MessageRouterResponse(int serviceCode,
// int generalStatus,
// int[] additionalStatus,
// @Nonnull ByteBuf data) {
//
// this.serviceCode = serviceCode;
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// this.data = data;
// }
//
// public int getServiceCode() {
// return serviceCode;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Nonnull
// public ByteBuf getData() {
// return data;
// }
//
// public static MessageRouterResponse decode(ByteBuf buffer) {
// int serviceCode = buffer.readUnsignedByte();
// buffer.skipBytes(1); // reserved
// int generalStatus = buffer.readUnsignedByte();
//
// int count = buffer.readUnsignedByte();
// int[] additionalStatus = new int[count];
// for (int i = 0; i < count; i++) {
// additionalStatus[i] = buffer.readShort();
// }
//
// ByteBuf data = buffer.isReadable() ?
// buffer.readSlice(buffer.readableBytes()).retain() : Unpooled.EMPTY_BUFFER;
//
// return new MessageRouterResponse(serviceCode, generalStatus, additionalStatus, data);
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/services/GetAttributeSingleService.java
import com.digitalpetri.enip.cip.CipResponseException;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.cip.structs.MessageRouterRequest;
import com.digitalpetri.enip.cip.structs.MessageRouterResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
package com.digitalpetri.enip.cip.services;
public class GetAttributeSingleService implements CipService<ByteBuf> {
public static final int SERVICE_CODE = 0x0E;
| private final PaddedEPath requestPath; |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/epath/LogicalSegment.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/ElectronicKey.java
// public final class ElectronicKey {
//
// private final int vendorId;
// private final int deviceType;
// private final int productCode;
// private final boolean compatibilitySet;
// private final short majorRevision;
// private final short minorRevision;
//
// public ElectronicKey(int vendorId,
// int deviceType,
// int productCode,
// boolean compatibilitySet,
// short majorRevision,
// short minorRevision) {
//
// this.vendorId = vendorId;
// this.deviceType = deviceType;
// this.productCode = productCode;
// this.compatibilitySet = compatibilitySet;
// this.majorRevision = majorRevision;
// this.minorRevision = minorRevision;
// }
//
// public int getVendorId() {
// return vendorId;
// }
//
// public int getDeviceType() {
// return deviceType;
// }
//
// public int getProductCode() {
// return productCode;
// }
//
// public boolean isCompatibilitySet() {
// return compatibilitySet;
// }
//
// public short getMajorRevision() {
// return majorRevision;
// }
//
// public short getMinorRevision() {
// return minorRevision;
// }
//
// public static ByteBuf encode(ElectronicKey key, ByteBuf buffer) {
// buffer.writeShort(key.getVendorId());
// buffer.writeShort(key.getDeviceType());
// buffer.writeShort(key.getProductCode());
//
// int majorRevisionAndCompatibility = key.isCompatibilitySet() ? 0x80 : 0x00;
// majorRevisionAndCompatibility |= (key.getMajorRevision() & 0x7F);
//
// buffer.writeByte(majorRevisionAndCompatibility);
// buffer.writeByte(key.getMinorRevision());
//
// return buffer;
// }
//
// }
| import com.digitalpetri.enip.cip.structs.ElectronicKey;
import io.netty.buffer.ByteBuf; |
segmentByte |= (SEGMENT_TYPE << 5);
segmentByte |= (segment.getType().getType() << 2);
segmentByte |= segment.getFormat().getType();
buffer.writeByte(segmentByte);
if (padded && (segment.getFormat() == LogicalFormat.Bits_16 || segment.getFormat() == LogicalFormat.Bits_32)) {
buffer.writeByte(0x00);
}
segment.encodeValue(buffer);
return buffer;
}
private static ByteBuf encodeIntValue(LogicalFormat format, int value, ByteBuf buffer) {
switch (format) {
case Bits_8:
return buffer.writeByte(value);
case Bits_16:
return buffer.writeShort(value);
case Bits_32:
return buffer.writeInt(value);
case Reserved:
default:
throw new IllegalStateException("Reserved segment type not supported");
}
}
| // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/ElectronicKey.java
// public final class ElectronicKey {
//
// private final int vendorId;
// private final int deviceType;
// private final int productCode;
// private final boolean compatibilitySet;
// private final short majorRevision;
// private final short minorRevision;
//
// public ElectronicKey(int vendorId,
// int deviceType,
// int productCode,
// boolean compatibilitySet,
// short majorRevision,
// short minorRevision) {
//
// this.vendorId = vendorId;
// this.deviceType = deviceType;
// this.productCode = productCode;
// this.compatibilitySet = compatibilitySet;
// this.majorRevision = majorRevision;
// this.minorRevision = minorRevision;
// }
//
// public int getVendorId() {
// return vendorId;
// }
//
// public int getDeviceType() {
// return deviceType;
// }
//
// public int getProductCode() {
// return productCode;
// }
//
// public boolean isCompatibilitySet() {
// return compatibilitySet;
// }
//
// public short getMajorRevision() {
// return majorRevision;
// }
//
// public short getMinorRevision() {
// return minorRevision;
// }
//
// public static ByteBuf encode(ElectronicKey key, ByteBuf buffer) {
// buffer.writeShort(key.getVendorId());
// buffer.writeShort(key.getDeviceType());
// buffer.writeShort(key.getProductCode());
//
// int majorRevisionAndCompatibility = key.isCompatibilitySet() ? 0x80 : 0x00;
// majorRevisionAndCompatibility |= (key.getMajorRevision() & 0x7F);
//
// buffer.writeByte(majorRevisionAndCompatibility);
// buffer.writeByte(key.getMinorRevision());
//
// return buffer;
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/LogicalSegment.java
import com.digitalpetri.enip.cip.structs.ElectronicKey;
import io.netty.buffer.ByteBuf;
segmentByte |= (SEGMENT_TYPE << 5);
segmentByte |= (segment.getType().getType() << 2);
segmentByte |= segment.getFormat().getType();
buffer.writeByte(segmentByte);
if (padded && (segment.getFormat() == LogicalFormat.Bits_16 || segment.getFormat() == LogicalFormat.Bits_32)) {
buffer.writeByte(0x00);
}
segment.encodeValue(buffer);
return buffer;
}
private static ByteBuf encodeIntValue(LogicalFormat format, int value, ByteBuf buffer) {
switch (format) {
case Bits_8:
return buffer.writeByte(value);
case Bits_16:
return buffer.writeShort(value);
case Bits_32:
return buffer.writeInt(value);
case Reserved:
default:
throw new IllegalStateException("Reserved segment type not supported");
}
}
| private static ByteBuf encodeKeyValue(LogicalFormat format, ElectronicKey value, ByteBuf buffer) { |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/services/SetAttributesAllService.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/CipResponseException.java
// public class CipResponseException extends Exception {
//
// private final int generalStatus;
// private final int[] additionalStatus;
//
// public CipResponseException(int generalStatus, int[] additionalStatus) {
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
//
// sb.append(String.format("status=0x%02X", generalStatus));
//
// CipStatusCodes.getName(generalStatus).ifPresent(name -> sb.append(" [").append(name).append("] "));
//
// List<String> as = Arrays.stream(additionalStatus)
// .mapToObj(a -> String.format("0x%04X", a))
// .collect(Collectors.toList());
//
// String additional = "[" + String.join(",", as) + "]";
//
// sb.append(", additional=").append(additional);
//
// return sb.toString();
// }
//
// /**
// * If {@code ex} is a {@link CipResponseException}, or if a {@link CipResponseException} can be found by walking
// * the exception cause chain, return it.
// *
// * @param ex the {@link Throwable} to extract from.
// * @return a {@link CipResponseException} if one was present in the exception chain.
// */
// public static Optional<CipResponseException> extract(Throwable ex) {
// if (ex instanceof CipResponseException) {
// return Optional.of((CipResponseException) ex);
// } else {
// Throwable cause = ex.getCause();
// return cause != null ?
// extract(cause) : Optional.empty();
// }
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterRequest.java
// public class MessageRouterRequest {
//
// private final int serviceCode;
// private final EPath.PaddedEPath requestPath;
// private final Consumer<ByteBuf> dataEncoder;
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, ByteBuf requestData) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = (buffer) -> buffer.writeBytes(requestData);
// }
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, Consumer<ByteBuf> dataEncoder) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = dataEncoder;
// }
//
// public static void encode(MessageRouterRequest request, ByteBuf buffer) {
// buffer.writeByte(request.serviceCode);
// EPath.encode(request.requestPath, buffer);
// request.dataEncoder.accept(buffer);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterResponse.java
// public class MessageRouterResponse {
//
// private final int serviceCode;
// private final int generalStatus;
// private final int[] additionalStatus;
//
// private final ByteBuf data;
//
// public MessageRouterResponse(int serviceCode,
// int generalStatus,
// int[] additionalStatus,
// @Nonnull ByteBuf data) {
//
// this.serviceCode = serviceCode;
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// this.data = data;
// }
//
// public int getServiceCode() {
// return serviceCode;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Nonnull
// public ByteBuf getData() {
// return data;
// }
//
// public static MessageRouterResponse decode(ByteBuf buffer) {
// int serviceCode = buffer.readUnsignedByte();
// buffer.skipBytes(1); // reserved
// int generalStatus = buffer.readUnsignedByte();
//
// int count = buffer.readUnsignedByte();
// int[] additionalStatus = new int[count];
// for (int i = 0; i < count; i++) {
// additionalStatus[i] = buffer.readShort();
// }
//
// ByteBuf data = buffer.isReadable() ?
// buffer.readSlice(buffer.readableBytes()).retain() : Unpooled.EMPTY_BUFFER;
//
// return new MessageRouterResponse(serviceCode, generalStatus, additionalStatus, data);
// }
//
// }
| import java.util.function.Consumer;
import com.digitalpetri.enip.cip.CipResponseException;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.cip.structs.MessageRouterRequest;
import com.digitalpetri.enip.cip.structs.MessageRouterResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil; | package com.digitalpetri.enip.cip.services;
public class SetAttributesAllService implements CipService<Void> {
public static final int SERVICE_CODE = 0x02;
| // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/CipResponseException.java
// public class CipResponseException extends Exception {
//
// private final int generalStatus;
// private final int[] additionalStatus;
//
// public CipResponseException(int generalStatus, int[] additionalStatus) {
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
//
// sb.append(String.format("status=0x%02X", generalStatus));
//
// CipStatusCodes.getName(generalStatus).ifPresent(name -> sb.append(" [").append(name).append("] "));
//
// List<String> as = Arrays.stream(additionalStatus)
// .mapToObj(a -> String.format("0x%04X", a))
// .collect(Collectors.toList());
//
// String additional = "[" + String.join(",", as) + "]";
//
// sb.append(", additional=").append(additional);
//
// return sb.toString();
// }
//
// /**
// * If {@code ex} is a {@link CipResponseException}, or if a {@link CipResponseException} can be found by walking
// * the exception cause chain, return it.
// *
// * @param ex the {@link Throwable} to extract from.
// * @return a {@link CipResponseException} if one was present in the exception chain.
// */
// public static Optional<CipResponseException> extract(Throwable ex) {
// if (ex instanceof CipResponseException) {
// return Optional.of((CipResponseException) ex);
// } else {
// Throwable cause = ex.getCause();
// return cause != null ?
// extract(cause) : Optional.empty();
// }
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterRequest.java
// public class MessageRouterRequest {
//
// private final int serviceCode;
// private final EPath.PaddedEPath requestPath;
// private final Consumer<ByteBuf> dataEncoder;
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, ByteBuf requestData) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = (buffer) -> buffer.writeBytes(requestData);
// }
//
// public MessageRouterRequest(int serviceCode, EPath.PaddedEPath requestPath, Consumer<ByteBuf> dataEncoder) {
// this.serviceCode = serviceCode;
// this.requestPath = requestPath;
// this.dataEncoder = dataEncoder;
// }
//
// public static void encode(MessageRouterRequest request, ByteBuf buffer) {
// buffer.writeByte(request.serviceCode);
// EPath.encode(request.requestPath, buffer);
// request.dataEncoder.accept(buffer);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/MessageRouterResponse.java
// public class MessageRouterResponse {
//
// private final int serviceCode;
// private final int generalStatus;
// private final int[] additionalStatus;
//
// private final ByteBuf data;
//
// public MessageRouterResponse(int serviceCode,
// int generalStatus,
// int[] additionalStatus,
// @Nonnull ByteBuf data) {
//
// this.serviceCode = serviceCode;
// this.generalStatus = generalStatus;
// this.additionalStatus = additionalStatus;
// this.data = data;
// }
//
// public int getServiceCode() {
// return serviceCode;
// }
//
// public int getGeneralStatus() {
// return generalStatus;
// }
//
// public int[] getAdditionalStatus() {
// return additionalStatus;
// }
//
// @Nonnull
// public ByteBuf getData() {
// return data;
// }
//
// public static MessageRouterResponse decode(ByteBuf buffer) {
// int serviceCode = buffer.readUnsignedByte();
// buffer.skipBytes(1); // reserved
// int generalStatus = buffer.readUnsignedByte();
//
// int count = buffer.readUnsignedByte();
// int[] additionalStatus = new int[count];
// for (int i = 0; i < count; i++) {
// additionalStatus[i] = buffer.readShort();
// }
//
// ByteBuf data = buffer.isReadable() ?
// buffer.readSlice(buffer.readableBytes()).retain() : Unpooled.EMPTY_BUFFER;
//
// return new MessageRouterResponse(serviceCode, generalStatus, additionalStatus, data);
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/services/SetAttributesAllService.java
import java.util.function.Consumer;
import com.digitalpetri.enip.cip.CipResponseException;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.cip.structs.MessageRouterRequest;
import com.digitalpetri.enip.cip.structs.MessageRouterResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
package com.digitalpetri.enip.cip.services;
public class SetAttributesAllService implements CipService<Void> {
public static final int SERVICE_CODE = 0x02;
| private final PaddedEPath requestPath; |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/structs/ForwardOpenRequest.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
| import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf; | package com.digitalpetri.enip.cip.structs;
public final class ForwardOpenRequest {
private final Duration timeout;
private final int o2tConnectionId;
private final int t2oConnectionId;
private final int connectionSerialNumber;
private final int vendorId;
private final long vendorSerialNumber;
private final int connectionTimeoutMultiplier; | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/ForwardOpenRequest.java
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf;
package com.digitalpetri.enip.cip.structs;
public final class ForwardOpenRequest {
private final Duration timeout;
private final int o2tConnectionId;
private final int t2oConnectionId;
private final int connectionSerialNumber;
private final int vendorId;
private final long vendorSerialNumber;
private final int connectionTimeoutMultiplier; | private final EPath.PaddedEPath connectionPath; |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/structs/ForwardOpenRequest.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
| import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf; |
public int getConnectionTimeoutMultiplier() {
return connectionTimeoutMultiplier;
}
public EPath.PaddedEPath getConnectionPath() {
return connectionPath;
}
public Duration getO2tRpi() {
return o2tRpi;
}
public NetworkConnectionParameters getO2tParameters() {
return o2tParameters;
}
public Duration getT2oRpi() {
return t2oRpi;
}
public NetworkConnectionParameters getT2oParameters() {
return t2oParameters;
}
public int getTransportClassAndTrigger() {
return transportClassAndTrigger;
}
public static ByteBuf encode(ForwardOpenRequest request, ByteBuf buffer) { | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/ForwardOpenRequest.java
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf;
public int getConnectionTimeoutMultiplier() {
return connectionTimeoutMultiplier;
}
public EPath.PaddedEPath getConnectionPath() {
return connectionPath;
}
public Duration getO2tRpi() {
return o2tRpi;
}
public NetworkConnectionParameters getO2tParameters() {
return o2tParameters;
}
public Duration getT2oRpi() {
return t2oRpi;
}
public NetworkConnectionParameters getT2oParameters() {
return t2oParameters;
}
public int getTransportClassAndTrigger() {
return transportClassAndTrigger;
}
public static ByteBuf encode(ForwardOpenRequest request, ByteBuf buffer) { | int priorityAndTimeoutBytes = TimeoutCalculator.calculateTimeoutBytes(request.timeout); |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/structs/LargeForwardOpenRequest.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
| import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf; | package com.digitalpetri.enip.cip.structs;
public class LargeForwardOpenRequest {
private final Duration timeout;
private final int o2tConnectionId;
private final int t2oConnectionId;
private final int connectionSerialNumber;
private final int vendorId;
private final long vendorSerialNumber;
private final int connectionTimeoutMultiplier; | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/LargeForwardOpenRequest.java
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf;
package com.digitalpetri.enip.cip.structs;
public class LargeForwardOpenRequest {
private final Duration timeout;
private final int o2tConnectionId;
private final int t2oConnectionId;
private final int connectionSerialNumber;
private final int vendorId;
private final long vendorSerialNumber;
private final int connectionTimeoutMultiplier; | private final EPath.PaddedEPath connectionPath; |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/structs/LargeForwardOpenRequest.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
| import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf; | package com.digitalpetri.enip.cip.structs;
public class LargeForwardOpenRequest {
private final Duration timeout;
private final int o2tConnectionId;
private final int t2oConnectionId;
private final int connectionSerialNumber;
private final int vendorId;
private final long vendorSerialNumber;
private final int connectionTimeoutMultiplier; | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/LargeForwardOpenRequest.java
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf;
package com.digitalpetri.enip.cip.structs;
public class LargeForwardOpenRequest {
private final Duration timeout;
private final int o2tConnectionId;
private final int t2oConnectionId;
private final int connectionSerialNumber;
private final int vendorId;
private final long vendorSerialNumber;
private final int connectionTimeoutMultiplier; | private final EPath.PaddedEPath connectionPath; |
digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/structs/LargeForwardOpenRequest.java | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
| import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf; |
public int getConnectionTimeoutMultiplier() {
return connectionTimeoutMultiplier;
}
public PaddedEPath getConnectionPath() {
return connectionPath;
}
public Duration getO2tRpi() {
return o2tRpi;
}
public NetworkConnectionParameters getO2tParameters() {
return o2tParameters;
}
public Duration getT2oRpi() {
return t2oRpi;
}
public NetworkConnectionParameters getT2oParameters() {
return t2oParameters;
}
public int getTransportClassAndTrigger() {
return transportClassAndTrigger;
}
public static ByteBuf encode(LargeForwardOpenRequest request, ByteBuf buffer) { | // Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public abstract class EPath {
//
// private final EPathSegment[] segments;
//
// protected EPath(EPathSegment[] segments) {
// this.segments = segments;
// }
//
// public EPathSegment[] getSegments() {
// return segments;
// }
//
// public abstract boolean isPadded();
//
// public static ByteBuf encode(EPath path, ByteBuf buffer) {
// // length placeholder...
// int lengthStartIndex = buffer.writerIndex();
// buffer.writeByte(0);
//
// // encode the path segments...
// int dataStartIndex = buffer.writerIndex();
//
// for (EPathSegment segment : path.getSegments()) {
// if (segment instanceof LogicalSegment) {
// LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof PortSegment) {
// PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
// } else if (segment instanceof DataSegment) {
// DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
// } else {
// throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
// }
// }
//
// // go back and update the length
// int bytesWritten = buffer.writerIndex() - dataStartIndex;
// int wordsWritten = bytesWritten / 2;
// buffer.markWriterIndex();
// buffer.writerIndex(lengthStartIndex);
// buffer.writeByte(wordsWritten);
// buffer.resetWriterIndex();
//
// return buffer;
// }
//
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/epath/EPath.java
// public static final class PaddedEPath extends EPath {
//
// public PaddedEPath(List<EPathSegment> segments) {
// this(segments.toArray(new EPathSegment[segments.size()]));
// }
//
// public PaddedEPath(EPathSegment... segments) {
// super(segments);
// }
//
// @Override
// public boolean isPadded() {
// return true;
// }
//
// public PaddedEPath append(PaddedEPath other) {
// int aLen = getSegments().length;
// int bLen = other.getSegments().length;
//
// EPathSegment[] newSegments = new EPathSegment[aLen + bLen];
//
// System.arraycopy(getSegments(), 0, newSegments, 0, aLen);
// System.arraycopy(other.getSegments(), 0, newSegments, aLen, bLen);
//
// return new PaddedEPath(newSegments);
// }
//
// }
//
// Path: cip-core/src/main/java/com/digitalpetri/enip/util/TimeoutCalculator.java
// public class TimeoutCalculator {
//
// private static final int MIN_TIMEOUT = 1;
// private static final int MAX_TIMEOUT = 8355840;
//
// public static int calculateTimeoutBytes(Duration timeout) {
// int desiredTimeout = (int) timeout.toMillis();
//
// if (desiredTimeout < MIN_TIMEOUT) desiredTimeout = MIN_TIMEOUT;
// if (desiredTimeout > MAX_TIMEOUT) desiredTimeout = MAX_TIMEOUT;
//
// boolean precisionLost = false;
// int shifts = 0;
// int multiplier = desiredTimeout;
//
// while (multiplier > 255) {
// precisionLost |= (multiplier & 1) == 1;
// multiplier >>= 1;
// shifts += 1;
// }
//
// if (precisionLost) {
// multiplier += 1;
// if (multiplier > 255) {
// multiplier >>= 1;
// shifts += 1;
// }
// }
//
// assert (shifts <= 15);
//
// int tick = (int) Math.pow(2, shifts);
//
// assert (tick >= 1 && tick <= 32768);
// assert (multiplier >= 1 && multiplier <= 255);
//
// return shifts << 8 | multiplier;
// }
//
// }
// Path: cip-core/src/main/java/com/digitalpetri/enip/cip/structs/LargeForwardOpenRequest.java
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.digitalpetri.enip.cip.epath.EPath;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.util.TimeoutCalculator;
import io.netty.buffer.ByteBuf;
public int getConnectionTimeoutMultiplier() {
return connectionTimeoutMultiplier;
}
public PaddedEPath getConnectionPath() {
return connectionPath;
}
public Duration getO2tRpi() {
return o2tRpi;
}
public NetworkConnectionParameters getO2tParameters() {
return o2tParameters;
}
public Duration getT2oRpi() {
return t2oRpi;
}
public NetworkConnectionParameters getT2oParameters() {
return t2oParameters;
}
public int getTransportClassAndTrigger() {
return transportClassAndTrigger;
}
public static ByteBuf encode(LargeForwardOpenRequest request, ByteBuf buffer) { | int priorityAndTimeoutBytes = TimeoutCalculator.calculateTimeoutBytes(request.timeout); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.