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
kogalur/randomForestSRC
src/main/java/Native.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.RFLogger; import java.io.File; import java.util.LinkedHashMap; import java.util.logging.Level; import java.io.IOException; import java.lang.SecurityException;
package com.kogalur.randomforest; class Native { private static Native myInstance; static { File file = new File("."); String libraryLocation; String libraryName; String opsSwitch; String sep; boolean libraryFlag; try { libraryFlag = true; libraryLocation = file.getCanonicalPath(); sep = File.separator; opsSwitch = System.getProperty("os.name"); if (opsSwitch.startsWith("Windows")) { libraryName = "@[email protected]"; } else if (opsSwitch.startsWith("Mac OS X")) { libraryName = "lib@[email protected]"; } else if (opsSwitch.startsWith("Linux")) { libraryName = "lib@[email protected]"; } else { libraryFlag = false;
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/Native.java import com.kogalur.randomforest.RFLogger; import java.io.File; import java.util.LinkedHashMap; import java.util.logging.Level; import java.io.IOException; import java.lang.SecurityException; package com.kogalur.randomforest; class Native { private static Native myInstance; static { File file = new File("."); String libraryLocation; String libraryName; String opsSwitch; String sep; boolean libraryFlag; try { libraryFlag = true; libraryLocation = file.getCanonicalPath(); sep = File.separator; opsSwitch = System.getProperty("os.name"); if (opsSwitch.startsWith("Windows")) { libraryName = "@[email protected]"; } else if (opsSwitch.startsWith("Mac OS X")) { libraryName = "lib@[email protected]"; } else if (opsSwitch.startsWith("Linux")) { libraryName = "lib@[email protected]"; } else { libraryFlag = false;
RFLogger.log(Level.SEVERE, "Unknown OS in determining shared object library for @PROJECT_PACKAGE_NAME@: " + opsSwitch);
kogalur/randomForestSRC
src/main/java/NativeOpt.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.RFLogger; import java.util.logging.Level;
package com.kogalur.randomforest; class NativeOpt { String name; java.util.HashMap <String, Integer> option; NativeOpt(String optionName, String[] optionParm, int[] optionBit) { if (optionParm.length != optionBit.length) {
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/NativeOpt.java import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; package com.kogalur.randomforest; class NativeOpt { String name; java.util.HashMap <String, Integer> option; NativeOpt(String optionName, String[] optionParm, int[] optionBit) { if (optionParm.length != optionBit.length) {
RFLogger.log(Level.SEVERE, "Constructor parameters malformed and of unequal length for: " + optionName);
kogalur/randomForestSRC
src/main/java/Ensemble.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.RFLogger; import java.util.Arrays; import java.util.logging.Level;
package com.kogalur.randomforest; class Ensemble { /* >>> CAUTION These are mapped to the native types in src/main/global.h <<< CAUTION */ // Name of the ensemble. String name; // Type of ensemble (char), (int), or (double). EnsembleType type; // Position or slot in list. int slot; // Size of ensemble vector; long size; // Multi-dimensional view of the ensemble. This is the number of dimensions. int auxDimSize; // Multi-dimensional view of the ensemble. This is the size of the internal dimensions. int[] auxDim; // Generic object containing the ensemble vector. This will be of type (double) or (int). Object ensembleVector; // Constructor called from native-code. Before exiting the // C-code, we loop over a list and populate each ensemble and it's // associated fields. void Ensemble(String name, byte nativeType, int slot, long size, int auxDimSize, int[] auxDim, Object ensembleVector) { int actualLength = 0; if (nativeType == EnsembleType.CHAR.getValue()) { type = EnsembleType.CHAR; actualLength = ((char[]) (ensembleVector)).length; } else if (nativeType == EnsembleType.INT.getValue()) { type = EnsembleType.INT; actualLength = ((int[]) (ensembleVector)).length; } else if (nativeType == EnsembleType.DOUBLE.getValue()) { type = EnsembleType.DOUBLE; actualLength = ((double[]) (ensembleVector)).length; } else {
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/Ensemble.java import com.kogalur.randomforest.RFLogger; import java.util.Arrays; import java.util.logging.Level; package com.kogalur.randomforest; class Ensemble { /* >>> CAUTION These are mapped to the native types in src/main/global.h <<< CAUTION */ // Name of the ensemble. String name; // Type of ensemble (char), (int), or (double). EnsembleType type; // Position or slot in list. int slot; // Size of ensemble vector; long size; // Multi-dimensional view of the ensemble. This is the number of dimensions. int auxDimSize; // Multi-dimensional view of the ensemble. This is the size of the internal dimensions. int[] auxDim; // Generic object containing the ensemble vector. This will be of type (double) or (int). Object ensembleVector; // Constructor called from native-code. Before exiting the // C-code, we loop over a list and populate each ensemble and it's // associated fields. void Ensemble(String name, byte nativeType, int slot, long size, int auxDimSize, int[] auxDim, Object ensembleVector) { int actualLength = 0; if (nativeType == EnsembleType.CHAR.getValue()) { type = EnsembleType.CHAR; actualLength = ((char[]) (ensembleVector)).length; } else if (nativeType == EnsembleType.INT.getValue()) { type = EnsembleType.INT; actualLength = ((int[]) (ensembleVector)).length; } else if (nativeType == EnsembleType.DOUBLE.getValue()) { type = EnsembleType.DOUBLE; actualLength = ((double[]) (ensembleVector)).length; } else {
RFLogger.log(Level.SEVERE, "Ensemble type (native) not found: " + nativeType);
kogalur/randomForestSRC
src/main/java/TestModelArg.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import org.apache.spark.sql.Dataset; import java.util.ArrayList; import java.util.Arrays; import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.Random;
set_xMarginal(); set_xImportance(); set_partial(); } /** * Sets the y-variable(s) to be targeted when multivariate * families are in force. Predictions over this set of targets * will be included in the ensembles. * @param yTarget Array of y-variables to be targeted when * multivariate families are in force. The default action is to * use all y-variables. */ public void set_yTarget(String[] yTarget) { this.yTarget = yTarget; int size = yTarget.length; ArrayList <String> allVariableList = new ArrayList <String> (Arrays.asList(modelArg.getYvar())); yTargetIndex = new int[size]; for (int i = 0; i < size; i++) { // Note the offset for the native code. yTargetIndex[i] = allVariableList.indexOf(yTarget[i]) + 1; if (yTargetIndex[i] <= 0) {
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/TestModelArg.java import org.apache.spark.sql.Dataset; import java.util.ArrayList; import java.util.Arrays; import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.Random; set_xMarginal(); set_xImportance(); set_partial(); } /** * Sets the y-variable(s) to be targeted when multivariate * families are in force. Predictions over this set of targets * will be included in the ensembles. * @param yTarget Array of y-variables to be targeted when * multivariate families are in force. The default action is to * use all y-variables. */ public void set_yTarget(String[] yTarget) { this.yTarget = yTarget; int size = yTarget.length; ArrayList <String> allVariableList = new ArrayList <String> (Arrays.asList(modelArg.getYvar())); yTargetIndex = new int[size]; for (int i = 0; i < size; i++) { // Note the offset for the native code. yTargetIndex[i] = allVariableList.indexOf(yTarget[i]) + 1; if (yTargetIndex[i] <= 0) {
RFLogger.log(Level.SEVERE, "Target y-variable not found in model: " + yTarget[i]);
kogalur/randomForestSRC
src/main/java/RandomForestModel.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.RFLogger; import java.lang.Math; import java.util.Arrays; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Set; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.logging.Level;
else { this.modelType = ModelType.PRED; } } // TBD TBD remove public option TBD TBD public Ensemble getEnsembleObj(String name) { Ensemble ensb = (Ensemble) ensembleList.get(name); return ensb; } // TBD TBD remove public option TBD TBD public void printEnsembleList() { Set entrySet = ensembleList.entrySet(); Iterator itr = entrySet.iterator(); int actLength = 0; long thrLength = 0; int i = 0; while(itr.hasNext()){ Map.Entry me = (Map.Entry) itr.next(); Ensemble ensb = (Ensemble) me.getValue(); ensb.printMetaInfo(); i++; } } // TBD TBD remove public option TBD TBD public void printEnsemble(Object ensb) { if (ensb == null) {
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/RandomForestModel.java import com.kogalur.randomforest.RFLogger; import java.lang.Math; import java.util.Arrays; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Set; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.logging.Level; else { this.modelType = ModelType.PRED; } } // TBD TBD remove public option TBD TBD public Ensemble getEnsembleObj(String name) { Ensemble ensb = (Ensemble) ensembleList.get(name); return ensb; } // TBD TBD remove public option TBD TBD public void printEnsembleList() { Set entrySet = ensembleList.entrySet(); Iterator itr = entrySet.iterator(); int actLength = 0; long thrLength = 0; int i = 0; while(itr.hasNext()){ Map.Entry me = (Map.Entry) itr.next(); Ensemble ensb = (Ensemble) me.getValue(); ensb.printMetaInfo(); i++; } } // TBD TBD remove public option TBD TBD public void printEnsemble(Object ensb) { if (ensb == null) {
RFLogger.log(Level.INFO, "Ensemble: null");
kogalur/randomForestSRC
src/main/java/ModelArg.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import org.apache.spark.sql.Row; import org.apache.spark.ml.feature.StringIndexer; import java.lang.Math; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Random; import java.util.Vector;
mode = new String("grow"); this.dataset = dataset; this.formula = formula; // Extract the column names from the dataset. columnName = dataset.columns(); setDefaultModelArg(); ensembleArg = new EnsembleArg(mode, family); } private void parseFormula() { boolean bigRFlag, complementFlag; formula = formula.replaceAll("\\ ", ""); formulaU = formula.split("~"); // ytry can be set via the RF-U formula. Thus we set the // default and user specified values here, directly. ytry = 0; if (formulaU.length != 2) { // Bad Formula. Throw exception.
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/ModelArg.java import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import org.apache.spark.sql.Row; import org.apache.spark.ml.feature.StringIndexer; import java.lang.Math; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Random; import java.util.Vector; mode = new String("grow"); this.dataset = dataset; this.formula = formula; // Extract the column names from the dataset. columnName = dataset.columns(); setDefaultModelArg(); ensembleArg = new EnsembleArg(mode, family); } private void parseFormula() { boolean bigRFlag, complementFlag; formula = formula.replaceAll("\\ ", ""); formulaU = formula.split("~"); // ytry can be set via the RF-U formula. Thus we set the // default and user specified values here, directly. ytry = 0; if (formulaU.length != 2) { // Bad Formula. Throw exception.
RFLogger.log(Level.SEVERE, "Unknown Formula Syntax: " + formula);
kogalur/randomForestSRC
src/main/java/EnsembleArg.java
// Path: src/main/java/NativeOpt.java // class NativeOpt { // // String name; // // java.util.HashMap <String, Integer> option; // // NativeOpt(String optionName, String[] optionParm, int[] optionBit) { // // if (optionParm.length != optionBit.length) { // RFLogger.log(Level.SEVERE, "Constructor parameters malformed and of unequal length for: " + optionName); // RFLogger.log(Level.SEVERE, "Please contact technical support."); // throw new IllegalArgumentException(); // } // // name = optionName; // option = new java.util.HashMap <String, Integer> (optionParm.length); // // for (int i = 0; i < optionParm.length; i++) { // option.put(optionParm[i], optionBit[i]); // } // } // // // int get(String optionParm) { // if (!option.containsKey(optionParm)) { // RFLogger.log(Level.SEVERE, "Unknown key: " + optionParm); // throw new IllegalArgumentException(); // } // return option.get(optionParm).intValue(); // } // // // } // // Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.NativeOpt; import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.List;
package com.kogalur.randomforest; //import java.util.Iterator; //import java.util.Arrays; //import java.util.ArrayList; class EnsembleArg { private String mode; private String family; private EnsembleArg growEnsembleArg; private java.util.HashMap <String, String> ensembleArg;
// Path: src/main/java/NativeOpt.java // class NativeOpt { // // String name; // // java.util.HashMap <String, Integer> option; // // NativeOpt(String optionName, String[] optionParm, int[] optionBit) { // // if (optionParm.length != optionBit.length) { // RFLogger.log(Level.SEVERE, "Constructor parameters malformed and of unequal length for: " + optionName); // RFLogger.log(Level.SEVERE, "Please contact technical support."); // throw new IllegalArgumentException(); // } // // name = optionName; // option = new java.util.HashMap <String, Integer> (optionParm.length); // // for (int i = 0; i < optionParm.length; i++) { // option.put(optionParm[i], optionBit[i]); // } // } // // // int get(String optionParm) { // if (!option.containsKey(optionParm)) { // RFLogger.log(Level.SEVERE, "Unknown key: " + optionParm); // throw new IllegalArgumentException(); // } // return option.get(optionParm).intValue(); // } // // // } // // Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/EnsembleArg.java import com.kogalur.randomforest.NativeOpt; import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.List; package com.kogalur.randomforest; //import java.util.Iterator; //import java.util.Arrays; //import java.util.ArrayList; class EnsembleArg { private String mode; private String family; private EnsembleArg growEnsembleArg; private java.util.HashMap <String, String> ensembleArg;
private java.util.HashMap <String, NativeOpt> ensembleList;
kogalur/randomForestSRC
src/main/java/EnsembleArg.java
// Path: src/main/java/NativeOpt.java // class NativeOpt { // // String name; // // java.util.HashMap <String, Integer> option; // // NativeOpt(String optionName, String[] optionParm, int[] optionBit) { // // if (optionParm.length != optionBit.length) { // RFLogger.log(Level.SEVERE, "Constructor parameters malformed and of unequal length for: " + optionName); // RFLogger.log(Level.SEVERE, "Please contact technical support."); // throw new IllegalArgumentException(); // } // // name = optionName; // option = new java.util.HashMap <String, Integer> (optionParm.length); // // for (int i = 0; i < optionParm.length; i++) { // option.put(optionParm[i], optionBit[i]); // } // } // // // int get(String optionParm) { // if (!option.containsKey(optionParm)) { // RFLogger.log(Level.SEVERE, "Unknown key: " + optionParm); // throw new IllegalArgumentException(); // } // return option.get(optionParm).intValue(); // } // // // } // // Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.NativeOpt; import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.List;
ensembleList.put("predictionType", new NativeOpt("predictionType", new String[] {"default"}, new int[] {0})); } else if (family.equals("RF-U")) { ensembleArg.put("errorType", "no"); ensembleList.put("errorType", new NativeOpt("errorType", new String[] {"no"}, new int[] {0})); ensembleArg.put("predictionType", "no"); ensembleList.put("predictionType", new NativeOpt("predictionType", new String[] {"no"}, new int[] {0})); } } void set(String key, String value) { if (ensembleList.containsKey(key)) { boolean setFlag = true; // The following keys have restrictions. if (key.equals("forest")) {
// Path: src/main/java/NativeOpt.java // class NativeOpt { // // String name; // // java.util.HashMap <String, Integer> option; // // NativeOpt(String optionName, String[] optionParm, int[] optionBit) { // // if (optionParm.length != optionBit.length) { // RFLogger.log(Level.SEVERE, "Constructor parameters malformed and of unequal length for: " + optionName); // RFLogger.log(Level.SEVERE, "Please contact technical support."); // throw new IllegalArgumentException(); // } // // name = optionName; // option = new java.util.HashMap <String, Integer> (optionParm.length); // // for (int i = 0; i < optionParm.length; i++) { // option.put(optionParm[i], optionBit[i]); // } // } // // // int get(String optionParm) { // if (!option.containsKey(optionParm)) { // RFLogger.log(Level.SEVERE, "Unknown key: " + optionParm); // throw new IllegalArgumentException(); // } // return option.get(optionParm).intValue(); // } // // // } // // Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/EnsembleArg.java import com.kogalur.randomforest.NativeOpt; import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.List; ensembleList.put("predictionType", new NativeOpt("predictionType", new String[] {"default"}, new int[] {0})); } else if (family.equals("RF-U")) { ensembleArg.put("errorType", "no"); ensembleList.put("errorType", new NativeOpt("errorType", new String[] {"no"}, new int[] {0})); ensembleArg.put("predictionType", "no"); ensembleList.put("predictionType", new NativeOpt("predictionType", new String[] {"no"}, new int[] {0})); } } void set(String key, String value) { if (ensembleList.containsKey(key)) { boolean setFlag = true; // The following keys have restrictions. if (key.equals("forest")) {
RFLogger.log(Level.WARNING, "forest ensemble cannot be modified.");
kogalur/randomForestSRC
src/main/java/GenericModelArg.java
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // }
import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.Random;
package com.kogalur.randomforest; class GenericModelArg { protected Random generator; protected int trace; protected int seed; protected int rfCores; protected int blockSize; protected int ntree; protected int[] getTree; protected Quantile quantile; protected String mode; private EnsembleArg ensembleArg; /** * Sets the seed for the random number generator used by the * algorithm. This must be a negative number. The seed is a very * important parameter if repeatability of the model generated is * required. Generally speaking, growing a model using the same * data set, the same model paramaters, and the same seed will * result in identical models. When large amounts of missing data * are involved, there can be slight variations due to Monte Carlo * effects. If the parameter is not set by the user, it can always * be recovered with {@link #get_seed}. */ public void set_seed(int seed) { this.seed = seed; if (seed >= 0) { if (seed > 0) {
// Path: src/main/java/RFLogger.java // public class RFLogger { // // private String fileName = "./classes/log.properties"; // private static java.util.logging.Logger logger = null; // // private static ConsoleHandler consoleHandler; // // private static SimpleFormatter simpleFormatter; // // private RFLogger() { // // // Create the logger. // logger = java.util.logging.Logger.getLogger(RFLogger.class.getName()); // // try { // java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(fileName)); // // } // catch (IOException e) { // System.out.println("Unable to configure logging for " + fileName); // // e.printStackTrace(); // // System.out.println("Resorting to console handler."); // // // //Create consoleHandler. // consoleHandler = new ConsoleHandler(); // // //Assigning handler to logger object. // logger.addHandler(consoleHandler); // // //Setting levels to handler and logger. // consoleHandler.setLevel(Level.INFO); // logger.setLevel(Level.ALL); // // // Creating SimpleFormatter for human readable format. // simpleFormatter = new SimpleFormatter(); // // // Setting formatter to all handlers. // consoleHandler.setFormatter(simpleFormatter); // // // Remove parent handlers in order to respect our formatting only. // // logger.setUseParentHandlers(false); // } // } // // private static java.util.logging.Logger getLogger() { // if(logger == null){ // new RFLogger(); // } // return logger; // } // // public static void log(Level level, String msg, Throwable thrown){ // getLogger().log(level, msg, thrown); // } // // public static void log(Level level, String msg){ // getLogger().log(level, msg); // } // // } // Path: src/main/java/GenericModelArg.java import com.kogalur.randomforest.RFLogger; import java.util.logging.Level; import java.util.Random; package com.kogalur.randomforest; class GenericModelArg { protected Random generator; protected int trace; protected int seed; protected int rfCores; protected int blockSize; protected int ntree; protected int[] getTree; protected Quantile quantile; protected String mode; private EnsembleArg ensembleArg; /** * Sets the seed for the random number generator used by the * algorithm. This must be a negative number. The seed is a very * important parameter if repeatability of the model generated is * required. Generally speaking, growing a model using the same * data set, the same model paramaters, and the same seed will * result in identical models. When large amounts of missing data * are involved, there can be slight variations due to Monte Carlo * effects. If the parameter is not set by the user, it can always * be recovered with {@link #get_seed}. */ public void set_seed(int seed) { this.seed = seed; if (seed >= 0) { if (seed > 0) {
RFLogger.log(Level.WARNING, "Invalid value for parameter seed: " + seed);
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/install/tasks/InstallVersionLibTask.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/ExtractRulesFileFilter.java // public class ExtractRulesFileFilter implements IZipFileFilter { // private ExtractRules rules; // // public ExtractRulesFileFilter(ExtractRules rules) { // this.rules = rules; // } // // @Override // public boolean shouldExtract(String fileName) { // return this.rules.shouldExtract(fileName); // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Library.java // public class Library { // // private static final StringSubstitutor SUBSTITUTOR = new StringSubstitutor(); // private static final String[] fallback = { "http://mirror.technicpack.net/Technic/lib/", "https://search.maven.org/remotecontent?filepath=" }; // private String name; // private List<Rule> rules; // private Map<OperatingSystem, String> natives; // private ExtractRules extract; // private String url; // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Rule> getRules() { // return rules; // } // // public Map<OperatingSystem, String> getNatives() { // return natives; // } // // public ExtractRules getExtract() { // return extract; // } // // public boolean isForCurrentOS() { // if (rules == null) { // return true; // } // return Rule.isAllowable(rules, null); // } // // public String getArtifactPath() { // return getArtifactPath(null); // } // // public String getArtifactPath(String classifier) { // if (this.name == null) { // throw new IllegalStateException("Cannot get artifact path of empty/blank artifact"); // } // return String.format("%s/%s", getArtifactBaseDir(), getArtifactFilename(classifier)); // } // // public String getArtifactBaseDir() { // if (this.name == null) { // throw new IllegalStateException("Cannot get artifact dir of empty/blank artifact"); // } // String[] parts = this.name.split(":", 3); // return String.format("%s/%s/%s", parts[0].replaceAll("\\.", "/"), parts[1], parts[2]); // } // // public String getArtifactFilename(String classifier) { // if (this.name == null) { // throw new IllegalStateException("Cannot get artifact filename of empty/blank artifact"); // } // // String[] parts = this.name.split(":", 3); // String result; // // if (classifier != null) { // result = String.format("%s-%s%s.jar", parts[1], parts[2], "-" + classifier); // } else { // result = String.format("%s-%s%s.jar", parts[1], parts[2], ""); // } // // return SUBSTITUTOR.replace(result); // } // // public String getDownloadUrl(String path, MirrorStore mirrorStore) { // if (this.url != null) { // String checkUrl = url + path; // if (Utils.pingHttpURL(checkUrl, mirrorStore)) { // return checkUrl; // } // for (String string : fallback) { // checkUrl = string + path; // if (Utils.pingHttpURL(checkUrl, mirrorStore)) { // return checkUrl; // } // } // } // return "https://libraries.minecraft.net/" + path; // } // // }
import net.technicpack.launchercore.install.ITasksQueue; import net.technicpack.launchercore.install.InstallTasksQueue; import net.technicpack.launchercore.install.LauncherDirectories; import net.technicpack.launchercore.install.tasks.EnsureFileTask; import net.technicpack.launchercore.install.tasks.ListenerTask; import net.technicpack.launchercore.install.verifiers.IFileVerifier; import net.technicpack.launchercore.install.verifiers.MD5FileVerifier; import net.technicpack.launchercore.install.verifiers.ValidZipFileVerifier; import net.technicpack.launchercore.modpacks.ModpackModel; import net.technicpack.minecraftcore.mojang.version.ExtractRulesFileFilter; import net.technicpack.minecraftcore.mojang.version.io.Library; import net.technicpack.utilslib.IZipFileFilter; import net.technicpack.utilslib.maven.MavenConnector; import net.technicpack.utilslib.OperatingSystem; import java.io.File; import java.io.IOException;
} } String path = library.getArtifactPath(natives).replace("${arch}", System.getProperty("sun.arch.data.model")); File cache = new File(directories.getCacheDirectory(), path); if (cache.getParentFile() != null) { cache.getParentFile().mkdirs(); } ValidZipFileVerifier zipVerifier = new ValidZipFileVerifier(); if (cache.exists() && zipVerifier.isFileValid(cache) && extractDirectory == null) return; IFileVerifier verifier = null; String url = null; if (!cache.exists() || !zipVerifier.isFileValid(cache)) { url = library.getDownloadUrl(path, queue.getMirrorStore()).replace("${arch}", System.getProperty("sun.arch.data.model")); String md5 = queue.getMirrorStore().getETag(url); if (md5 != null && !md5.isEmpty()) { verifier = new MD5FileVerifier(md5); } else { verifier = zipVerifier; } } IZipFileFilter filter = null; if (library.getExtract() != null)
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/ExtractRulesFileFilter.java // public class ExtractRulesFileFilter implements IZipFileFilter { // private ExtractRules rules; // // public ExtractRulesFileFilter(ExtractRules rules) { // this.rules = rules; // } // // @Override // public boolean shouldExtract(String fileName) { // return this.rules.shouldExtract(fileName); // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Library.java // public class Library { // // private static final StringSubstitutor SUBSTITUTOR = new StringSubstitutor(); // private static final String[] fallback = { "http://mirror.technicpack.net/Technic/lib/", "https://search.maven.org/remotecontent?filepath=" }; // private String name; // private List<Rule> rules; // private Map<OperatingSystem, String> natives; // private ExtractRules extract; // private String url; // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Rule> getRules() { // return rules; // } // // public Map<OperatingSystem, String> getNatives() { // return natives; // } // // public ExtractRules getExtract() { // return extract; // } // // public boolean isForCurrentOS() { // if (rules == null) { // return true; // } // return Rule.isAllowable(rules, null); // } // // public String getArtifactPath() { // return getArtifactPath(null); // } // // public String getArtifactPath(String classifier) { // if (this.name == null) { // throw new IllegalStateException("Cannot get artifact path of empty/blank artifact"); // } // return String.format("%s/%s", getArtifactBaseDir(), getArtifactFilename(classifier)); // } // // public String getArtifactBaseDir() { // if (this.name == null) { // throw new IllegalStateException("Cannot get artifact dir of empty/blank artifact"); // } // String[] parts = this.name.split(":", 3); // return String.format("%s/%s/%s", parts[0].replaceAll("\\.", "/"), parts[1], parts[2]); // } // // public String getArtifactFilename(String classifier) { // if (this.name == null) { // throw new IllegalStateException("Cannot get artifact filename of empty/blank artifact"); // } // // String[] parts = this.name.split(":", 3); // String result; // // if (classifier != null) { // result = String.format("%s-%s%s.jar", parts[1], parts[2], "-" + classifier); // } else { // result = String.format("%s-%s%s.jar", parts[1], parts[2], ""); // } // // return SUBSTITUTOR.replace(result); // } // // public String getDownloadUrl(String path, MirrorStore mirrorStore) { // if (this.url != null) { // String checkUrl = url + path; // if (Utils.pingHttpURL(checkUrl, mirrorStore)) { // return checkUrl; // } // for (String string : fallback) { // checkUrl = string + path; // if (Utils.pingHttpURL(checkUrl, mirrorStore)) { // return checkUrl; // } // } // } // return "https://libraries.minecraft.net/" + path; // } // // } // Path: src/main/java/net/technicpack/minecraftcore/install/tasks/InstallVersionLibTask.java import net.technicpack.launchercore.install.ITasksQueue; import net.technicpack.launchercore.install.InstallTasksQueue; import net.technicpack.launchercore.install.LauncherDirectories; import net.technicpack.launchercore.install.tasks.EnsureFileTask; import net.technicpack.launchercore.install.tasks.ListenerTask; import net.technicpack.launchercore.install.verifiers.IFileVerifier; import net.technicpack.launchercore.install.verifiers.MD5FileVerifier; import net.technicpack.launchercore.install.verifiers.ValidZipFileVerifier; import net.technicpack.launchercore.modpacks.ModpackModel; import net.technicpack.minecraftcore.mojang.version.ExtractRulesFileFilter; import net.technicpack.minecraftcore.mojang.version.io.Library; import net.technicpack.utilslib.IZipFileFilter; import net.technicpack.utilslib.maven.MavenConnector; import net.technicpack.utilslib.OperatingSystem; import java.io.File; import java.io.IOException; } } String path = library.getArtifactPath(natives).replace("${arch}", System.getProperty("sun.arch.data.model")); File cache = new File(directories.getCacheDirectory(), path); if (cache.getParentFile() != null) { cache.getParentFile().mkdirs(); } ValidZipFileVerifier zipVerifier = new ValidZipFileVerifier(); if (cache.exists() && zipVerifier.isFileValid(cache) && extractDirectory == null) return; IFileVerifier verifier = null; String url = null; if (!cache.exists() || !zipVerifier.isFileValid(cache)) { url = library.getDownloadUrl(path, queue.getMirrorStore()).replace("${arch}", System.getProperty("sun.arch.data.model")); String md5 = queue.getMirrorStore().getETag(url); if (md5 != null && !md5.isEmpty()) { verifier = new MD5FileVerifier(md5); } else { verifier = zipVerifier; } } IZipFileFilter filter = null; if (library.getExtract() != null)
filter = new ExtractRulesFileFilter(library.getExtract());
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/list/VersionEntry.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/ReleaseType.java // public enum ReleaseType { // SNAPSHOT("snapshot"), // RELEASE("release"), // OLD_BETA("old-beta"), // OLD_ALPHA("old-alpha"); // // private static final Map<String, ReleaseType> lookup = new HashMap<String, ReleaseType>(); // private final String name; // // private ReleaseType(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public static ReleaseType get(String name) { // return lookup.get(name); // } // // static { // for (ReleaseType type : values()) { // lookup.put(type.getName(), type); // } // } // }
import net.technicpack.minecraftcore.mojang.version.io.ReleaseType; import java.util.Date;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version.list; public class VersionEntry { private String id; private Date time; private Date releaseTime;
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/ReleaseType.java // public enum ReleaseType { // SNAPSHOT("snapshot"), // RELEASE("release"), // OLD_BETA("old-beta"), // OLD_ALPHA("old-alpha"); // // private static final Map<String, ReleaseType> lookup = new HashMap<String, ReleaseType>(); // private final String name; // // private ReleaseType(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public static ReleaseType get(String name) { // return lookup.get(name); // } // // static { // for (ReleaseType type : values()) { // lookup.put(type.getName(), type); // } // } // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/list/VersionEntry.java import net.technicpack.minecraftcore.mojang.version.io.ReleaseType; import java.util.Date; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version.list; public class VersionEntry { private String id; private Date time; private Date releaseTime;
private ReleaseType type;
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // }
import java.util.Date; import java.util.List; import net.technicpack.minecraftcore.mojang.version.io.*; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version; public interface MojangVersion { public String getId(); public ReleaseType getType(); public void setType(ReleaseType releaseType); public Date getUpdatedTime(); public void setUpdatedTime(Date updatedTime); public Date getReleaseTime(); public void setReleaseTime(Date releaseTime);
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java import java.util.Date; import java.util.List; import net.technicpack.minecraftcore.mojang.version.io.*; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version; public interface MojangVersion { public String getId(); public ReleaseType getType(); public void setType(ReleaseType releaseType); public Date getUpdatedTime(); public void setUpdatedTime(Date updatedTime); public Date getReleaseTime(); public void setReleaseTime(Date releaseTime);
public ArgumentList getMinecraftArguments();
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java
// Path: src/main/java/net/technicpack/minecraftcore/launch/ILaunchOptions.java // public interface ILaunchOptions { // String getClientId(); // WindowType getLaunchWindowType(); // int getCustomWidth(); // int getCustomHeight(); // boolean shouldUseStencilBuffer(); // }
import com.google.gson.JsonArray; import com.google.gson.JsonElement; import net.technicpack.minecraftcore.launch.ILaunchOptions; import org.apache.commons.text.StringSubstitutor; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package net.technicpack.minecraftcore.mojang.version.io.argument; public class ArgumentList { private final List<Argument> args; private ArgumentList(List<Argument> args) { this.args = Collections.unmodifiableList(args); } public static ArgumentList fromString(String args) { if (args == null) return null; Builder argsBuilder = new Builder(); for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); return argsBuilder.build(); } public List<Argument> getArguments() { return args; }
// Path: src/main/java/net/technicpack/minecraftcore/launch/ILaunchOptions.java // public interface ILaunchOptions { // String getClientId(); // WindowType getLaunchWindowType(); // int getCustomWidth(); // int getCustomHeight(); // boolean shouldUseStencilBuffer(); // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java import com.google.gson.JsonArray; import com.google.gson.JsonElement; import net.technicpack.minecraftcore.launch.ILaunchOptions; import org.apache.commons.text.StringSubstitutor; import java.util.ArrayList; import java.util.Collections; import java.util.List; package net.technicpack.minecraftcore.mojang.version.io.argument; public class ArgumentList { private final List<Argument> args; private ArgumentList(List<Argument> args) { this.args = Collections.unmodifiableList(args); } public static ArgumentList fromString(String args) { if (args == null) return null; Builder argsBuilder = new Builder(); for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); return argsBuilder.build(); } public List<Argument> getArguments() { return args; }
public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) {
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/auth/response/AuthResponse.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/Profile.java // public class Profile { // private String id; // private String name; // private boolean legacy; // // public Profile() { // // } // // public Profile(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public boolean isLegacy() { // return legacy; // } // // @Override // public String toString() { // return "Profile{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/User.java // public class User { // private String id; // private UserProperties properties; // // public User() { // // } // // public String getId() { // return id; // } // // public UserProperties getUserProperties() { // return properties; // } // }
import com.google.gson.JsonArray; import net.technicpack.launchercore.auth.IAuthResponse; import net.technicpack.minecraftcore.mojang.auth.io.Profile; import net.technicpack.minecraftcore.mojang.auth.io.User; import java.util.Arrays; import java.util.HashMap;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.auth.response; public class AuthResponse extends Response implements IAuthResponse { private String accessToken; private String clientToken;
// Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/Profile.java // public class Profile { // private String id; // private String name; // private boolean legacy; // // public Profile() { // // } // // public Profile(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public boolean isLegacy() { // return legacy; // } // // @Override // public String toString() { // return "Profile{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/User.java // public class User { // private String id; // private UserProperties properties; // // public User() { // // } // // public String getId() { // return id; // } // // public UserProperties getUserProperties() { // return properties; // } // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/response/AuthResponse.java import com.google.gson.JsonArray; import net.technicpack.launchercore.auth.IAuthResponse; import net.technicpack.minecraftcore.mojang.auth.io.Profile; import net.technicpack.minecraftcore.mojang.auth.io.User; import java.util.Arrays; import java.util.HashMap; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.auth.response; public class AuthResponse extends Response implements IAuthResponse { private String accessToken; private String clientToken;
private Profile[] availableProfiles;
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/auth/response/AuthResponse.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/Profile.java // public class Profile { // private String id; // private String name; // private boolean legacy; // // public Profile() { // // } // // public Profile(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public boolean isLegacy() { // return legacy; // } // // @Override // public String toString() { // return "Profile{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/User.java // public class User { // private String id; // private UserProperties properties; // // public User() { // // } // // public String getId() { // return id; // } // // public UserProperties getUserProperties() { // return properties; // } // }
import com.google.gson.JsonArray; import net.technicpack.launchercore.auth.IAuthResponse; import net.technicpack.minecraftcore.mojang.auth.io.Profile; import net.technicpack.minecraftcore.mojang.auth.io.User; import java.util.Arrays; import java.util.HashMap;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.auth.response; public class AuthResponse extends Response implements IAuthResponse { private String accessToken; private String clientToken; private Profile[] availableProfiles; private Profile selectedProfile;
// Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/Profile.java // public class Profile { // private String id; // private String name; // private boolean legacy; // // public Profile() { // // } // // public Profile(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public boolean isLegacy() { // return legacy; // } // // @Override // public String toString() { // return "Profile{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/io/User.java // public class User { // private String id; // private UserProperties properties; // // public User() { // // } // // public String getId() { // return id; // } // // public UserProperties getUserProperties() { // return properties; // } // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/auth/response/AuthResponse.java import com.google.gson.JsonArray; import net.technicpack.launchercore.auth.IAuthResponse; import net.technicpack.minecraftcore.mojang.auth.io.Profile; import net.technicpack.minecraftcore.mojang.auth.io.User; import java.util.Arrays; import java.util.HashMap; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.auth.response; public class AuthResponse extends Response implements IAuthResponse { private String accessToken; private String clientToken; private Profile[] availableProfiles; private Profile selectedProfile;
private User user;
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/install/tasks/InstallModpackTask.java
// Path: src/main/java/net/technicpack/minecraftcore/install/tasks/CleanupModpackCacheTask.java // public class CleanupModpackCacheTask implements IInstallTask { // private ModpackModel pack; // private Modpack modpack; // // public CleanupModpackCacheTask(ModpackModel pack, Modpack modpack) { // this.pack = pack; // this.modpack = modpack; // } // // @Override // public String getTaskDescription() { // return "Cleaning Modpack Cache"; // } // // @Override // public float getTaskProgress() { // return 0; // } // // @Override // public void runTask(InstallTasksQueue queue) throws IOException { // File[] files = this.pack.getCacheDir().listFiles(); // // if (files == null) { // return; // } // // Set<String> keepFiles = new HashSet<String>(modpack.getMods().size() + 1); // for (Mod mod : modpack.getMods()) { // String version = mod.getVersion(); // // String name; // if (version != null) { // name = mod.getName() + "-" + version + ".zip"; // } else { // name = mod.getName() + ".zip"; // } // // keepFiles.add(name); // } // keepFiles.add("minecraft.jar"); // // for (File file : files) { // String fileName = file.getName(); // if (keepFiles.contains(fileName)) { // continue; // } // FileUtils.deleteQuietly(file); // } // } // }
import net.technicpack.launchercore.install.verifiers.ValidZipFileVerifier; import java.io.File; import java.io.IOException; import net.technicpack.launchercore.exception.CacheDeleteException; import net.technicpack.launchercore.install.ITasksQueue; import net.technicpack.launchercore.install.InstallTasksQueue; import net.technicpack.launchercore.install.tasks.EnsureFileTask; import net.technicpack.launchercore.install.tasks.IInstallTask; import net.technicpack.launchercore.modpacks.ModpackModel; import net.technicpack.minecraftcore.install.tasks.CleanupModpackCacheTask; import net.technicpack.rest.io.Modpack; import net.technicpack.rest.io.Mod; import net.technicpack.launchercore.install.verifiers.IFileVerifier; import net.technicpack.launchercore.install.verifiers.MD5FileVerifier;
if (flansDir.exists()) { deleteMods(flansDir); } File packOutput = this.pack.getInstalledDirectory(); for (Mod mod : modpack.getMods()) { String url = mod.getUrl(); String md5 = mod.getMd5(); String version = mod.getVersion(); String name; if (version != null) { name = mod.getName() + "-" + version + ".zip"; } else { name = mod.getName() + ".zip"; } File cache = new File(this.pack.getCacheDir(), name); IFileVerifier verifier = null; if (md5 != null && !md5.isEmpty()) verifier = new MD5FileVerifier(md5); else verifier = new ValidZipFileVerifier(); checkModQueue.addTask(new EnsureFileTask(cache, verifier, packOutput, url, downloadModQueue, copyModQueue)); }
// Path: src/main/java/net/technicpack/minecraftcore/install/tasks/CleanupModpackCacheTask.java // public class CleanupModpackCacheTask implements IInstallTask { // private ModpackModel pack; // private Modpack modpack; // // public CleanupModpackCacheTask(ModpackModel pack, Modpack modpack) { // this.pack = pack; // this.modpack = modpack; // } // // @Override // public String getTaskDescription() { // return "Cleaning Modpack Cache"; // } // // @Override // public float getTaskProgress() { // return 0; // } // // @Override // public void runTask(InstallTasksQueue queue) throws IOException { // File[] files = this.pack.getCacheDir().listFiles(); // // if (files == null) { // return; // } // // Set<String> keepFiles = new HashSet<String>(modpack.getMods().size() + 1); // for (Mod mod : modpack.getMods()) { // String version = mod.getVersion(); // // String name; // if (version != null) { // name = mod.getName() + "-" + version + ".zip"; // } else { // name = mod.getName() + ".zip"; // } // // keepFiles.add(name); // } // keepFiles.add("minecraft.jar"); // // for (File file : files) { // String fileName = file.getName(); // if (keepFiles.contains(fileName)) { // continue; // } // FileUtils.deleteQuietly(file); // } // } // } // Path: src/main/java/net/technicpack/minecraftcore/install/tasks/InstallModpackTask.java import net.technicpack.launchercore.install.verifiers.ValidZipFileVerifier; import java.io.File; import java.io.IOException; import net.technicpack.launchercore.exception.CacheDeleteException; import net.technicpack.launchercore.install.ITasksQueue; import net.technicpack.launchercore.install.InstallTasksQueue; import net.technicpack.launchercore.install.tasks.EnsureFileTask; import net.technicpack.launchercore.install.tasks.IInstallTask; import net.technicpack.launchercore.modpacks.ModpackModel; import net.technicpack.minecraftcore.install.tasks.CleanupModpackCacheTask; import net.technicpack.rest.io.Modpack; import net.technicpack.rest.io.Mod; import net.technicpack.launchercore.install.verifiers.IFileVerifier; import net.technicpack.launchercore.install.verifiers.MD5FileVerifier; if (flansDir.exists()) { deleteMods(flansDir); } File packOutput = this.pack.getInstalledDirectory(); for (Mod mod : modpack.getMods()) { String url = mod.getUrl(); String md5 = mod.getMd5(); String version = mod.getVersion(); String name; if (version != null) { name = mod.getName() + "-" + version + ".zip"; } else { name = mod.getName() + ".zip"; } File cache = new File(this.pack.getCacheDir(), name); IFileVerifier verifier = null; if (md5 != null && !md5.isEmpty()) verifier = new MD5FileVerifier(md5); else verifier = new ValidZipFileVerifier(); checkModQueue.addTask(new EnsureFileTask(cache, verifier, packOutput, url, downloadModQueue, copyModQueue)); }
copyModQueue.addTask(new CleanupModpackCacheTask(this.pack, modpack));
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/PredicatedArgument.java
// Path: src/main/java/net/technicpack/minecraftcore/launch/ILaunchOptions.java // public interface ILaunchOptions { // String getClientId(); // WindowType getLaunchWindowType(); // int getCustomWidth(); // int getCustomHeight(); // boolean shouldUseStencilBuffer(); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Rule.java // public class Rule { // // public static boolean isAllowable(List<Rule> rules, ILaunchOptions opts) { // for (int i = rules.size() - 1; i >= 0; i--) { // Rule rule = rules.get(i); // if (rule.isApplicable(opts)) { // return !rule.isNegated(); // } // } // return false; // } // // private final boolean negated; // private final List<RuleCondition> conditions = new ArrayList<>(); // // public Rule(JsonObject rule) { // String action = rule.get("action").getAsString(); // switch (action) { // case "allow": // negated = false; // break; // case "disallow": // negated = true; // break; // default: // throw new JsonParseException("Expected rule action, got: " + action); // } // // if (rule.has("os")) { // JsonObject os = rule.get("os").getAsJsonObject(); // conditions.add(new OsCondition( // os.has("name") ? os.get("name").getAsString() : null, // os.has("version") ? os.get("version").getAsString() : null, // os.has("arch") ? os.get("arch").getAsString() : null)); // } // if (rule.has("features")) { // JsonObject features = rule.get("features").getAsJsonObject(); // if (features.has("has_custom_resolution")) { // conditions.add(new CustomResolutionCondition(features.get("has_custom_resolution").getAsBoolean())); // } // if (features.has("is_demo_user")) { // conditions.add(new DemoCondition(features.get("is_demo_user").getAsBoolean())); // } // } // } // // public boolean isApplicable(ILaunchOptions opts) { // if (conditions.isEmpty()) return true; // for (RuleCondition condition : conditions) { // if (!condition.test(opts)) return false; // } // return true; // } // // public boolean isNegated() { // return negated; // } // // public JsonElement serialize() { // JsonObject json = new JsonObject(); // for (RuleCondition condition : conditions) { // condition.serialize(json); // } // json.addProperty("action", negated ? "disallow" : "allow"); // return json; // } // // private static JsonObject getFeatures(JsonObject root) { // if (root.has("features")) return root.get("features").getAsJsonObject(); // JsonObject features = new JsonObject(); // root.add("features", features); // return features; // } // // private interface RuleCondition { // // boolean test(ILaunchOptions opts); // // void serialize(JsonObject root); // // } // // private static class OsCondition implements RuleCondition { // // private final String name; // private final Pattern version; // private final String arch; // // OsCondition(String name, String version, String arch) { // this.name = name; // this.version = version == null ? null : Pattern.compile(version, Pattern.CASE_INSENSITIVE); // this.arch = arch; // } // // @Override // public boolean test(ILaunchOptions opts) { // String os = OperatingSystem.getOperatingSystem().getName(); // String osVersion = System.getProperty("os.version"); // String archProp = System.getProperty("os.arch").toLowerCase(); // return (name == null || name.equalsIgnoreCase(os)) // && (version == null || version.matcher(osVersion).matches()) // && (arch == null || archProp.contains(arch.toLowerCase())); // } // // @Override // public void serialize(JsonObject root) { // JsonObject os = new JsonObject(); // if (name != null) os.addProperty("name", name); // if (version != null) os.addProperty("version", version.pattern()); // if (arch != null) os.addProperty("arch", arch); // root.add("os", os); // } // // } // // private static class CustomResolutionCondition implements RuleCondition { // // private final boolean shouldHaveCustomResolution; // // CustomResolutionCondition(boolean shouldHaveCustomResolution) { // this.shouldHaveCustomResolution = shouldHaveCustomResolution; // } // // @Override // public boolean test(ILaunchOptions opts) { // return opts != null // && (opts.getLaunchWindowType() == WindowType.CUSTOM) == shouldHaveCustomResolution; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("has_custom_resolution", shouldHaveCustomResolution); // } // // } // // private static class DemoCondition implements RuleCondition { // // private final boolean shouldBeDemoUser; // // DemoCondition(boolean shouldBeDemoUser) { // this.shouldBeDemoUser = shouldBeDemoUser; // } // // @Override // public boolean test(ILaunchOptions opts) { // return !shouldBeDemoUser; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("is_demo_user", shouldBeDemoUser); // } // // } // // }
import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.technicpack.minecraftcore.launch.ILaunchOptions; import net.technicpack.minecraftcore.mojang.version.io.Rule; import java.util.List;
package net.technicpack.minecraftcore.mojang.version.io.argument; public class PredicatedArgument extends Argument { private final List<Rule> rules; private final Argument value; public PredicatedArgument(List<Rule> rules, Argument value) { this.rules = rules; this.value = value; } @Override
// Path: src/main/java/net/technicpack/minecraftcore/launch/ILaunchOptions.java // public interface ILaunchOptions { // String getClientId(); // WindowType getLaunchWindowType(); // int getCustomWidth(); // int getCustomHeight(); // boolean shouldUseStencilBuffer(); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Rule.java // public class Rule { // // public static boolean isAllowable(List<Rule> rules, ILaunchOptions opts) { // for (int i = rules.size() - 1; i >= 0; i--) { // Rule rule = rules.get(i); // if (rule.isApplicable(opts)) { // return !rule.isNegated(); // } // } // return false; // } // // private final boolean negated; // private final List<RuleCondition> conditions = new ArrayList<>(); // // public Rule(JsonObject rule) { // String action = rule.get("action").getAsString(); // switch (action) { // case "allow": // negated = false; // break; // case "disallow": // negated = true; // break; // default: // throw new JsonParseException("Expected rule action, got: " + action); // } // // if (rule.has("os")) { // JsonObject os = rule.get("os").getAsJsonObject(); // conditions.add(new OsCondition( // os.has("name") ? os.get("name").getAsString() : null, // os.has("version") ? os.get("version").getAsString() : null, // os.has("arch") ? os.get("arch").getAsString() : null)); // } // if (rule.has("features")) { // JsonObject features = rule.get("features").getAsJsonObject(); // if (features.has("has_custom_resolution")) { // conditions.add(new CustomResolutionCondition(features.get("has_custom_resolution").getAsBoolean())); // } // if (features.has("is_demo_user")) { // conditions.add(new DemoCondition(features.get("is_demo_user").getAsBoolean())); // } // } // } // // public boolean isApplicable(ILaunchOptions opts) { // if (conditions.isEmpty()) return true; // for (RuleCondition condition : conditions) { // if (!condition.test(opts)) return false; // } // return true; // } // // public boolean isNegated() { // return negated; // } // // public JsonElement serialize() { // JsonObject json = new JsonObject(); // for (RuleCondition condition : conditions) { // condition.serialize(json); // } // json.addProperty("action", negated ? "disallow" : "allow"); // return json; // } // // private static JsonObject getFeatures(JsonObject root) { // if (root.has("features")) return root.get("features").getAsJsonObject(); // JsonObject features = new JsonObject(); // root.add("features", features); // return features; // } // // private interface RuleCondition { // // boolean test(ILaunchOptions opts); // // void serialize(JsonObject root); // // } // // private static class OsCondition implements RuleCondition { // // private final String name; // private final Pattern version; // private final String arch; // // OsCondition(String name, String version, String arch) { // this.name = name; // this.version = version == null ? null : Pattern.compile(version, Pattern.CASE_INSENSITIVE); // this.arch = arch; // } // // @Override // public boolean test(ILaunchOptions opts) { // String os = OperatingSystem.getOperatingSystem().getName(); // String osVersion = System.getProperty("os.version"); // String archProp = System.getProperty("os.arch").toLowerCase(); // return (name == null || name.equalsIgnoreCase(os)) // && (version == null || version.matcher(osVersion).matches()) // && (arch == null || archProp.contains(arch.toLowerCase())); // } // // @Override // public void serialize(JsonObject root) { // JsonObject os = new JsonObject(); // if (name != null) os.addProperty("name", name); // if (version != null) os.addProperty("version", version.pattern()); // if (arch != null) os.addProperty("arch", arch); // root.add("os", os); // } // // } // // private static class CustomResolutionCondition implements RuleCondition { // // private final boolean shouldHaveCustomResolution; // // CustomResolutionCondition(boolean shouldHaveCustomResolution) { // this.shouldHaveCustomResolution = shouldHaveCustomResolution; // } // // @Override // public boolean test(ILaunchOptions opts) { // return opts != null // && (opts.getLaunchWindowType() == WindowType.CUSTOM) == shouldHaveCustomResolution; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("has_custom_resolution", shouldHaveCustomResolution); // } // // } // // private static class DemoCondition implements RuleCondition { // // private final boolean shouldBeDemoUser; // // DemoCondition(boolean shouldBeDemoUser) { // this.shouldBeDemoUser = shouldBeDemoUser; // } // // @Override // public boolean test(ILaunchOptions opts) { // return !shouldBeDemoUser; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("is_demo_user", shouldBeDemoUser); // } // // } // // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/PredicatedArgument.java import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.technicpack.minecraftcore.launch.ILaunchOptions; import net.technicpack.minecraftcore.mojang.version.io.Rule; import java.util.List; package net.technicpack.minecraftcore.mojang.version.io.argument; public class PredicatedArgument extends Argument { private final List<Rule> rules; private final Argument value; public PredicatedArgument(List<Rule> rules, Argument value) { this.rules = rules; this.value = value; } @Override
public boolean doesApply(ILaunchOptions opts) {
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentListAdapter.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Rule.java // public class Rule { // // public static boolean isAllowable(List<Rule> rules, ILaunchOptions opts) { // for (int i = rules.size() - 1; i >= 0; i--) { // Rule rule = rules.get(i); // if (rule.isApplicable(opts)) { // return !rule.isNegated(); // } // } // return false; // } // // private final boolean negated; // private final List<RuleCondition> conditions = new ArrayList<>(); // // public Rule(JsonObject rule) { // String action = rule.get("action").getAsString(); // switch (action) { // case "allow": // negated = false; // break; // case "disallow": // negated = true; // break; // default: // throw new JsonParseException("Expected rule action, got: " + action); // } // // if (rule.has("os")) { // JsonObject os = rule.get("os").getAsJsonObject(); // conditions.add(new OsCondition( // os.has("name") ? os.get("name").getAsString() : null, // os.has("version") ? os.get("version").getAsString() : null, // os.has("arch") ? os.get("arch").getAsString() : null)); // } // if (rule.has("features")) { // JsonObject features = rule.get("features").getAsJsonObject(); // if (features.has("has_custom_resolution")) { // conditions.add(new CustomResolutionCondition(features.get("has_custom_resolution").getAsBoolean())); // } // if (features.has("is_demo_user")) { // conditions.add(new DemoCondition(features.get("is_demo_user").getAsBoolean())); // } // } // } // // public boolean isApplicable(ILaunchOptions opts) { // if (conditions.isEmpty()) return true; // for (RuleCondition condition : conditions) { // if (!condition.test(opts)) return false; // } // return true; // } // // public boolean isNegated() { // return negated; // } // // public JsonElement serialize() { // JsonObject json = new JsonObject(); // for (RuleCondition condition : conditions) { // condition.serialize(json); // } // json.addProperty("action", negated ? "disallow" : "allow"); // return json; // } // // private static JsonObject getFeatures(JsonObject root) { // if (root.has("features")) return root.get("features").getAsJsonObject(); // JsonObject features = new JsonObject(); // root.add("features", features); // return features; // } // // private interface RuleCondition { // // boolean test(ILaunchOptions opts); // // void serialize(JsonObject root); // // } // // private static class OsCondition implements RuleCondition { // // private final String name; // private final Pattern version; // private final String arch; // // OsCondition(String name, String version, String arch) { // this.name = name; // this.version = version == null ? null : Pattern.compile(version, Pattern.CASE_INSENSITIVE); // this.arch = arch; // } // // @Override // public boolean test(ILaunchOptions opts) { // String os = OperatingSystem.getOperatingSystem().getName(); // String osVersion = System.getProperty("os.version"); // String archProp = System.getProperty("os.arch").toLowerCase(); // return (name == null || name.equalsIgnoreCase(os)) // && (version == null || version.matcher(osVersion).matches()) // && (arch == null || archProp.contains(arch.toLowerCase())); // } // // @Override // public void serialize(JsonObject root) { // JsonObject os = new JsonObject(); // if (name != null) os.addProperty("name", name); // if (version != null) os.addProperty("version", version.pattern()); // if (arch != null) os.addProperty("arch", arch); // root.add("os", os); // } // // } // // private static class CustomResolutionCondition implements RuleCondition { // // private final boolean shouldHaveCustomResolution; // // CustomResolutionCondition(boolean shouldHaveCustomResolution) { // this.shouldHaveCustomResolution = shouldHaveCustomResolution; // } // // @Override // public boolean test(ILaunchOptions opts) { // return opts != null // && (opts.getLaunchWindowType() == WindowType.CUSTOM) == shouldHaveCustomResolution; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("has_custom_resolution", shouldHaveCustomResolution); // } // // } // // private static class DemoCondition implements RuleCondition { // // private final boolean shouldBeDemoUser; // // DemoCondition(boolean shouldBeDemoUser) { // this.shouldBeDemoUser = shouldBeDemoUser; // } // // @Override // public boolean test(ILaunchOptions opts) { // return !shouldBeDemoUser; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("is_demo_user", shouldBeDemoUser); // } // // } // // }
import com.google.gson.*; import net.technicpack.minecraftcore.mojang.version.io.Rule; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package net.technicpack.minecraftcore.mojang.version.io.argument; public class ArgumentListAdapter implements JsonSerializer<ArgumentList>, JsonDeserializer<ArgumentList> { @Override public ArgumentList deserialize(JsonElement json, Type type, JsonDeserializationContext ctx) throws JsonParseException { if (!json.isJsonArray()) throw new JsonParseException("Expected argument array, got: " + json); ArgumentList.Builder argsBuilder = new ArgumentList.Builder(); for (JsonElement arg : json.getAsJsonArray()) { if (arg.isJsonObject()) { JsonObject argObj = arg.getAsJsonObject(); JsonArray rules = argObj.get("rules").getAsJsonArray();
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Rule.java // public class Rule { // // public static boolean isAllowable(List<Rule> rules, ILaunchOptions opts) { // for (int i = rules.size() - 1; i >= 0; i--) { // Rule rule = rules.get(i); // if (rule.isApplicable(opts)) { // return !rule.isNegated(); // } // } // return false; // } // // private final boolean negated; // private final List<RuleCondition> conditions = new ArrayList<>(); // // public Rule(JsonObject rule) { // String action = rule.get("action").getAsString(); // switch (action) { // case "allow": // negated = false; // break; // case "disallow": // negated = true; // break; // default: // throw new JsonParseException("Expected rule action, got: " + action); // } // // if (rule.has("os")) { // JsonObject os = rule.get("os").getAsJsonObject(); // conditions.add(new OsCondition( // os.has("name") ? os.get("name").getAsString() : null, // os.has("version") ? os.get("version").getAsString() : null, // os.has("arch") ? os.get("arch").getAsString() : null)); // } // if (rule.has("features")) { // JsonObject features = rule.get("features").getAsJsonObject(); // if (features.has("has_custom_resolution")) { // conditions.add(new CustomResolutionCondition(features.get("has_custom_resolution").getAsBoolean())); // } // if (features.has("is_demo_user")) { // conditions.add(new DemoCondition(features.get("is_demo_user").getAsBoolean())); // } // } // } // // public boolean isApplicable(ILaunchOptions opts) { // if (conditions.isEmpty()) return true; // for (RuleCondition condition : conditions) { // if (!condition.test(opts)) return false; // } // return true; // } // // public boolean isNegated() { // return negated; // } // // public JsonElement serialize() { // JsonObject json = new JsonObject(); // for (RuleCondition condition : conditions) { // condition.serialize(json); // } // json.addProperty("action", negated ? "disallow" : "allow"); // return json; // } // // private static JsonObject getFeatures(JsonObject root) { // if (root.has("features")) return root.get("features").getAsJsonObject(); // JsonObject features = new JsonObject(); // root.add("features", features); // return features; // } // // private interface RuleCondition { // // boolean test(ILaunchOptions opts); // // void serialize(JsonObject root); // // } // // private static class OsCondition implements RuleCondition { // // private final String name; // private final Pattern version; // private final String arch; // // OsCondition(String name, String version, String arch) { // this.name = name; // this.version = version == null ? null : Pattern.compile(version, Pattern.CASE_INSENSITIVE); // this.arch = arch; // } // // @Override // public boolean test(ILaunchOptions opts) { // String os = OperatingSystem.getOperatingSystem().getName(); // String osVersion = System.getProperty("os.version"); // String archProp = System.getProperty("os.arch").toLowerCase(); // return (name == null || name.equalsIgnoreCase(os)) // && (version == null || version.matcher(osVersion).matches()) // && (arch == null || archProp.contains(arch.toLowerCase())); // } // // @Override // public void serialize(JsonObject root) { // JsonObject os = new JsonObject(); // if (name != null) os.addProperty("name", name); // if (version != null) os.addProperty("version", version.pattern()); // if (arch != null) os.addProperty("arch", arch); // root.add("os", os); // } // // } // // private static class CustomResolutionCondition implements RuleCondition { // // private final boolean shouldHaveCustomResolution; // // CustomResolutionCondition(boolean shouldHaveCustomResolution) { // this.shouldHaveCustomResolution = shouldHaveCustomResolution; // } // // @Override // public boolean test(ILaunchOptions opts) { // return opts != null // && (opts.getLaunchWindowType() == WindowType.CUSTOM) == shouldHaveCustomResolution; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("has_custom_resolution", shouldHaveCustomResolution); // } // // } // // private static class DemoCondition implements RuleCondition { // // private final boolean shouldBeDemoUser; // // DemoCondition(boolean shouldBeDemoUser) { // this.shouldBeDemoUser = shouldBeDemoUser; // } // // @Override // public boolean test(ILaunchOptions opts) { // return !shouldBeDemoUser; // } // // @Override // public void serialize(JsonObject root) { // getFeatures(root).addProperty("is_demo_user", shouldBeDemoUser); // } // // } // // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentListAdapter.java import com.google.gson.*; import net.technicpack.minecraftcore.mojang.version.io.Rule; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; package net.technicpack.minecraftcore.mojang.version.io.argument; public class ArgumentListAdapter implements JsonSerializer<ArgumentList>, JsonDeserializer<ArgumentList> { @Override public ArgumentList deserialize(JsonElement json, Type type, JsonDeserializationContext ctx) throws JsonParseException { if (!json.isJsonArray()) throw new JsonParseException("Expected argument array, got: " + json); ArgumentList.Builder argsBuilder = new ArgumentList.Builder(); for (JsonElement arg : json.getAsJsonArray()) { if (arg.isJsonObject()) { JsonObject argObj = arg.getAsJsonObject(); JsonArray rules = argObj.get("rules").getAsJsonArray();
List<Rule> predicates = new ArrayList<>();
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/CompleteVersion.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // }
import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; import java.util.ArrayList; import java.util.Date; import java.util.List;
public ReleaseType getType() { return type; } @Override public void setType(ReleaseType type) { this.type = type; } @Override public Date getUpdatedTime() { return time; } @Override public void setUpdatedTime(Date updatedTime) { this.time = updatedTime; } @Override public Date getReleaseTime() { return releaseTime; } @Override public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } @Override
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/CompleteVersion.java import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; import java.util.ArrayList; import java.util.Date; import java.util.List; public ReleaseType getType() { return type; } @Override public void setType(ReleaseType type) { this.type = type; } @Override public Date getUpdatedTime() { return time; } @Override public void setUpdatedTime(Date updatedTime) { this.time = updatedTime; } @Override public Date getReleaseTime() { return releaseTime; } @Override public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } @Override
public ArgumentList getMinecraftArguments() {
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/chain/ChainVersionBuilder.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersionBuilder.java // public interface MojangVersionBuilder { // MojangVersion buildVersionFromKey(String key) throws IOException, InterruptedException; // }
import java.io.IOException; import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.MojangVersionBuilder;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version.chain; public class ChainVersionBuilder implements MojangVersionBuilder { private MojangVersionBuilder primaryVersionBuilder; private MojangVersionBuilder chainedVersionBuilder; public ChainVersionBuilder(MojangVersionBuilder primaryVersionBuilder, MojangVersionBuilder chainedVersionBuilder) { this.primaryVersionBuilder = primaryVersionBuilder; this.chainedVersionBuilder = chainedVersionBuilder; }
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersionBuilder.java // public interface MojangVersionBuilder { // MojangVersion buildVersionFromKey(String key) throws IOException, InterruptedException; // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/chain/ChainVersionBuilder.java import java.io.IOException; import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.MojangVersionBuilder; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version.chain; public class ChainVersionBuilder implements MojangVersionBuilder { private MojangVersionBuilder primaryVersionBuilder; private MojangVersionBuilder chainedVersionBuilder; public ChainVersionBuilder(MojangVersionBuilder primaryVersionBuilder, MojangVersionBuilder chainedVersionBuilder) { this.primaryVersionBuilder = primaryVersionBuilder; this.chainedVersionBuilder = chainedVersionBuilder; }
public MojangVersion buildVersionFromKey(String key) throws InterruptedException, IOException {
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/Rule.java
// Path: src/main/java/net/technicpack/minecraftcore/launch/ILaunchOptions.java // public interface ILaunchOptions { // String getClientId(); // WindowType getLaunchWindowType(); // int getCustomWidth(); // int getCustomHeight(); // boolean shouldUseStencilBuffer(); // } // // Path: src/main/java/net/technicpack/minecraftcore/launch/WindowType.java // public enum WindowType { // DEFAULT, // FULLSCREEN, // CUSTOM // }
import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import net.technicpack.minecraftcore.launch.ILaunchOptions; import net.technicpack.minecraftcore.launch.WindowType; import net.technicpack.utilslib.OperatingSystem; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern;
String os = OperatingSystem.getOperatingSystem().getName(); String osVersion = System.getProperty("os.version"); String archProp = System.getProperty("os.arch").toLowerCase(); return (name == null || name.equalsIgnoreCase(os)) && (version == null || version.matcher(osVersion).matches()) && (arch == null || archProp.contains(arch.toLowerCase())); } @Override public void serialize(JsonObject root) { JsonObject os = new JsonObject(); if (name != null) os.addProperty("name", name); if (version != null) os.addProperty("version", version.pattern()); if (arch != null) os.addProperty("arch", arch); root.add("os", os); } } private static class CustomResolutionCondition implements RuleCondition { private final boolean shouldHaveCustomResolution; CustomResolutionCondition(boolean shouldHaveCustomResolution) { this.shouldHaveCustomResolution = shouldHaveCustomResolution; } @Override public boolean test(ILaunchOptions opts) { return opts != null
// Path: src/main/java/net/technicpack/minecraftcore/launch/ILaunchOptions.java // public interface ILaunchOptions { // String getClientId(); // WindowType getLaunchWindowType(); // int getCustomWidth(); // int getCustomHeight(); // boolean shouldUseStencilBuffer(); // } // // Path: src/main/java/net/technicpack/minecraftcore/launch/WindowType.java // public enum WindowType { // DEFAULT, // FULLSCREEN, // CUSTOM // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/Rule.java import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import net.technicpack.minecraftcore.launch.ILaunchOptions; import net.technicpack.minecraftcore.launch.WindowType; import net.technicpack.utilslib.OperatingSystem; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; String os = OperatingSystem.getOperatingSystem().getName(); String osVersion = System.getProperty("os.version"); String archProp = System.getProperty("os.arch").toLowerCase(); return (name == null || name.equalsIgnoreCase(os)) && (version == null || version.matcher(osVersion).matches()) && (arch == null || archProp.contains(arch.toLowerCase())); } @Override public void serialize(JsonObject root) { JsonObject os = new JsonObject(); if (name != null) os.addProperty("name", name); if (version != null) os.addProperty("version", version.pattern()); if (arch != null) os.addProperty("arch", arch); root.add("os", os); } } private static class CustomResolutionCondition implements RuleCondition { private final boolean shouldHaveCustomResolution; CustomResolutionCondition(boolean shouldHaveCustomResolution) { this.shouldHaveCustomResolution = shouldHaveCustomResolution; } @Override public boolean test(ILaunchOptions opts) { return opts != null
&& (opts.getLaunchWindowType() == WindowType.CUSTOM) == shouldHaveCustomResolution;
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/list/VersionList.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/list/LatestEntry.java // public class LatestEntry { // private String snapshot; // private String release; // // public String getSnapshot() { // return snapshot; // } // // public String getRelease() { // return release; // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/list/VersionEntry.java // public class VersionEntry { // private String id; // private Date time; // private Date releaseTime; // private ReleaseType type; // // public String getId() { // return id; // } // // public Date getTime() { // return time; // } // // public Date getReleaseTime() { // return releaseTime; // } // // public ReleaseType getType() { // return type; // } // }
import java.util.List; import net.technicpack.minecraftcore.mojang.version.list.LatestEntry; import net.technicpack.minecraftcore.mojang.version.list.VersionEntry;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version.list; public class VersionList { private List<VersionEntry> versions;
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/list/LatestEntry.java // public class LatestEntry { // private String snapshot; // private String release; // // public String getSnapshot() { // return snapshot; // } // // public String getRelease() { // return release; // } // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/list/VersionEntry.java // public class VersionEntry { // private String id; // private Date time; // private Date releaseTime; // private ReleaseType type; // // public String getId() { // return id; // } // // public Date getTime() { // return time; // } // // public Date getReleaseTime() { // return releaseTime; // } // // public ReleaseType getType() { // return type; // } // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/list/VersionList.java import java.util.List; import net.technicpack.minecraftcore.mojang.version.list.LatestEntry; import net.technicpack.minecraftcore.mojang.version.list.VersionEntry; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version.list; public class VersionList { private List<VersionEntry> versions;
private LatestEntry latest;
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/chain/VersionChain.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // }
import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.io.*; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; import java.util.Date; import java.util.LinkedList; import java.util.List;
public ReleaseType getType() { return chain.get(0).getType(); } @Override public void setType(ReleaseType releaseType) { chain.get(0).setType(releaseType); } @Override public Date getUpdatedTime() { return chain.get(0).getUpdatedTime(); } @Override public void setUpdatedTime(Date updatedTime) { chain.get(0).setUpdatedTime(updatedTime); } @Override public Date getReleaseTime() { return chain.get(0).getReleaseTime(); } @Override public void setReleaseTime(Date releaseTime) { chain.get(0).setReleaseTime(releaseTime); } @Override
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/chain/VersionChain.java import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.io.*; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; import java.util.Date; import java.util.LinkedList; import java.util.List; public ReleaseType getType() { return chain.get(0).getType(); } @Override public void setType(ReleaseType releaseType) { chain.get(0).setType(releaseType); } @Override public Date getUpdatedTime() { return chain.get(0).getUpdatedTime(); } @Override public void setUpdatedTime(Date updatedTime) { chain.get(0).setUpdatedTime(updatedTime); } @Override public Date getReleaseTime() { return chain.get(0).getReleaseTime(); } @Override public void setReleaseTime(Date releaseTime) { chain.get(0).setReleaseTime(releaseTime); } @Override
public ArgumentList getMinecraftArguments() {
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/CompleteVersionParser.java
// Path: src/main/java/net/technicpack/minecraftcore/MojangUtils.java // public class MojangUtils { // public static final String baseURL = "https://s3.amazonaws.com/Minecraft.Download/"; // public static final String assetsIndexes = baseURL + "indexes/"; // public static final String versions = baseURL + "versions/"; // public static final String assets = "http://resources.download.minecraft.net/"; // public static final String versionList = versions + "versions.json"; // // public static String getVersionJson(String version) { // return versions + version + "/" + version + ".json"; // } // // public static String getVersionDownload(String version) { // return versions + version + "/" + version + ".jar"; // } // // public static String getAssetsIndex(String assetsKey) { // return assetsIndexes + assetsKey + ".json"; // } // // public static String getResourceUrl(String hash) { // return assets + hash.substring(0, 2) + "/" + hash; // } // // private static final Gson gson; // private static final Gson uglyGson; // private static final NavigableMap<Integer, Class<? extends MojangVersion>> versionJsonVersions; // // static { // GsonBuilder builder = new GsonBuilder(); // builder.registerTypeAdapterFactory(new LowerCaseEnumTypeAdapterFactory()); // builder.registerTypeAdapter(Date.class, new DateTypeAdapter()); // builder.registerTypeAdapter(UserProperties.class, new UserPropertiesAdapter()); // builder.registerTypeAdapter(ArgumentList.class, new ArgumentListAdapter()); // builder.registerTypeAdapter(Rule.class, new RuleAdapter()); // builder.enableComplexMapKeySerialization(); // uglyGson = builder.create(); // // builder.setPrettyPrinting(); // gson = builder.create(); // // versionJsonVersions = new TreeMap<Integer, Class<? extends MojangVersion>>(); // versionJsonVersions.put(0, CompleteVersion.class); // versionJsonVersions.put(21, CompleteVersionV21.class); // } // // public static Gson getGson() { // return gson; // } // // public static Gson getUglyGson() { // return uglyGson; // } // // public static void copyMinecraftJar(File minecraft, File output) throws IOException { // String[] security = { "MOJANG_C.DSA", // "MOJANG_C.SF", // "CODESIGN.RSA", // "CODESIGN.SF" }; // JarFile jarFile = new JarFile(minecraft); // try { // String fileName = jarFile.getName(); // String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); // // JarOutputStream jos = new JarOutputStream(new FileOutputStream(output)); // Enumeration<JarEntry> entries = jarFile.entries(); // // while (entries.hasMoreElements()) { // JarEntry entry = entries.nextElement(); // if (containsAny(entry.getName(), security)) { // continue; // } // InputStream is = jarFile.getInputStream(entry); // // //jos.putNextEntry(entry); // //create a new entry to avoid ZipException: invalid entry compressed size // jos.putNextEntry(new JarEntry(entry.getName())); // byte[] buffer = new byte[4096]; // int bytesRead = 0; // while ((bytesRead = is.read(buffer)) != -1) { // jos.write(buffer, 0, bytesRead); // } // is.close(); // jos.flush(); // jos.closeEntry(); // } // jos.close(); // } finally { // jarFile.close(); // } // // } // // private static boolean containsAny(String inputString, String[] contains) { // for (String string : contains) { // if (inputString.contains(string)) { // return true; // } // } // return false; // } // // public static MojangVersion parseVersionJson(String json) { // JsonObject root = JsonParser.parseString(json).getAsJsonObject(); // Class<? extends MojangVersion> versionJsonType; // if (root.has("minimumLauncherVersion")) { // int minLauncherVersion = root.get("minimumLauncherVersion").getAsInt(); // Map.Entry<Integer, Class<? extends MojangVersion>> entry = versionJsonVersions.floorEntry(minLauncherVersion); // if (entry == null) { // throw new IllegalArgumentException("Unsupported minimumLauncherVersion: " + minLauncherVersion); // } // versionJsonType = entry.getValue(); // } else { // fallback: check if "arguments" key exists since only 1.13+ should have it // versionJsonType = root.has("arguments") ? CompleteVersionV21.class : CompleteVersion.class; // } // return getGson().fromJson(root, versionJsonType); // } // // public static boolean isLegacyVersion(String version) { // final String[] versionParts = version.split("[.-]", 3); // // return Integer.valueOf(versionParts[0]) == 1 && Integer.valueOf(versionParts[1]) < 6; // } // }
import net.technicpack.launchercore.install.IVersionDataParser; import net.technicpack.minecraftcore.MojangUtils;
/* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version; public class CompleteVersionParser implements IVersionDataParser<MojangVersion> { @Override public MojangVersion parseVersionData(String data) {
// Path: src/main/java/net/technicpack/minecraftcore/MojangUtils.java // public class MojangUtils { // public static final String baseURL = "https://s3.amazonaws.com/Minecraft.Download/"; // public static final String assetsIndexes = baseURL + "indexes/"; // public static final String versions = baseURL + "versions/"; // public static final String assets = "http://resources.download.minecraft.net/"; // public static final String versionList = versions + "versions.json"; // // public static String getVersionJson(String version) { // return versions + version + "/" + version + ".json"; // } // // public static String getVersionDownload(String version) { // return versions + version + "/" + version + ".jar"; // } // // public static String getAssetsIndex(String assetsKey) { // return assetsIndexes + assetsKey + ".json"; // } // // public static String getResourceUrl(String hash) { // return assets + hash.substring(0, 2) + "/" + hash; // } // // private static final Gson gson; // private static final Gson uglyGson; // private static final NavigableMap<Integer, Class<? extends MojangVersion>> versionJsonVersions; // // static { // GsonBuilder builder = new GsonBuilder(); // builder.registerTypeAdapterFactory(new LowerCaseEnumTypeAdapterFactory()); // builder.registerTypeAdapter(Date.class, new DateTypeAdapter()); // builder.registerTypeAdapter(UserProperties.class, new UserPropertiesAdapter()); // builder.registerTypeAdapter(ArgumentList.class, new ArgumentListAdapter()); // builder.registerTypeAdapter(Rule.class, new RuleAdapter()); // builder.enableComplexMapKeySerialization(); // uglyGson = builder.create(); // // builder.setPrettyPrinting(); // gson = builder.create(); // // versionJsonVersions = new TreeMap<Integer, Class<? extends MojangVersion>>(); // versionJsonVersions.put(0, CompleteVersion.class); // versionJsonVersions.put(21, CompleteVersionV21.class); // } // // public static Gson getGson() { // return gson; // } // // public static Gson getUglyGson() { // return uglyGson; // } // // public static void copyMinecraftJar(File minecraft, File output) throws IOException { // String[] security = { "MOJANG_C.DSA", // "MOJANG_C.SF", // "CODESIGN.RSA", // "CODESIGN.SF" }; // JarFile jarFile = new JarFile(minecraft); // try { // String fileName = jarFile.getName(); // String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); // // JarOutputStream jos = new JarOutputStream(new FileOutputStream(output)); // Enumeration<JarEntry> entries = jarFile.entries(); // // while (entries.hasMoreElements()) { // JarEntry entry = entries.nextElement(); // if (containsAny(entry.getName(), security)) { // continue; // } // InputStream is = jarFile.getInputStream(entry); // // //jos.putNextEntry(entry); // //create a new entry to avoid ZipException: invalid entry compressed size // jos.putNextEntry(new JarEntry(entry.getName())); // byte[] buffer = new byte[4096]; // int bytesRead = 0; // while ((bytesRead = is.read(buffer)) != -1) { // jos.write(buffer, 0, bytesRead); // } // is.close(); // jos.flush(); // jos.closeEntry(); // } // jos.close(); // } finally { // jarFile.close(); // } // // } // // private static boolean containsAny(String inputString, String[] contains) { // for (String string : contains) { // if (inputString.contains(string)) { // return true; // } // } // return false; // } // // public static MojangVersion parseVersionJson(String json) { // JsonObject root = JsonParser.parseString(json).getAsJsonObject(); // Class<? extends MojangVersion> versionJsonType; // if (root.has("minimumLauncherVersion")) { // int minLauncherVersion = root.get("minimumLauncherVersion").getAsInt(); // Map.Entry<Integer, Class<? extends MojangVersion>> entry = versionJsonVersions.floorEntry(minLauncherVersion); // if (entry == null) { // throw new IllegalArgumentException("Unsupported minimumLauncherVersion: " + minLauncherVersion); // } // versionJsonType = entry.getValue(); // } else { // fallback: check if "arguments" key exists since only 1.13+ should have it // versionJsonType = root.has("arguments") ? CompleteVersionV21.class : CompleteVersion.class; // } // return getGson().fromJson(root, versionJsonType); // } // // public static boolean isLegacyVersion(String version) { // final String[] versionParts = version.split("[.-]", 3); // // return Integer.valueOf(versionParts[0]) == 1 && Integer.valueOf(versionParts[1]) < 6; // } // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/CompleteVersionParser.java import net.technicpack.launchercore.install.IVersionDataParser; import net.technicpack.minecraftcore.MojangUtils; /* * This file is part of Technic Minecraft Core. * Copyright ©2015 Syndicate, LLC * * Technic Minecraft Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Technic Minecraft Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, * as well as a copy of the GNU Lesser General Public License, * along with Technic Minecraft Core. If not, see <http://www.gnu.org/licenses/>. */ package net.technicpack.minecraftcore.mojang.version; public class CompleteVersionParser implements IVersionDataParser<MojangVersion> { @Override public MojangVersion parseVersionData(String data) {
return MojangUtils.parseVersionJson(data);
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/CompleteVersionV21.java
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // }
import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; import java.util.ArrayList; import java.util.Date; import java.util.List;
public ReleaseType getType() { return type; } @Override public void setType(ReleaseType type) { this.type = type; } @Override public Date getUpdatedTime() { return time; } @Override public void setUpdatedTime(Date updatedTime) { this.time = updatedTime; } @Override public Date getReleaseTime() { return releaseTime; } @Override public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } @Override
// Path: src/main/java/net/technicpack/minecraftcore/mojang/version/MojangVersion.java // public interface MojangVersion { // // public String getId(); // // public ReleaseType getType(); // // public void setType(ReleaseType releaseType); // // public Date getUpdatedTime(); // // public void setUpdatedTime(Date updatedTime); // // public Date getReleaseTime(); // // public void setReleaseTime(Date releaseTime); // // public ArgumentList getMinecraftArguments(); // // public ArgumentList getJavaArguments(); // // public List<Library> getLibraries(); // // public List<Library> getLibrariesForOS(); // // public String getMainClass(); // // public void setMainClass(String mainClass); // // public int getMinimumLauncherVersion(); // // public String getIncompatibilityReason(); // // public List<Rule> getRules(); // // String getAssetsKey(); // // AssetIndex getAssetIndex(); // // GameDownloads getDownloads(); // // public String getJarKey(); // // public String getParentVersion(); // // public boolean getAreAssetsVirtual(); // // public void setAreAssetsVirtual(boolean areAssetsVirtual); // // public void addLibrary(Library library); // } // // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/argument/ArgumentList.java // public class ArgumentList { // // private final List<Argument> args; // // private ArgumentList(List<Argument> args) { // this.args = Collections.unmodifiableList(args); // } // // public static ArgumentList fromString(String args) { // if (args == null) return null; // Builder argsBuilder = new Builder(); // for (String arg : args.split(" ")) argsBuilder.addArgument(Argument.literal(arg)); // return argsBuilder.build(); // } // // public List<Argument> getArguments() { // return args; // } // // public List<String> resolve(ILaunchOptions opts, StringSubstitutor derefs) { // List<String> resolved = new ArrayList<>(); // if (derefs == null) derefs = new StringSubstitutor(); // for (Argument arg : args) { // if (arg.doesApply(opts)) { // for (String argStr : arg.getArgStrings()) { // resolved.add(derefs.replace(argStr)); // } // } // } // return resolved; // } // // public JsonElement serialize() { // JsonArray json = new JsonArray(); // for (Argument arg : args) json.add(arg.serialize()); // return json; // } // // public static class Builder { // // private final List<Argument> args = new ArrayList<>(); // // public void addArgument(Argument arg) { // args.add(arg); // } // // public ArgumentList build() { // return new ArgumentList(args); // } // // } // // } // Path: src/main/java/net/technicpack/minecraftcore/mojang/version/io/CompleteVersionV21.java import net.technicpack.minecraftcore.mojang.version.MojangVersion; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; import java.util.ArrayList; import java.util.Date; import java.util.List; public ReleaseType getType() { return type; } @Override public void setType(ReleaseType type) { this.type = type; } @Override public Date getUpdatedTime() { return time; } @Override public void setUpdatedTime(Date updatedTime) { this.time = updatedTime; } @Override public Date getReleaseTime() { return releaseTime; } @Override public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } @Override
public ArgumentList getMinecraftArguments() {
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClient.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java // public class InitialData { // public Boolean enabled; // true // public String title; // 'Rocket.Chat' // public String color; // '#C1272D' // public Boolean registrationForm; // true // public User visitor; // undefined // public List<Trigger> triggers; // [] // public List<Department> departments; // [] // public Boolean allowSwitchingDepartments; // true // public Boolean online; // true // public String offlineColor; // '#666666' // public String offlineMessage; // 'We are not online right now. Please leave us a message:' // public String offlineSuccessMessage; // '' // public String offlineUnavailableMessage; // '' // public Boolean displayOfflineForm; // true // public Boolean videoCall; // false // public String offlineTitle; // 'Leave a message' // public String language; // 'en' // public Boolean transcript; // false // public String transcriptMessage; // 'Would you like a copy of this chat emailed?' // public String conversationFinishedMessage; // 'Conversation finished' // public Boolean nameFieldRegistrationForm; // true // public Boolean emailFieldRegistrationForm; // true // // @Override // public String toString() { // return "InitialData{" + // "enabled=" + enabled + // ", title='" + title + '\'' + // ", color='" + color + '\'' + // ", registrationForm=" + registrationForm + // ", visitor=" + visitor + // ", triggers=" + triggers + // ", departments=" + departments + // ", allowSwitchingDepartments=" + allowSwitchingDepartments + // ", online=" + online + // ", offlineColor='" + offlineColor + '\'' + // ", offlineMessage='" + offlineMessage + '\'' + // ", offlineSuccessMessage='" + offlineSuccessMessage + '\'' + // ", offlineUnavailableMessage='" + offlineUnavailableMessage + '\'' + // ", displayOfflineForm=" + displayOfflineForm + // ", videoCall=" + videoCall + // ", offlineTitle='" + offlineTitle + '\'' + // ", language='" + language + '\'' + // ", transcript=" + transcript + // ", transcriptMessage='" + transcriptMessage + '\'' + // ", conversationFinishedMessage='" + conversationFinishedMessage + '\'' + // ", nameFieldRegistrationForm=" + nameFieldRegistrationForm + // ", emailFieldRegistrationForm=" + emailFieldRegistrationForm + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java // public class LiveChatMessage { // public String msg; // public User u; // public String rid; // public String _id; // public String token; // public String alias; // public DateWrapper _updatedAt; // public DateWrapper ts; // public Boolean newRoom; // public Boolean showConnecting; // // @Override // public String toString() { // return "LiveChatMessage{" + // "msg='" + msg + '\'' + // ", u=" + u + // ", rid='" + rid + '\'' + // ", _id='" + _id + '\'' + // ", token='" + token + '\'' + // ", alias='" + alias + '\'' + // ", _updatedAt=" + _updatedAt + // ", ts=" + ts + // ", newRoom=" + newRoom + // ", showConnecting=" + showConnecting + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/RegisterGuest.java // public class RegisterGuest { // public String userId; // public Visitor visitor; // // @Override // public String toString() { // return "RegisterGuest{" + // "userId='" + userId + '\'' + // ", visitor=" + visitor + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.request.*; import com.github.daniel_sc.rocketchat.modern_client.response.*; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.LiveChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger;
public CompletableFuture<ChatMessage> sendMessage(String msg, String rid) { return sendMessageExtendedParams(msg, rid, null, null, null, null, null); } public CompletableFuture<ChatMessage> sendMessageExtendedParams(String msg, String rid, String alias, String avatar, String emoji, Boolean groupable, List<Attachment> attachments) { MethodRequest request = new MethodRequest("sendMessage", SendMessageParam.forSendMessage(msg, rid, alias, avatar, emoji, groupable, attachments)); return send(request, failOnError(r -> { if (r.result == null) { throw new IllegalStateException("Message result is empty!"); } return GSON.fromJson(r.result, ChatMessage.class); })); } public CompletableFuture<ChatMessage> updateMessage(String msg, String _id) { return updateMessageWithAttachments(msg, _id, null, null); } public CompletableFuture<ChatMessage> updateMessageWithAttachments(String msg, String _id, Boolean groupable, List<Attachment> attachments) { MethodRequest request = new MethodRequest("updateMessage", SendMessageParam.forUpdate(_id, msg, null, null, null, null, groupable, attachments)); return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), ChatMessage.class))); } public CompletableFuture<List<Permission>> getPermissions() { return send(new MethodRequest("permissions/get"), failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), new TypeToken<List<Permission>>() { }.getType()))); }
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java // public class InitialData { // public Boolean enabled; // true // public String title; // 'Rocket.Chat' // public String color; // '#C1272D' // public Boolean registrationForm; // true // public User visitor; // undefined // public List<Trigger> triggers; // [] // public List<Department> departments; // [] // public Boolean allowSwitchingDepartments; // true // public Boolean online; // true // public String offlineColor; // '#666666' // public String offlineMessage; // 'We are not online right now. Please leave us a message:' // public String offlineSuccessMessage; // '' // public String offlineUnavailableMessage; // '' // public Boolean displayOfflineForm; // true // public Boolean videoCall; // false // public String offlineTitle; // 'Leave a message' // public String language; // 'en' // public Boolean transcript; // false // public String transcriptMessage; // 'Would you like a copy of this chat emailed?' // public String conversationFinishedMessage; // 'Conversation finished' // public Boolean nameFieldRegistrationForm; // true // public Boolean emailFieldRegistrationForm; // true // // @Override // public String toString() { // return "InitialData{" + // "enabled=" + enabled + // ", title='" + title + '\'' + // ", color='" + color + '\'' + // ", registrationForm=" + registrationForm + // ", visitor=" + visitor + // ", triggers=" + triggers + // ", departments=" + departments + // ", allowSwitchingDepartments=" + allowSwitchingDepartments + // ", online=" + online + // ", offlineColor='" + offlineColor + '\'' + // ", offlineMessage='" + offlineMessage + '\'' + // ", offlineSuccessMessage='" + offlineSuccessMessage + '\'' + // ", offlineUnavailableMessage='" + offlineUnavailableMessage + '\'' + // ", displayOfflineForm=" + displayOfflineForm + // ", videoCall=" + videoCall + // ", offlineTitle='" + offlineTitle + '\'' + // ", language='" + language + '\'' + // ", transcript=" + transcript + // ", transcriptMessage='" + transcriptMessage + '\'' + // ", conversationFinishedMessage='" + conversationFinishedMessage + '\'' + // ", nameFieldRegistrationForm=" + nameFieldRegistrationForm + // ", emailFieldRegistrationForm=" + emailFieldRegistrationForm + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java // public class LiveChatMessage { // public String msg; // public User u; // public String rid; // public String _id; // public String token; // public String alias; // public DateWrapper _updatedAt; // public DateWrapper ts; // public Boolean newRoom; // public Boolean showConnecting; // // @Override // public String toString() { // return "LiveChatMessage{" + // "msg='" + msg + '\'' + // ", u=" + u + // ", rid='" + rid + '\'' + // ", _id='" + _id + '\'' + // ", token='" + token + '\'' + // ", alias='" + alias + '\'' + // ", _updatedAt=" + _updatedAt + // ", ts=" + ts + // ", newRoom=" + newRoom + // ", showConnecting=" + showConnecting + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/RegisterGuest.java // public class RegisterGuest { // public String userId; // public Visitor visitor; // // @Override // public String toString() { // return "RegisterGuest{" + // "userId='" + userId + '\'' + // ", visitor=" + visitor + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClient.java import com.github.daniel_sc.rocketchat.modern_client.request.*; import com.github.daniel_sc.rocketchat.modern_client.response.*; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.LiveChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; public CompletableFuture<ChatMessage> sendMessage(String msg, String rid) { return sendMessageExtendedParams(msg, rid, null, null, null, null, null); } public CompletableFuture<ChatMessage> sendMessageExtendedParams(String msg, String rid, String alias, String avatar, String emoji, Boolean groupable, List<Attachment> attachments) { MethodRequest request = new MethodRequest("sendMessage", SendMessageParam.forSendMessage(msg, rid, alias, avatar, emoji, groupable, attachments)); return send(request, failOnError(r -> { if (r.result == null) { throw new IllegalStateException("Message result is empty!"); } return GSON.fromJson(r.result, ChatMessage.class); })); } public CompletableFuture<ChatMessage> updateMessage(String msg, String _id) { return updateMessageWithAttachments(msg, _id, null, null); } public CompletableFuture<ChatMessage> updateMessageWithAttachments(String msg, String _id, Boolean groupable, List<Attachment> attachments) { MethodRequest request = new MethodRequest("updateMessage", SendMessageParam.forUpdate(_id, msg, null, null, null, null, groupable, attachments)); return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), ChatMessage.class))); } public CompletableFuture<List<Permission>> getPermissions() { return send(new MethodRequest("permissions/get"), failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), new TypeToken<List<Permission>>() { }.getType()))); }
public CompletableFuture<InitialData> livechatGetInitialData(String visitorToken) {
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClient.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java // public class InitialData { // public Boolean enabled; // true // public String title; // 'Rocket.Chat' // public String color; // '#C1272D' // public Boolean registrationForm; // true // public User visitor; // undefined // public List<Trigger> triggers; // [] // public List<Department> departments; // [] // public Boolean allowSwitchingDepartments; // true // public Boolean online; // true // public String offlineColor; // '#666666' // public String offlineMessage; // 'We are not online right now. Please leave us a message:' // public String offlineSuccessMessage; // '' // public String offlineUnavailableMessage; // '' // public Boolean displayOfflineForm; // true // public Boolean videoCall; // false // public String offlineTitle; // 'Leave a message' // public String language; // 'en' // public Boolean transcript; // false // public String transcriptMessage; // 'Would you like a copy of this chat emailed?' // public String conversationFinishedMessage; // 'Conversation finished' // public Boolean nameFieldRegistrationForm; // true // public Boolean emailFieldRegistrationForm; // true // // @Override // public String toString() { // return "InitialData{" + // "enabled=" + enabled + // ", title='" + title + '\'' + // ", color='" + color + '\'' + // ", registrationForm=" + registrationForm + // ", visitor=" + visitor + // ", triggers=" + triggers + // ", departments=" + departments + // ", allowSwitchingDepartments=" + allowSwitchingDepartments + // ", online=" + online + // ", offlineColor='" + offlineColor + '\'' + // ", offlineMessage='" + offlineMessage + '\'' + // ", offlineSuccessMessage='" + offlineSuccessMessage + '\'' + // ", offlineUnavailableMessage='" + offlineUnavailableMessage + '\'' + // ", displayOfflineForm=" + displayOfflineForm + // ", videoCall=" + videoCall + // ", offlineTitle='" + offlineTitle + '\'' + // ", language='" + language + '\'' + // ", transcript=" + transcript + // ", transcriptMessage='" + transcriptMessage + '\'' + // ", conversationFinishedMessage='" + conversationFinishedMessage + '\'' + // ", nameFieldRegistrationForm=" + nameFieldRegistrationForm + // ", emailFieldRegistrationForm=" + emailFieldRegistrationForm + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java // public class LiveChatMessage { // public String msg; // public User u; // public String rid; // public String _id; // public String token; // public String alias; // public DateWrapper _updatedAt; // public DateWrapper ts; // public Boolean newRoom; // public Boolean showConnecting; // // @Override // public String toString() { // return "LiveChatMessage{" + // "msg='" + msg + '\'' + // ", u=" + u + // ", rid='" + rid + '\'' + // ", _id='" + _id + '\'' + // ", token='" + token + '\'' + // ", alias='" + alias + '\'' + // ", _updatedAt=" + _updatedAt + // ", ts=" + ts + // ", newRoom=" + newRoom + // ", showConnecting=" + showConnecting + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/RegisterGuest.java // public class RegisterGuest { // public String userId; // public Visitor visitor; // // @Override // public String toString() { // return "RegisterGuest{" + // "userId='" + userId + '\'' + // ", visitor=" + visitor + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.request.*; import com.github.daniel_sc.rocketchat.modern_client.response.*; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.LiveChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger;
public CompletableFuture<ChatMessage> updateMessageWithAttachments(String msg, String _id, Boolean groupable, List<Attachment> attachments) { MethodRequest request = new MethodRequest("updateMessage", SendMessageParam.forUpdate(_id, msg, null, null, null, null, groupable, attachments)); return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), ChatMessage.class))); } public CompletableFuture<List<Permission>> getPermissions() { return send(new MethodRequest("permissions/get"), failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), new TypeToken<List<Permission>>() { }.getType()))); } public CompletableFuture<InitialData> livechatGetInitialData(String visitorToken) { MethodRequest request; if (visitorToken != null) { request = new MethodRequest("livechat:getInitialData", visitorToken); } else { request = new MethodRequest("livechat:getInitialData"); } return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), InitialData.class))); } public CompletableFuture<Void> livechatSendOfflineMessage(String msg, String name, String email) { Map<String, Object> params = new HashMap<>(); params.put("name", name); params.put("message", msg); params.put("email", email); return send(new MethodRequest("livechat:sendOfflineMessage", params), failOnError(r -> null)); }
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java // public class InitialData { // public Boolean enabled; // true // public String title; // 'Rocket.Chat' // public String color; // '#C1272D' // public Boolean registrationForm; // true // public User visitor; // undefined // public List<Trigger> triggers; // [] // public List<Department> departments; // [] // public Boolean allowSwitchingDepartments; // true // public Boolean online; // true // public String offlineColor; // '#666666' // public String offlineMessage; // 'We are not online right now. Please leave us a message:' // public String offlineSuccessMessage; // '' // public String offlineUnavailableMessage; // '' // public Boolean displayOfflineForm; // true // public Boolean videoCall; // false // public String offlineTitle; // 'Leave a message' // public String language; // 'en' // public Boolean transcript; // false // public String transcriptMessage; // 'Would you like a copy of this chat emailed?' // public String conversationFinishedMessage; // 'Conversation finished' // public Boolean nameFieldRegistrationForm; // true // public Boolean emailFieldRegistrationForm; // true // // @Override // public String toString() { // return "InitialData{" + // "enabled=" + enabled + // ", title='" + title + '\'' + // ", color='" + color + '\'' + // ", registrationForm=" + registrationForm + // ", visitor=" + visitor + // ", triggers=" + triggers + // ", departments=" + departments + // ", allowSwitchingDepartments=" + allowSwitchingDepartments + // ", online=" + online + // ", offlineColor='" + offlineColor + '\'' + // ", offlineMessage='" + offlineMessage + '\'' + // ", offlineSuccessMessage='" + offlineSuccessMessage + '\'' + // ", offlineUnavailableMessage='" + offlineUnavailableMessage + '\'' + // ", displayOfflineForm=" + displayOfflineForm + // ", videoCall=" + videoCall + // ", offlineTitle='" + offlineTitle + '\'' + // ", language='" + language + '\'' + // ", transcript=" + transcript + // ", transcriptMessage='" + transcriptMessage + '\'' + // ", conversationFinishedMessage='" + conversationFinishedMessage + '\'' + // ", nameFieldRegistrationForm=" + nameFieldRegistrationForm + // ", emailFieldRegistrationForm=" + emailFieldRegistrationForm + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java // public class LiveChatMessage { // public String msg; // public User u; // public String rid; // public String _id; // public String token; // public String alias; // public DateWrapper _updatedAt; // public DateWrapper ts; // public Boolean newRoom; // public Boolean showConnecting; // // @Override // public String toString() { // return "LiveChatMessage{" + // "msg='" + msg + '\'' + // ", u=" + u + // ", rid='" + rid + '\'' + // ", _id='" + _id + '\'' + // ", token='" + token + '\'' + // ", alias='" + alias + '\'' + // ", _updatedAt=" + _updatedAt + // ", ts=" + ts + // ", newRoom=" + newRoom + // ", showConnecting=" + showConnecting + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/RegisterGuest.java // public class RegisterGuest { // public String userId; // public Visitor visitor; // // @Override // public String toString() { // return "RegisterGuest{" + // "userId='" + userId + '\'' + // ", visitor=" + visitor + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClient.java import com.github.daniel_sc.rocketchat.modern_client.request.*; import com.github.daniel_sc.rocketchat.modern_client.response.*; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.LiveChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; public CompletableFuture<ChatMessage> updateMessageWithAttachments(String msg, String _id, Boolean groupable, List<Attachment> attachments) { MethodRequest request = new MethodRequest("updateMessage", SendMessageParam.forUpdate(_id, msg, null, null, null, null, groupable, attachments)); return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), ChatMessage.class))); } public CompletableFuture<List<Permission>> getPermissions() { return send(new MethodRequest("permissions/get"), failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), new TypeToken<List<Permission>>() { }.getType()))); } public CompletableFuture<InitialData> livechatGetInitialData(String visitorToken) { MethodRequest request; if (visitorToken != null) { request = new MethodRequest("livechat:getInitialData", visitorToken); } else { request = new MethodRequest("livechat:getInitialData"); } return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), InitialData.class))); } public CompletableFuture<Void> livechatSendOfflineMessage(String msg, String name, String email) { Map<String, Object> params = new HashMap<>(); params.put("name", name); params.put("message", msg); params.put("email", email); return send(new MethodRequest("livechat:sendOfflineMessage", params), failOnError(r -> null)); }
public CompletableFuture<LiveChatMessage> livechatSendMessage(String msg, String roomId, String visitorToken) {
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClient.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java // public class InitialData { // public Boolean enabled; // true // public String title; // 'Rocket.Chat' // public String color; // '#C1272D' // public Boolean registrationForm; // true // public User visitor; // undefined // public List<Trigger> triggers; // [] // public List<Department> departments; // [] // public Boolean allowSwitchingDepartments; // true // public Boolean online; // true // public String offlineColor; // '#666666' // public String offlineMessage; // 'We are not online right now. Please leave us a message:' // public String offlineSuccessMessage; // '' // public String offlineUnavailableMessage; // '' // public Boolean displayOfflineForm; // true // public Boolean videoCall; // false // public String offlineTitle; // 'Leave a message' // public String language; // 'en' // public Boolean transcript; // false // public String transcriptMessage; // 'Would you like a copy of this chat emailed?' // public String conversationFinishedMessage; // 'Conversation finished' // public Boolean nameFieldRegistrationForm; // true // public Boolean emailFieldRegistrationForm; // true // // @Override // public String toString() { // return "InitialData{" + // "enabled=" + enabled + // ", title='" + title + '\'' + // ", color='" + color + '\'' + // ", registrationForm=" + registrationForm + // ", visitor=" + visitor + // ", triggers=" + triggers + // ", departments=" + departments + // ", allowSwitchingDepartments=" + allowSwitchingDepartments + // ", online=" + online + // ", offlineColor='" + offlineColor + '\'' + // ", offlineMessage='" + offlineMessage + '\'' + // ", offlineSuccessMessage='" + offlineSuccessMessage + '\'' + // ", offlineUnavailableMessage='" + offlineUnavailableMessage + '\'' + // ", displayOfflineForm=" + displayOfflineForm + // ", videoCall=" + videoCall + // ", offlineTitle='" + offlineTitle + '\'' + // ", language='" + language + '\'' + // ", transcript=" + transcript + // ", transcriptMessage='" + transcriptMessage + '\'' + // ", conversationFinishedMessage='" + conversationFinishedMessage + '\'' + // ", nameFieldRegistrationForm=" + nameFieldRegistrationForm + // ", emailFieldRegistrationForm=" + emailFieldRegistrationForm + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java // public class LiveChatMessage { // public String msg; // public User u; // public String rid; // public String _id; // public String token; // public String alias; // public DateWrapper _updatedAt; // public DateWrapper ts; // public Boolean newRoom; // public Boolean showConnecting; // // @Override // public String toString() { // return "LiveChatMessage{" + // "msg='" + msg + '\'' + // ", u=" + u + // ", rid='" + rid + '\'' + // ", _id='" + _id + '\'' + // ", token='" + token + '\'' + // ", alias='" + alias + '\'' + // ", _updatedAt=" + _updatedAt + // ", ts=" + ts + // ", newRoom=" + newRoom + // ", showConnecting=" + showConnecting + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/RegisterGuest.java // public class RegisterGuest { // public String userId; // public Visitor visitor; // // @Override // public String toString() { // return "RegisterGuest{" + // "userId='" + userId + '\'' + // ", visitor=" + visitor + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.request.*; import com.github.daniel_sc.rocketchat.modern_client.response.*; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.LiveChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger;
public CompletableFuture<InitialData> livechatGetInitialData(String visitorToken) { MethodRequest request; if (visitorToken != null) { request = new MethodRequest("livechat:getInitialData", visitorToken); } else { request = new MethodRequest("livechat:getInitialData"); } return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), InitialData.class))); } public CompletableFuture<Void> livechatSendOfflineMessage(String msg, String name, String email) { Map<String, Object> params = new HashMap<>(); params.put("name", name); params.put("message", msg); params.put("email", email); return send(new MethodRequest("livechat:sendOfflineMessage", params), failOnError(r -> null)); } public CompletableFuture<LiveChatMessage> livechatSendMessage(String msg, String roomId, String visitorToken) { Map<String, Object> params = new HashMap<>(); params.put("_id", UUID.randomUUID().toString()); params.put("rid", roomId); params.put("msg", msg); params.put("token", visitorToken); return send(new MethodRequest("sendMessageLivechat", params), failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), LiveChatMessage.class))); }
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java // public class InitialData { // public Boolean enabled; // true // public String title; // 'Rocket.Chat' // public String color; // '#C1272D' // public Boolean registrationForm; // true // public User visitor; // undefined // public List<Trigger> triggers; // [] // public List<Department> departments; // [] // public Boolean allowSwitchingDepartments; // true // public Boolean online; // true // public String offlineColor; // '#666666' // public String offlineMessage; // 'We are not online right now. Please leave us a message:' // public String offlineSuccessMessage; // '' // public String offlineUnavailableMessage; // '' // public Boolean displayOfflineForm; // true // public Boolean videoCall; // false // public String offlineTitle; // 'Leave a message' // public String language; // 'en' // public Boolean transcript; // false // public String transcriptMessage; // 'Would you like a copy of this chat emailed?' // public String conversationFinishedMessage; // 'Conversation finished' // public Boolean nameFieldRegistrationForm; // true // public Boolean emailFieldRegistrationForm; // true // // @Override // public String toString() { // return "InitialData{" + // "enabled=" + enabled + // ", title='" + title + '\'' + // ", color='" + color + '\'' + // ", registrationForm=" + registrationForm + // ", visitor=" + visitor + // ", triggers=" + triggers + // ", departments=" + departments + // ", allowSwitchingDepartments=" + allowSwitchingDepartments + // ", online=" + online + // ", offlineColor='" + offlineColor + '\'' + // ", offlineMessage='" + offlineMessage + '\'' + // ", offlineSuccessMessage='" + offlineSuccessMessage + '\'' + // ", offlineUnavailableMessage='" + offlineUnavailableMessage + '\'' + // ", displayOfflineForm=" + displayOfflineForm + // ", videoCall=" + videoCall + // ", offlineTitle='" + offlineTitle + '\'' + // ", language='" + language + '\'' + // ", transcript=" + transcript + // ", transcriptMessage='" + transcriptMessage + '\'' + // ", conversationFinishedMessage='" + conversationFinishedMessage + '\'' + // ", nameFieldRegistrationForm=" + nameFieldRegistrationForm + // ", emailFieldRegistrationForm=" + emailFieldRegistrationForm + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java // public class LiveChatMessage { // public String msg; // public User u; // public String rid; // public String _id; // public String token; // public String alias; // public DateWrapper _updatedAt; // public DateWrapper ts; // public Boolean newRoom; // public Boolean showConnecting; // // @Override // public String toString() { // return "LiveChatMessage{" + // "msg='" + msg + '\'' + // ", u=" + u + // ", rid='" + rid + '\'' + // ", _id='" + _id + '\'' + // ", token='" + token + '\'' + // ", alias='" + alias + '\'' + // ", _updatedAt=" + _updatedAt + // ", ts=" + ts + // ", newRoom=" + newRoom + // ", showConnecting=" + showConnecting + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/RegisterGuest.java // public class RegisterGuest { // public String userId; // public Visitor visitor; // // @Override // public String toString() { // return "RegisterGuest{" + // "userId='" + userId + '\'' + // ", visitor=" + visitor + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClient.java import com.github.daniel_sc.rocketchat.modern_client.request.*; import com.github.daniel_sc.rocketchat.modern_client.response.*; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.LiveChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; public CompletableFuture<InitialData> livechatGetInitialData(String visitorToken) { MethodRequest request; if (visitorToken != null) { request = new MethodRequest("livechat:getInitialData", visitorToken); } else { request = new MethodRequest("livechat:getInitialData"); } return send(request, failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), InitialData.class))); } public CompletableFuture<Void> livechatSendOfflineMessage(String msg, String name, String email) { Map<String, Object> params = new HashMap<>(); params.put("name", name); params.put("message", msg); params.put("email", email); return send(new MethodRequest("livechat:sendOfflineMessage", params), failOnError(r -> null)); } public CompletableFuture<LiveChatMessage> livechatSendMessage(String msg, String roomId, String visitorToken) { Map<String, Object> params = new HashMap<>(); params.put("_id", UUID.randomUUID().toString()); params.put("rid", roomId); params.put("msg", msg); params.put("token", visitorToken); return send(new MethodRequest("sendMessageLivechat", params), failOnError(r -> GSON.fromJson(GSON.toJsonTree(r.result), LiveChatMessage.class))); }
public CompletableFuture<RegisterGuest> livechatRegisterGuest(String visitorToken, String name, String email, String department) {
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/User.java // public class User { // public String _id; // public String username; // public String name; // // @Override // public String toString() { // return "User{" + // "_id='" + _id + '\'' + // ", username='" + username + '\'' + // ", name='" + name + '\'' + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.response.User; import java.util.List;
package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class InitialData { public Boolean enabled; // true public String title; // 'Rocket.Chat' public String color; // '#C1272D' public Boolean registrationForm; // true
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/User.java // public class User { // public String _id; // public String username; // public String name; // // @Override // public String toString() { // return "User{" + // "_id='" + _id + '\'' + // ", username='" + username + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/InitialData.java import com.github.daniel_sc.rocketchat.modern_client.response.User; import java.util.List; package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class InitialData { public Boolean enabled; // true public String title; // 'Rocket.Chat' public String color; // '#C1272D' public Boolean registrationForm; // true
public User visitor; // undefined
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/Department.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper;
package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class Department { public String _id; // "4swtja84kmn5WCdwL" public Boolean enabled; // true public String name; // "My Department" public String description; // "I have no description for this department" public Long numAgents; // 1 public Boolean showOnRegistration; // true
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/Department.java import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class Department { public String _id; // "4swtja84kmn5WCdwL" public Boolean enabled; // true public String name; // "My Department" public String description; // "I have no description for this department" public Long numAgents; // 1 public Boolean showOnRegistration; // true
public DateWrapper _updatedAt; // "2016-12-06T17:19:18.138Z"
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/Trigger.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; import java.util.List;
package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class Trigger { public String _id; // "Lk52shJFYyb55trw8", public String name; // "test" public String description; // "test" public Boolean enabled; // true public Boolean runOnce; // true public List<Condition> conditions; public List<Action> actions;
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/Trigger.java import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; import java.util.List; package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class Trigger { public String _id; // "Lk52shJFYyb55trw8", public String name; // "test" public String description; // "test" public Boolean enabled; // true public Boolean runOnce; // true public List<Condition> conditions; public List<Action> actions;
public DateWrapper _updatedAt;
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/User.java // public class User { // public String _id; // public String username; // public String name; // // @Override // public String toString() { // return "User{" + // "_id='" + _id + '\'' + // ", username='" + username + '\'' + // ", name='" + name + '\'' + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; import com.github.daniel_sc.rocketchat.modern_client.response.User;
package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class LiveChatMessage { public String msg;
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/User.java // public class User { // public String _id; // public String username; // public String name; // // @Override // public String toString() { // return "User{" + // "_id='" + _id + '\'' + // ", username='" + username + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; import com.github.daniel_sc.rocketchat.modern_client.response.User; package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class LiveChatMessage { public String msg;
public User u;
daniel-sc/rocketchat-modern-client
src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/User.java // public class User { // public String _id; // public String username; // public String name; // // @Override // public String toString() { // return "User{" + // "_id='" + _id + '\'' + // ", username='" + username + '\'' + // ", name='" + name + '\'' + // '}'; // } // }
import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; import com.github.daniel_sc.rocketchat.modern_client.response.User;
package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class LiveChatMessage { public String msg; public User u; public String rid; public String _id; public String token; public String alias;
// Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/DateWrapper.java // public class DateWrapper { // @SerializedName("$date") // public Date date; // // @Override // public String toString() { // return "DateWrapper{" + // "date=" + date + // '}'; // } // } // // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/User.java // public class User { // public String _id; // public String username; // public String name; // // @Override // public String toString() { // return "User{" + // "_id='" + _id + '\'' + // ", username='" + username + '\'' + // ", name='" + name + '\'' + // '}'; // } // } // Path: src/main/java/com/github/daniel_sc/rocketchat/modern_client/response/livechat/LiveChatMessage.java import com.github.daniel_sc.rocketchat.modern_client.response.DateWrapper; import com.github.daniel_sc.rocketchat.modern_client.response.User; package com.github.daniel_sc.rocketchat.modern_client.response.livechat; public class LiveChatMessage { public String msg; public User u; public String rid; public String _id; public String token; public String alias;
public DateWrapper _updatedAt;
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/PipeStep.java
// Path: src/main/java/io/playpen/core/coordinator/local/Server.java // @Data // public class Server { // private P3Package p3; // // private String uuid; // // private String name; // // private Map<String, String> properties = new ConcurrentHashMap<>(); // // private String localPath; // // private XProcess process; // // private boolean freezeOnShutdown = false; // // public String getSafeName() { // if (name != null) // return name; // return uuid; // } // } // // Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.coordinator.local.Server; import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.stringtemplate.v4.ST;
package io.playpen.core.p3.step; @Log4j2 public class PipeStep implements IPackageStep { @Override public String getStepId() { return "pipe"; } @Override
// Path: src/main/java/io/playpen/core/coordinator/local/Server.java // @Data // public class Server { // private P3Package p3; // // private String uuid; // // private String name; // // private Map<String, String> properties = new ConcurrentHashMap<>(); // // private String localPath; // // private XProcess process; // // private boolean freezeOnShutdown = false; // // public String getSafeName() { // if (name != null) // return name; // return uuid; // } // } // // Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/PipeStep.java import io.playpen.core.coordinator.local.Server; import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.stringtemplate.v4.ST; package io.playpen.core.p3.step; @Log4j2 public class PipeStep implements IPackageStep { @Override public String getStepId() { return "pipe"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/PipeStep.java
// Path: src/main/java/io/playpen/core/coordinator/local/Server.java // @Data // public class Server { // private P3Package p3; // // private String uuid; // // private String name; // // private Map<String, String> properties = new ConcurrentHashMap<>(); // // private String localPath; // // private XProcess process; // // private boolean freezeOnShutdown = false; // // public String getSafeName() { // if (name != null) // return name; // return uuid; // } // } // // Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.coordinator.local.Server; import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.stringtemplate.v4.ST;
package io.playpen.core.p3.step; @Log4j2 public class PipeStep implements IPackageStep { @Override public String getStepId() { return "pipe"; } @Override
// Path: src/main/java/io/playpen/core/coordinator/local/Server.java // @Data // public class Server { // private P3Package p3; // // private String uuid; // // private String name; // // private Map<String, String> properties = new ConcurrentHashMap<>(); // // private String localPath; // // private XProcess process; // // private boolean freezeOnShutdown = false; // // public String getSafeName() { // if (name != null) // return name; // return uuid; // } // } // // Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/PipeStep.java import io.playpen.core.coordinator.local.Server; import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.stringtemplate.v4.ST; package io.playpen.core.p3.step; @Log4j2 public class PipeStep implements IPackageStep { @Override public String getStepId() { return "pipe"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/PipeStep.java
// Path: src/main/java/io/playpen/core/coordinator/local/Server.java // @Data // public class Server { // private P3Package p3; // // private String uuid; // // private String name; // // private Map<String, String> properties = new ConcurrentHashMap<>(); // // private String localPath; // // private XProcess process; // // private boolean freezeOnShutdown = false; // // public String getSafeName() { // if (name != null) // return name; // return uuid; // } // } // // Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.coordinator.local.Server; import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.stringtemplate.v4.ST;
package io.playpen.core.p3.step; @Log4j2 public class PipeStep implements IPackageStep { @Override public String getStepId() { return "pipe"; } @Override public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
// Path: src/main/java/io/playpen/core/coordinator/local/Server.java // @Data // public class Server { // private P3Package p3; // // private String uuid; // // private String name; // // private Map<String, String> properties = new ConcurrentHashMap<>(); // // private String localPath; // // private XProcess process; // // private boolean freezeOnShutdown = false; // // public String getSafeName() { // if (name != null) // return name; // return uuid; // } // } // // Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/PipeStep.java import io.playpen.core.coordinator.local.Server; import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.stringtemplate.v4.ST; package io.playpen.core.p3.step; @Log4j2 public class PipeStep implements IPackageStep { @Override public String getStepId() { return "pipe"; } @Override public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
if(!(ctx.getUser() instanceof Server)) {
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // }
import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands;
package io.playpen.core.coordinator.network.authenticator; public interface IAuthenticator { String getName();
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands; package io.playpen.core.coordinator.network.authenticator; public interface IAuthenticator { String getName();
boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from);
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // }
import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands;
package io.playpen.core.coordinator.network.authenticator; public interface IAuthenticator { String getName();
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands; package io.playpen.core.coordinator.network.authenticator; public interface IAuthenticator { String getName();
boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from);
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java
// Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java // public interface IAuthenticator { // String getName(); // boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from); // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // }
import io.netty.channel.Channel; import io.playpen.core.coordinator.network.authenticator.IAuthenticator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.p3.P3Package; import io.playpen.core.protocol.Commands; import lombok.Data; import lombok.extern.log4j.Log4j2; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet;
package io.playpen.core.coordinator.network; @Data @Log4j2 public class LocalCoordinator { private String uuid; private String key; private String name; private String keyName = ""; private Map<String, Integer> resources = new ConcurrentHashMap<>(); private Set<String> attributes = new ConcurrentSkipListSet<>(); private Map<String, Server> servers = new ConcurrentHashMap<>(); private Channel channel = null; private boolean enabled = false; /** * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. * This must be manually set and unset, but will also reset if the network coordinator is restarted. */ private boolean restricted = false;
// Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java // public interface IAuthenticator { // String getName(); // boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from); // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java import io.netty.channel.Channel; import io.playpen.core.coordinator.network.authenticator.IAuthenticator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.p3.P3Package; import io.playpen.core.protocol.Commands; import lombok.Data; import lombok.extern.log4j.Log4j2; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; package io.playpen.core.coordinator.network; @Data @Log4j2 public class LocalCoordinator { private String uuid; private String key; private String name; private String keyName = ""; private Map<String, Integer> resources = new ConcurrentHashMap<>(); private Set<String> attributes = new ConcurrentSkipListSet<>(); private Map<String, Server> servers = new ConcurrentHashMap<>(); private Channel channel = null; private boolean enabled = false; /** * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. * This must be manually set and unset, but will also reset if the network coordinator is restarted. */ private boolean restricted = false;
private List<IAuthenticator> authenticators = new ArrayList<>();
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java
// Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java // public interface IAuthenticator { // String getName(); // boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from); // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // }
import io.netty.channel.Channel; import io.playpen.core.coordinator.network.authenticator.IAuthenticator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.p3.P3Package; import io.playpen.core.protocol.Commands; import lombok.Data; import lombok.extern.log4j.Log4j2; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet;
public boolean isEnabled() { return enabled && channel != null && channel.isActive(); } public Server getServer(String idOrName) { if(servers.containsKey(idOrName)) return servers.get(idOrName); for(Server server : servers.values()) { if(server.getName() != null && server.getName().equals(idOrName)) return server; } return null; } public Map<String, Integer> getAvailableResources() { Map<String, Integer> used = new HashMap<>(); for(Map.Entry<String, Integer> entry : resources.entrySet()) { Integer value = entry.getValue(); for(Server server : servers.values()) { value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); } used.put(entry.getKey(), value); } return used; }
// Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java // public interface IAuthenticator { // String getName(); // boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from); // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java import io.netty.channel.Channel; import io.playpen.core.coordinator.network.authenticator.IAuthenticator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.p3.P3Package; import io.playpen.core.protocol.Commands; import lombok.Data; import lombok.extern.log4j.Log4j2; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; public boolean isEnabled() { return enabled && channel != null && channel.isActive(); } public Server getServer(String idOrName) { if(servers.containsKey(idOrName)) return servers.get(idOrName); for(Server server : servers.values()) { if(server.getName() != null && server.getName().equals(idOrName)) return server; } return null; } public Map<String, Integer> getAvailableResources() { Map<String, Integer> used = new HashMap<>(); for(Map.Entry<String, Integer> entry : resources.entrySet()) { Integer value = entry.getValue(); for(Server server : servers.values()) { value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); } used.put(entry.getKey(), value); } return used; }
public boolean canProvisionPackage(P3Package p3) {
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java
// Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java // public interface IAuthenticator { // String getName(); // boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from); // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // }
import io.netty.channel.Channel; import io.playpen.core.coordinator.network.authenticator.IAuthenticator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.p3.P3Package; import io.playpen.core.protocol.Commands; import lombok.Data; import lombok.extern.log4j.Log4j2; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet;
while(servers.containsKey(server.getUuid())) server.setUuid(UUID.randomUUID().toString()); server.setP3(p3); server.setName(name); server.getProperties().putAll(properties); server.setCoordinator(this); servers.put(server.getUuid(), server); return server; } /** * Normalized resource usage is the sum of (resource / max resource) divided by the * number of resources. This should be between 0 and 1. */ public double getNormalizedResourceUsage() { double result = 0.0; Map<String, Integer> available = getAvailableResources(); for(Map.Entry<String, Integer> max : resources.entrySet()) { if(max.getValue() <= 0) // wat continue; Integer used = available.getOrDefault(max.getKey(), 0); result += used.doubleValue() / max.getValue().doubleValue(); } return result; }
// Path: src/main/java/io/playpen/core/coordinator/network/authenticator/IAuthenticator.java // public interface IAuthenticator { // String getName(); // boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from); // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java import io.netty.channel.Channel; import io.playpen.core.coordinator.network.authenticator.IAuthenticator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.p3.P3Package; import io.playpen.core.protocol.Commands; import lombok.Data; import lombok.extern.log4j.Log4j2; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; while(servers.containsKey(server.getUuid())) server.setUuid(UUID.randomUUID().toString()); server.setP3(p3); server.setName(name); server.getProperties().putAll(properties); server.setCoordinator(this); servers.put(server.getUuid(), server); return server; } /** * Normalized resource usage is the sum of (resource / max resource) divided by the * number of resources. This should be between 0 and 1. */ public double getNormalizedResourceUsage() { double result = 0.0; Map<String, Integer> available = getAvailableResources(); for(Map.Entry<String, Integer> max : resources.entrySet()) { if(max.getValue() <= 0) // wat continue; Integer used = available.getOrDefault(max.getKey(), 0); result += used.doubleValue() / max.getValue().doubleValue(); } return result; }
public boolean authenticate(Commands.BaseCommand command, TransactionInfo info)
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/CopyStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.stringtemplate.v4.ST; import java.io.File; import java.io.IOException;
package io.playpen.core.p3.step; @Log4j2 public class CopyStep implements IPackageStep { @Override public String getStepId() { return "copy-directory"; } @Override
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/CopyStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.stringtemplate.v4.ST; import java.io.File; import java.io.IOException; package io.playpen.core.p3.step; @Log4j2 public class CopyStep implements IPackageStep { @Override public String getStepId() { return "copy-directory"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/CopyStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.stringtemplate.v4.ST; import java.io.File; import java.io.IOException;
package io.playpen.core.p3.step; @Log4j2 public class CopyStep implements IPackageStep { @Override public String getStepId() { return "copy-directory"; } @Override
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/CopyStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.stringtemplate.v4.ST; import java.io.File; import java.io.IOException; package io.playpen.core.p3.step; @Log4j2 public class CopyStep implements IPackageStep { @Override public String getStepId() { return "copy-directory"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/CopyStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.stringtemplate.v4.ST; import java.io.File; import java.io.IOException;
package io.playpen.core.p3.step; @Log4j2 public class CopyStep implements IPackageStep { @Override public String getStepId() { return "copy-directory"; } @Override public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) { String from = config.optString("from"); if(from == null) { log.error("'from' is not defined as a string in config"); return false; } String to = config.optString("to"); if (to == null) { log.error("'to' is not defined as a string in config"); return false; } ST templateFrom = new ST(from);
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/CopyStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.stringtemplate.v4.ST; import java.io.File; import java.io.IOException; package io.playpen.core.p3.step; @Log4j2 public class CopyStep implements IPackageStep { @Override public String getStepId() { return "copy-directory"; } @Override public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) { String from = config.optString("from"); if(from == null) { log.error("'from' is not defined as a string in config"); return false; } String to = config.optString("to"); if (to == null) { log.error("'to' is not defined as a string in config"); return false; } ST templateFrom = new ST(from);
STUtils.buildSTProperties(p3, ctx, templateFrom);
PlayPen/playpen-core
src/main/java/io/playpen/core/networking/TransactionManager.java
// Path: src/main/java/io/playpen/core/coordinator/PlayPen.java // public abstract class PlayPen { // private static PlayPen instance = null; // // public static PlayPen get() { // return instance; // } // // // do not call except from Bootstrap // public static void reset() { // instance = null; // } // // public PlayPen() { // instance = this; // } // // public abstract String getServerId(); // // public abstract CoordinatorMode getCoordinatorMode(); // // public abstract PackageManager getPackageManager(); // // public abstract PluginManager getPluginManager(); // // public abstract ScheduledExecutorService getScheduler(); // // public String generateId() { // return getServerId() + "-" + UUID.randomUUID().toString(); // } // // public abstract boolean send(Protocol.Transaction message, String target); // // public abstract boolean receive(Protocol.AuthenticatedMessage auth, Channel from); // // public abstract boolean process(Commands.BaseCommand command, TransactionInfo info, String from); // // public abstract void onVMShutdown(); // }
import io.playpen.core.coordinator.PlayPen; import io.playpen.core.protocol.Commands; import io.playpen.core.protocol.Protocol; import lombok.extern.log4j.Log4j2; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
package io.playpen.core.networking; @Log4j2 public class TransactionManager { public static final long TRANSACTION_TIMEOUT = 340; // seconds private static TransactionManager instance = new TransactionManager(); public static TransactionManager get() { return instance; } private Map<String, TransactionInfo> transactions = new ConcurrentHashMap<>(); private TransactionManager() {} boolean isActive(String id) { return transactions.containsKey(id); } public TransactionInfo getTransaction(String id) { return transactions.get(id); } public Protocol.Transaction build(String id, Protocol.Transaction.Mode mode, Commands.BaseCommand command) { TransactionInfo info = getTransaction(id); if(info == null) { log.error("Unable to build unknown transaction " + id); return null; } return Protocol.Transaction.newBuilder() .setId(info.getId()) .setMode(mode) .setPayload(command) .build(); } public TransactionInfo begin() { TransactionInfo info = new TransactionInfo();
// Path: src/main/java/io/playpen/core/coordinator/PlayPen.java // public abstract class PlayPen { // private static PlayPen instance = null; // // public static PlayPen get() { // return instance; // } // // // do not call except from Bootstrap // public static void reset() { // instance = null; // } // // public PlayPen() { // instance = this; // } // // public abstract String getServerId(); // // public abstract CoordinatorMode getCoordinatorMode(); // // public abstract PackageManager getPackageManager(); // // public abstract PluginManager getPluginManager(); // // public abstract ScheduledExecutorService getScheduler(); // // public String generateId() { // return getServerId() + "-" + UUID.randomUUID().toString(); // } // // public abstract boolean send(Protocol.Transaction message, String target); // // public abstract boolean receive(Protocol.AuthenticatedMessage auth, Channel from); // // public abstract boolean process(Commands.BaseCommand command, TransactionInfo info, String from); // // public abstract void onVMShutdown(); // } // Path: src/main/java/io/playpen/core/networking/TransactionManager.java import io.playpen.core.coordinator.PlayPen; import io.playpen.core.protocol.Commands; import io.playpen.core.protocol.Protocol; import lombok.extern.log4j.Log4j2; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; package io.playpen.core.networking; @Log4j2 public class TransactionManager { public static final long TRANSACTION_TIMEOUT = 340; // seconds private static TransactionManager instance = new TransactionManager(); public static TransactionManager get() { return instance; } private Map<String, TransactionInfo> transactions = new ConcurrentHashMap<>(); private TransactionManager() {} boolean isActive(String id) { return transactions.containsKey(id); } public TransactionInfo getTransaction(String id) { return transactions.get(id); } public Protocol.Transaction build(String id, Protocol.Transaction.Mode mode, Commands.BaseCommand command) { TransactionInfo info = getTransaction(id); if(info == null) { log.error("Unable to build unknown transaction " + id); return null; } return Protocol.Transaction.newBuilder() .setId(info.getId()) .setMode(mode) .setPayload(command) .build(); } public TransactionInfo begin() { TransactionInfo info = new TransactionInfo();
info.setId(PlayPen.get().generateId());
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/Server.java
// Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // }
import io.playpen.core.p3.P3Package; import lombok.Data; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap;
package io.playpen.core.coordinator.network; @Data public class Server {
// Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // Path: src/main/java/io/playpen/core/coordinator/network/Server.java import io.playpen.core.p3.P3Package; import lombok.Data; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; package io.playpen.core.coordinator.network; @Data public class Server {
private P3Package p3;
PlayPen/playpen-core
src/test/java/io/playpen/core/ProcessBufferTest.java
// Path: src/main/java/io/playpen/core/utils/process/ProcessBuffer.java // public abstract class ProcessBuffer { // private final StringBuilder rumpBuffer = new StringBuilder(128); // private volatile boolean rumpBufferHasContents = false; // private final Lock lock = new ReentrantLock(); // // public void append(CharBuffer buffer) { // // Okay, I'll admit it: this thing is literally a Rube Goldberg machine. But it works well enough! // StringBuilder found = new StringBuilder(); // // if (rumpBufferHasContents) { // lock.lock(); // try { // found.append(rumpBuffer); // rumpBuffer.delete(0, rumpBuffer.length()); // rumpBufferHasContents = false; // } finally { // lock.unlock(); // } // } // // for (int i = 0; i < buffer.remaining(); i++) { // char c = buffer.get(i); // if (c == '\r') { // // When it looks like a hammer, there must be a sickle too. // continue; // } // if (c == '\n') { // if (found.length() == 0) // continue; // onOutput(found.toString()); // found.delete(0, found.length()); // } else { // found.append(c); // } // } // // // Consume the buffer. // buffer.position(buffer.remaining()); // // if (found.length() != 0) { // lock.lock(); // try { // this.rumpBuffer.append(found); // rumpBufferHasContents = true; // } finally { // lock.unlock(); // } // } // } // // protected abstract void onOutput(String output); // } // // Path: src/main/java/io/playpen/core/utils/process/ProcessBuffer.java // public abstract class ProcessBuffer { // private final StringBuilder rumpBuffer = new StringBuilder(128); // private volatile boolean rumpBufferHasContents = false; // private final Lock lock = new ReentrantLock(); // // public void append(CharBuffer buffer) { // // Okay, I'll admit it: this thing is literally a Rube Goldberg machine. But it works well enough! // StringBuilder found = new StringBuilder(); // // if (rumpBufferHasContents) { // lock.lock(); // try { // found.append(rumpBuffer); // rumpBuffer.delete(0, rumpBuffer.length()); // rumpBufferHasContents = false; // } finally { // lock.unlock(); // } // } // // for (int i = 0; i < buffer.remaining(); i++) { // char c = buffer.get(i); // if (c == '\r') { // // When it looks like a hammer, there must be a sickle too. // continue; // } // if (c == '\n') { // if (found.length() == 0) // continue; // onOutput(found.toString()); // found.delete(0, found.length()); // } else { // found.append(c); // } // } // // // Consume the buffer. // buffer.position(buffer.remaining()); // // if (found.length() != 0) { // lock.lock(); // try { // this.rumpBuffer.append(found); // rumpBufferHasContents = true; // } finally { // lock.unlock(); // } // } // } // // protected abstract void onOutput(String output); // }
import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import io.playpen.core.utils.process.ProcessBuffer; import io.playpen.core.utils.process.ProcessBuffer; import org.junit.Assert; import org.junit.Test; import java.nio.CharBuffer; import java.util.List;
buffer.append(CharBuffer.wrap(fullBuffer(strings))); sanityCheck(buffer); } @Test public void verifyIncompleteLine() { List<String> strings = Lists.newArrayList("Test", "Testing2"); TestBuffer buffer = new TestBuffer(strings); buffer.append(CharBuffer.wrap(fullBuffer(strings) + "Potato")); sanityCheck(buffer); } @Test public void verifyLaterCompletedLine() { List<String> strings = Lists.newArrayList("Test", "Testing2", "Potato"); TestBuffer buffer = new TestBuffer(strings); buffer.append(CharBuffer.wrap(String.join(LINE_SEPERATOR, strings))); buffer.append(CharBuffer.wrap(LINE_SEPERATOR)); sanityCheck(buffer); } private static void sanityCheck(TestBuffer buffer) { if (!buffer.expected.isEmpty()) { int hasRead = buffer.origSize - buffer.expected.size(); Assert.fail("Didn't read enough data (read " + hasRead + " lines, wanted " + buffer.origSize + " lines)"); } }
// Path: src/main/java/io/playpen/core/utils/process/ProcessBuffer.java // public abstract class ProcessBuffer { // private final StringBuilder rumpBuffer = new StringBuilder(128); // private volatile boolean rumpBufferHasContents = false; // private final Lock lock = new ReentrantLock(); // // public void append(CharBuffer buffer) { // // Okay, I'll admit it: this thing is literally a Rube Goldberg machine. But it works well enough! // StringBuilder found = new StringBuilder(); // // if (rumpBufferHasContents) { // lock.lock(); // try { // found.append(rumpBuffer); // rumpBuffer.delete(0, rumpBuffer.length()); // rumpBufferHasContents = false; // } finally { // lock.unlock(); // } // } // // for (int i = 0; i < buffer.remaining(); i++) { // char c = buffer.get(i); // if (c == '\r') { // // When it looks like a hammer, there must be a sickle too. // continue; // } // if (c == '\n') { // if (found.length() == 0) // continue; // onOutput(found.toString()); // found.delete(0, found.length()); // } else { // found.append(c); // } // } // // // Consume the buffer. // buffer.position(buffer.remaining()); // // if (found.length() != 0) { // lock.lock(); // try { // this.rumpBuffer.append(found); // rumpBufferHasContents = true; // } finally { // lock.unlock(); // } // } // } // // protected abstract void onOutput(String output); // } // // Path: src/main/java/io/playpen/core/utils/process/ProcessBuffer.java // public abstract class ProcessBuffer { // private final StringBuilder rumpBuffer = new StringBuilder(128); // private volatile boolean rumpBufferHasContents = false; // private final Lock lock = new ReentrantLock(); // // public void append(CharBuffer buffer) { // // Okay, I'll admit it: this thing is literally a Rube Goldberg machine. But it works well enough! // StringBuilder found = new StringBuilder(); // // if (rumpBufferHasContents) { // lock.lock(); // try { // found.append(rumpBuffer); // rumpBuffer.delete(0, rumpBuffer.length()); // rumpBufferHasContents = false; // } finally { // lock.unlock(); // } // } // // for (int i = 0; i < buffer.remaining(); i++) { // char c = buffer.get(i); // if (c == '\r') { // // When it looks like a hammer, there must be a sickle too. // continue; // } // if (c == '\n') { // if (found.length() == 0) // continue; // onOutput(found.toString()); // found.delete(0, found.length()); // } else { // found.append(c); // } // } // // // Consume the buffer. // buffer.position(buffer.remaining()); // // if (found.length() != 0) { // lock.lock(); // try { // this.rumpBuffer.append(found); // rumpBufferHasContents = true; // } finally { // lock.unlock(); // } // } // } // // protected abstract void onOutput(String output); // } // Path: src/test/java/io/playpen/core/ProcessBufferTest.java import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import io.playpen.core.utils.process.ProcessBuffer; import io.playpen.core.utils.process.ProcessBuffer; import org.junit.Assert; import org.junit.Test; import java.nio.CharBuffer; import java.util.List; buffer.append(CharBuffer.wrap(fullBuffer(strings))); sanityCheck(buffer); } @Test public void verifyIncompleteLine() { List<String> strings = Lists.newArrayList("Test", "Testing2"); TestBuffer buffer = new TestBuffer(strings); buffer.append(CharBuffer.wrap(fullBuffer(strings) + "Potato")); sanityCheck(buffer); } @Test public void verifyLaterCompletedLine() { List<String> strings = Lists.newArrayList("Test", "Testing2", "Potato"); TestBuffer buffer = new TestBuffer(strings); buffer.append(CharBuffer.wrap(String.join(LINE_SEPERATOR, strings))); buffer.append(CharBuffer.wrap(LINE_SEPERATOR)); sanityCheck(buffer); } private static void sanityCheck(TestBuffer buffer) { if (!buffer.expected.isEmpty()) { int hasRead = buffer.origSize - buffer.expected.size(); Assert.fail("Didn't read enough data (read " + hasRead + " lines, wanted " + buffer.origSize + " lines)"); } }
private class TestBuffer extends ProcessBuffer {
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/authenticator/DeprovisionAuthenticator.java
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // }
import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands;
package io.playpen.core.coordinator.network.authenticator; public class DeprovisionAuthenticator implements IAuthenticator { @Override public String getName() { return "deprovision"; } @Override
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // Path: src/main/java/io/playpen/core/coordinator/network/authenticator/DeprovisionAuthenticator.java import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands; package io.playpen.core.coordinator.network.authenticator; public class DeprovisionAuthenticator implements IAuthenticator { @Override public String getName() { return "deprovision"; } @Override
public boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from) {
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/authenticator/DeprovisionAuthenticator.java
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // }
import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands;
package io.playpen.core.coordinator.network.authenticator; public class DeprovisionAuthenticator implements IAuthenticator { @Override public String getName() { return "deprovision"; } @Override
// Path: src/main/java/io/playpen/core/coordinator/network/LocalCoordinator.java // @Data // @Log4j2 // public class LocalCoordinator { // private String uuid; // // private String key; // // private String name; // // private String keyName = ""; // // private Map<String, Integer> resources = new ConcurrentHashMap<>(); // // private Set<String> attributes = new ConcurrentSkipListSet<>(); // // private Map<String, Server> servers = new ConcurrentHashMap<>(); // // private Channel channel = null; // // private boolean enabled = false; // // /** // * Setting this to true will prevent automatic selection of this coordinator for provisioning operations. // * This must be manually set and unset, but will also reset if the network coordinator is restarted. // */ // private boolean restricted = false; // // private List<IAuthenticator> authenticators = new ArrayList<>(); // // public String getName() { // if(name == null) { // return uuid; // } // // return name; // } // // public boolean isEnabled() { // return enabled && channel != null && channel.isActive(); // } // // public Server getServer(String idOrName) { // if(servers.containsKey(idOrName)) // return servers.get(idOrName); // // for(Server server : servers.values()) { // if(server.getName() != null && server.getName().equals(idOrName)) // return server; // } // // return null; // } // // public Map<String, Integer> getAvailableResources() { // Map<String, Integer> used = new HashMap<>(); // for(Map.Entry<String, Integer> entry : resources.entrySet()) { // Integer value = entry.getValue(); // for(Server server : servers.values()) { // value -= server.getP3().getResources().getOrDefault(entry.getKey(), 0); // } // // used.put(entry.getKey(), value); // } // // return used; // } // // public boolean canProvisionPackage(P3Package p3) { // for(String attr : p3.getAttributes()) { // if(!attributes.contains(attr)) { // log.warn("Coordinator " + getUuid() + " doesn't have attribute " + attr + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // Map<String, Integer> resources = getAvailableResources(); // for(Map.Entry<String, Integer> entry : p3.getResources().entrySet()) { // if(!resources.containsKey(entry.getKey())) { // log.warn("Coordinator " + getUuid() + " doesn't have resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // // if(resources.get(entry.getKey()) - entry.getValue() < 0) { // log.warn("Coordinator " + getUuid() + " doesn't have enough of resource " + entry.getKey() + " for " + p3.getId() + " at " + p3.getVersion()); // return false; // } // } // // return true; // } // // public Server createServer(P3Package p3, String name, Map<String, String> properties) { // if(!p3.isResolved()) { // log.error("Cannot create server for unresolved package"); // return null; // } // // if(!canProvisionPackage(p3)) { // log.error("Coordinator " + getUuid() + " failed provision check for package " + p3.getId() + " at " + p3.getVersion()); // return null; // } // // Server server = new Server(); // server.setUuid(UUID.randomUUID().toString()); // while(servers.containsKey(server.getUuid())) // server.setUuid(UUID.randomUUID().toString()); // // server.setP3(p3); // server.setName(name); // server.getProperties().putAll(properties); // server.setCoordinator(this); // servers.put(server.getUuid(), server); // // return server; // } // // /** // * Normalized resource usage is the sum of (resource / max resource) divided by the // * number of resources. This should be between 0 and 1. // */ // public double getNormalizedResourceUsage() { // double result = 0.0; // Map<String, Integer> available = getAvailableResources(); // for(Map.Entry<String, Integer> max : resources.entrySet()) { // if(max.getValue() <= 0) // wat // continue; // // Integer used = available.getOrDefault(max.getKey(), 0); // result += used.doubleValue() / max.getValue().doubleValue(); // } // // return result; // } // // public boolean authenticate(Commands.BaseCommand command, TransactionInfo info) // { // if (authenticators.isEmpty()) // return true; // // for (IAuthenticator auth : authenticators) // { // if (auth.hasAccess(command, info, this)) // return true; // } // // return false; // } // } // // Path: src/main/java/io/playpen/core/networking/TransactionInfo.java // @Data // public class TransactionInfo { // private String id; // // private String target = null; // // private Protocol.Transaction transaction = null; // // private ITransactionListener handler = null; // // private ScheduledFuture cancelTask = null; // // private boolean done = false; // } // Path: src/main/java/io/playpen/core/coordinator/network/authenticator/DeprovisionAuthenticator.java import io.playpen.core.coordinator.network.LocalCoordinator; import io.playpen.core.networking.TransactionInfo; import io.playpen.core.protocol.Commands; package io.playpen.core.coordinator.network.authenticator; public class DeprovisionAuthenticator implements IAuthenticator { @Override public String getName() { return "deprovision"; } @Override
public boolean hasAccess(Commands.BaseCommand command, TransactionInfo info, LocalCoordinator from) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/StringTemplateStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONArray; import org.json.JSONObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Locale;
package io.playpen.core.p3.step; @Log4j2 public class StringTemplateStep implements IPackageStep { @Override public String getStepId() { return "string-template"; } @Override
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/StringTemplateStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONArray; import org.json.JSONObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Locale; package io.playpen.core.p3.step; @Log4j2 public class StringTemplateStep implements IPackageStep { @Override public String getStepId() { return "string-template"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/StringTemplateStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONArray; import org.json.JSONObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Locale;
package io.playpen.core.p3.step; @Log4j2 public class StringTemplateStep implements IPackageStep { @Override public String getStepId() { return "string-template"; } @Override
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/StringTemplateStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONArray; import org.json.JSONObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Locale; package io.playpen.core.p3.step; @Log4j2 public class StringTemplateStep implements IPackageStep { @Override public String getStepId() { return "string-template"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/StringTemplateStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONArray; import org.json.JSONObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Locale;
for(int i = 0; i < jsonFiles.length(); ++i) { String fileName = jsonFiles.optString(i); if(fileName == null) { log.error("Unable to read files entry #" + i); return false; } File file = Paths.get(ctx.getDestination().getPath(), fileName).toFile(); if(!file.exists()) { log.error("File does not exist: " + file.getPath()); return false; } files[i] = file; } for(File file : files) { String fileContents; try { fileContents = new String(Files.readAllBytes(file.toPath())); } catch(IOException e) { log.error("Unable to read file " + file.getPath(), e); return false; } log.info("Rendering " + file.getPath()); ST template = new ST(fileContents);
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // // Path: src/main/java/io/playpen/core/utils/STUtils.java // public class STUtils { // // public static void buildSTProperties(P3Package p3, PackageContext ctx, ST template) { // template.add("package-id", p3.getId()); // template.add("package-version", p3.getVersion()); // template.add("resources", ctx.getResources()); // template.add("asset_path", Paths.get(Bootstrap.getHomeDir().getPath(), "assets").toFile().getAbsolutePath()); // template.add("server_path", ctx.getDestination().getAbsolutePath()); // // for(Map.Entry<String, String> entry : ctx.getProperties().entrySet()) { // template.add(entry.getKey(), entry.getValue()); // } // // Map<String, String> versions = new HashMap<>(); // for (P3Package p3Package : ctx.getDependencyChain()) { // versions.put(p3Package.getId(), p3Package.getVersion()); // } // versions.put(p3.getId(), p3.getVersion()); // // template.add("package_versions", versions); // } // // private STUtils() {} // } // Path: src/main/java/io/playpen/core/p3/step/StringTemplateStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import io.playpen.core.utils.STUtils; import lombok.extern.log4j.Log4j2; import org.json.JSONArray; import org.json.JSONObject; import org.stringtemplate.v4.AutoIndentWriter; import org.stringtemplate.v4.ST; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Locale; for(int i = 0; i < jsonFiles.length(); ++i) { String fileName = jsonFiles.optString(i); if(fileName == null) { log.error("Unable to read files entry #" + i); return false; } File file = Paths.get(ctx.getDestination().getPath(), fileName).toFile(); if(!file.exists()) { log.error("File does not exist: " + file.getPath()); return false; } files[i] = file; } for(File file : files) { String fileContents; try { fileContents = new String(Files.readAllBytes(file.toPath())); } catch(IOException e) { log.error("Unable to read file " + file.getPath(), e); return false; } log.info("Rendering " + file.getPath()); ST template = new ST(fileContents);
STUtils.buildSTProperties(p3, ctx, template);
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/ExpandStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.zeroturnaround.zip.ZipException; import org.zeroturnaround.zip.ZipUtil; import java.io.File;
package io.playpen.core.p3.step; @Log4j2 public class ExpandStep implements IPackageStep { @Override public String getStepId() { return "expand"; } @Override
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // Path: src/main/java/io/playpen/core/p3/step/ExpandStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.zeroturnaround.zip.ZipException; import org.zeroturnaround.zip.ZipUtil; import java.io.File; package io.playpen.core.p3.step; @Log4j2 public class ExpandStep implements IPackageStep { @Override public String getStepId() { return "expand"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/step/ExpandStep.java
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // }
import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.zeroturnaround.zip.ZipException; import org.zeroturnaround.zip.ZipUtil; import java.io.File;
package io.playpen.core.p3.step; @Log4j2 public class ExpandStep implements IPackageStep { @Override public String getStepId() { return "expand"; } @Override
// Path: src/main/java/io/playpen/core/p3/IPackageStep.java // public interface IPackageStep { // String getStepId(); // // boolean runStep(P3Package p3, PackageContext ctx, JSONObject config); // } // // Path: src/main/java/io/playpen/core/p3/P3Package.java // @Data // @Log4j2 // public class P3Package { // // @Data // public static class PackageStepConfig { // IPackageStep step; // JSONObject config; // } // // @Data // public static class P3PackageInfo { // private String id; // private String version; // // @Override // public boolean equals(Object other) { // if(other instanceof P3PackageInfo) { // P3PackageInfo o = (P3PackageInfo)other; // return id.equals(o.getId()) && version.equals(o.getVersion()); // } // // return false; // } // // @Override // public int hashCode() { // return id.hashCode() ^ version.hashCode(); // } // } // // private String localPath; // // private boolean resolved; // // // ALWAYS call calculateChecksum() before using this! // private String checksum = null; // // private String id; // // private String version; // // private List<P3Package> dependencies = new ArrayList<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private Set<String> attributes = new HashSet<>(); // // private Map<String, String> strings = new HashMap<>(); // // private List<PackageStepConfig> provisionSteps = new ArrayList<>(); // // private List<PackageStepConfig> executionSteps = new ArrayList<>(); // // private List<PackageStepConfig> shutdownSteps = new ArrayList<>(); // // /** // * Checks to make sure required fields are filled. Does not check resolution status! // */ // public boolean validate() { // if(id == null || id.isEmpty() || version == null || version.isEmpty()) // return false; // // for(P3Package p3 : dependencies) // { // if(!p3.validate()) // return false; // } // // return true; // } // // public void calculateChecksum() throws PackageException { // calculateChecksum(false); // } // // public synchronized void calculateChecksum(boolean force) throws PackageException { // if (!force && checksum != null) // return; // // if (!resolved) // throw new PackageException("Cannot calculate checksum on unresolved package"); // // if (localPath == null || localPath.isEmpty()) // throw new PackageException("Cannot calculate checksum on package with invalid localPath"); // // log.debug("Recalculating checksum on " + id + " (" + version + ")"); // // try { // checksum = AuthUtils.createPackageChecksum(localPath); // } catch (IOException e) { // throw new PackageException("Unable to calculate checksum from package file", e); // } // } // } // // Path: src/main/java/io/playpen/core/p3/PackageContext.java // @Data // public class PackageContext { // private PackageManager packageManager; // // private File destination; // // private Map<String, String> properties = new HashMap<>(); // // private Map<String, Integer> resources = new HashMap<>(); // // private List<P3Package> dependencyChain = new ArrayList<>(); // // private Object user; // } // Path: src/main/java/io/playpen/core/p3/step/ExpandStep.java import io.playpen.core.p3.IPackageStep; import io.playpen.core.p3.P3Package; import io.playpen.core.p3.PackageContext; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import org.zeroturnaround.zip.ZipException; import org.zeroturnaround.zip.ZipUtil; import java.io.File; package io.playpen.core.p3.step; @Log4j2 public class ExpandStep implements IPackageStep { @Override public String getStepId() { return "expand"; } @Override
public boolean runStep(P3Package p3, PackageContext ctx, JSONObject config) {
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/network/INetworkListener.java
// Path: src/main/java/io/playpen/core/plugin/IEventListener.java // public interface IEventListener<T extends IEventListener<T>> { // void onListenerRegistered(EventManager<T> em); // // void onListenerRemoved(EventManager<T> em); // } // // Path: src/main/java/io/playpen/core/plugin/IPlugin.java // public interface IPlugin { // void setSchema(PluginSchema schema); // // PluginSchema getSchema(); // // void setPluginDir(File pluginDir); // // File getPluginDir(); // // void setConfig(JSONObject config); // // JSONObject getConfig(); // // boolean onStart(); // // void onStop(); // }
import io.playpen.core.plugin.IEventListener; import io.playpen.core.plugin.IPlugin;
package io.playpen.core.coordinator.network; public interface INetworkListener extends IEventListener<INetworkListener> { /** * Called right after netty startup. */ void onNetworkStartup(); /** * Called right before netty shutdown. */ void onNetworkShutdown(); /** * Called after a coordinator has been created with a new keypair. * @param coordinator */ void onCoordinatorCreated(LocalCoordinator coordinator); /** * Called after a coordinator has synced. * @param coordinator */ void onCoordinatorSync(LocalCoordinator coordinator); /** * Called when the network requests provisioning of a local coordinator. * @param coordinator * @param server */ void onRequestProvision(LocalCoordinator coordinator, Server server); /** * Called when a local coordinator responds to a provision request. * @param coordinator * @param server * @param ok */ void onProvisionResponse(LocalCoordinator coordinator, Server server, boolean ok); /** * Called when the network requests deprovisioning of a server. * @param coordinator * @param server */ void onRequestDeprovision(LocalCoordinator coordinator, Server server); /** * Called when a local coordinator notifies the network of a server shutdown. * @param coordinator * @param server */ void onServerShutdown(LocalCoordinator coordinator, Server server); /** * Called when the network requests shutdown of a local coordinator. * @param coordinator */ void onRequestShutdown(LocalCoordinator coordinator); /** * Called when a plugin broadcasts a message to other plugins * @param id * @param args */
// Path: src/main/java/io/playpen/core/plugin/IEventListener.java // public interface IEventListener<T extends IEventListener<T>> { // void onListenerRegistered(EventManager<T> em); // // void onListenerRemoved(EventManager<T> em); // } // // Path: src/main/java/io/playpen/core/plugin/IPlugin.java // public interface IPlugin { // void setSchema(PluginSchema schema); // // PluginSchema getSchema(); // // void setPluginDir(File pluginDir); // // File getPluginDir(); // // void setConfig(JSONObject config); // // JSONObject getConfig(); // // boolean onStart(); // // void onStop(); // } // Path: src/main/java/io/playpen/core/coordinator/network/INetworkListener.java import io.playpen.core.plugin.IEventListener; import io.playpen.core.plugin.IPlugin; package io.playpen.core.coordinator.network; public interface INetworkListener extends IEventListener<INetworkListener> { /** * Called right after netty startup. */ void onNetworkStartup(); /** * Called right before netty shutdown. */ void onNetworkShutdown(); /** * Called after a coordinator has been created with a new keypair. * @param coordinator */ void onCoordinatorCreated(LocalCoordinator coordinator); /** * Called after a coordinator has synced. * @param coordinator */ void onCoordinatorSync(LocalCoordinator coordinator); /** * Called when the network requests provisioning of a local coordinator. * @param coordinator * @param server */ void onRequestProvision(LocalCoordinator coordinator, Server server); /** * Called when a local coordinator responds to a provision request. * @param coordinator * @param server * @param ok */ void onProvisionResponse(LocalCoordinator coordinator, Server server, boolean ok); /** * Called when the network requests deprovisioning of a server. * @param coordinator * @param server */ void onRequestDeprovision(LocalCoordinator coordinator, Server server); /** * Called when a local coordinator notifies the network of a server shutdown. * @param coordinator * @param server */ void onServerShutdown(LocalCoordinator coordinator, Server server); /** * Called when the network requests shutdown of a local coordinator. * @param coordinator */ void onRequestShutdown(LocalCoordinator coordinator); /** * Called when a plugin broadcasts a message to other plugins * @param id * @param args */
void onPluginMessage(IPlugin plugin, String id, Object... args);
PlayPen/playpen-core
src/main/java/io/playpen/core/p3/P3Package.java
// Path: src/main/java/io/playpen/core/utils/AuthUtils.java // public class AuthUtils { // // private static StandardPBEByteEncryptor getEncryptor(String key) // { // StandardPBEByteEncryptor encryptor = new StandardPBEByteEncryptor(); // encryptor.setPassword(key); // encryptor.setAlgorithm("PBEWithSHA1AndRC4_128"); // encryptor.setKeyObtentionIterations(4000); // return encryptor; // } // // public static byte[] encrypt(byte[] bytes, String key) // { // StandardPBEByteEncryptor encryptor = getEncryptor(key); // return encryptor.encrypt(bytes); // } // // public static byte[] decrypt(byte[] bytes, String key) // { // StandardPBEByteEncryptor encryptor = getEncryptor(key); // return encryptor.decrypt(bytes); // } // // public static String createHash(String key, byte[] message) { // MessageDigest digest; // // try { // digest = MessageDigest.getInstance("SHA-1"); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError(e); // } // // digest.update(message); // digest.update(key.getBytes(StandardCharsets.UTF_8)); // // return Hex.encodeHexString(digest.digest()); // } // // public static String createPackageChecksum(String fp) throws IOException { // Path path = Paths.get(fp); // try (CheckedInputStream is = new CheckedInputStream(Files.newInputStream(path), new Adler32())) { // byte[] buf = new byte[1024*1024]; // int total = 0; // int c = 0; // while (total < 100*1024*1024 && (c = is.read(buf)) >= 0) { // total += c; // } // // ByteBuffer bb = ByteBuffer.allocate(Long.BYTES); // bb.putLong(path.toFile().length()); // buf = bb.array(); // is.getChecksum().update(buf, 0, buf.length); // return Long.toHexString(is.getChecksum().getValue()); // } // } // // public static boolean validateHash(String hash, String key, String message) { // return validateHash(hash, key, message.getBytes(StandardCharsets.UTF_8)); // } // // public static boolean validateHash(String hash, String key, byte[] message) { // return hash.equals(createHash(key, message)); // } // // public static boolean validateHash(Protocol.AuthenticatedMessage payload, String key) { // return validateHash(payload.getHash(), key, payload.getPayload().toByteArray()); // } // // private AuthUtils() {} // }
import io.playpen.core.utils.AuthUtils; import lombok.Data; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import java.io.IOException; import java.util.*;
public boolean validate() { if(id == null || id.isEmpty() || version == null || version.isEmpty()) return false; for(P3Package p3 : dependencies) { if(!p3.validate()) return false; } return true; } public void calculateChecksum() throws PackageException { calculateChecksum(false); } public synchronized void calculateChecksum(boolean force) throws PackageException { if (!force && checksum != null) return; if (!resolved) throw new PackageException("Cannot calculate checksum on unresolved package"); if (localPath == null || localPath.isEmpty()) throw new PackageException("Cannot calculate checksum on package with invalid localPath"); log.debug("Recalculating checksum on " + id + " (" + version + ")"); try {
// Path: src/main/java/io/playpen/core/utils/AuthUtils.java // public class AuthUtils { // // private static StandardPBEByteEncryptor getEncryptor(String key) // { // StandardPBEByteEncryptor encryptor = new StandardPBEByteEncryptor(); // encryptor.setPassword(key); // encryptor.setAlgorithm("PBEWithSHA1AndRC4_128"); // encryptor.setKeyObtentionIterations(4000); // return encryptor; // } // // public static byte[] encrypt(byte[] bytes, String key) // { // StandardPBEByteEncryptor encryptor = getEncryptor(key); // return encryptor.encrypt(bytes); // } // // public static byte[] decrypt(byte[] bytes, String key) // { // StandardPBEByteEncryptor encryptor = getEncryptor(key); // return encryptor.decrypt(bytes); // } // // public static String createHash(String key, byte[] message) { // MessageDigest digest; // // try { // digest = MessageDigest.getInstance("SHA-1"); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError(e); // } // // digest.update(message); // digest.update(key.getBytes(StandardCharsets.UTF_8)); // // return Hex.encodeHexString(digest.digest()); // } // // public static String createPackageChecksum(String fp) throws IOException { // Path path = Paths.get(fp); // try (CheckedInputStream is = new CheckedInputStream(Files.newInputStream(path), new Adler32())) { // byte[] buf = new byte[1024*1024]; // int total = 0; // int c = 0; // while (total < 100*1024*1024 && (c = is.read(buf)) >= 0) { // total += c; // } // // ByteBuffer bb = ByteBuffer.allocate(Long.BYTES); // bb.putLong(path.toFile().length()); // buf = bb.array(); // is.getChecksum().update(buf, 0, buf.length); // return Long.toHexString(is.getChecksum().getValue()); // } // } // // public static boolean validateHash(String hash, String key, String message) { // return validateHash(hash, key, message.getBytes(StandardCharsets.UTF_8)); // } // // public static boolean validateHash(String hash, String key, byte[] message) { // return hash.equals(createHash(key, message)); // } // // public static boolean validateHash(Protocol.AuthenticatedMessage payload, String key) { // return validateHash(payload.getHash(), key, payload.getPayload().toByteArray()); // } // // private AuthUtils() {} // } // Path: src/main/java/io/playpen/core/p3/P3Package.java import io.playpen.core.utils.AuthUtils; import lombok.Data; import lombok.extern.log4j.Log4j2; import org.json.JSONObject; import java.io.IOException; import java.util.*; public boolean validate() { if(id == null || id.isEmpty() || version == null || version.isEmpty()) return false; for(P3Package p3 : dependencies) { if(!p3.validate()) return false; } return true; } public void calculateChecksum() throws PackageException { calculateChecksum(false); } public synchronized void calculateChecksum(boolean force) throws PackageException { if (!force && checksum != null) return; if (!resolved) throw new PackageException("Cannot calculate checksum on unresolved package"); if (localPath == null || localPath.isEmpty()) throw new PackageException("Cannot calculate checksum on package with invalid localPath"); log.debug("Recalculating checksum on " + id + " (" + version + ")"); try {
checksum = AuthUtils.createPackageChecksum(localPath);
PlayPen/playpen-core
src/main/java/io/playpen/core/coordinator/local/ConsoleMessageListener.java
// Path: src/main/java/io/playpen/core/utils/process/IProcessListener.java // public interface IProcessListener { // void onProcessAttach(XProcess proc); // void onProcessDetach(XProcess proc); // void onProcessOutput(XProcess proc, String out); // void onProcessInput(XProcess proc, String in); // void onProcessEnd(XProcess proc); // } // // Path: src/main/java/io/playpen/core/utils/process/XProcess.java // @Log4j2 // public class XProcess extends NuAbstractCharsetHandler { // public static final int MAX_LINE_STORAGE = 25; // // private final List<String> command; // private final String workingDir; // private NuProcess process = null; // private final List<IProcessListener> listeners = new CopyOnWriteArrayList<>(); // private final OutputBuffer outputBuffer = new OutputBuffer(); // private final Map<String, String> environment; // private boolean wait; // // @Getter // private ConcurrentLinkedQueue<String> lastLines = new ConcurrentLinkedQueue<>(); // // public XProcess(List<String> command, String workingDir, Map<String, String> environment, boolean wait) { // super(StandardCharsets.UTF_8); // this.command = command; // this.workingDir = workingDir; // this.environment = environment; // this.wait = wait; // } // // public void addListener(IProcessListener listener) { // listeners.add(listener); // listener.onProcessAttach(this); // } // // public void removeListener(IProcessListener listener) { // listeners.remove(listener); // listener.onProcessDetach(this); // } // // public void sendInput(String in) { // byte[] inAsBytes = in.getBytes(StandardCharsets.UTF_8); // process.writeStdin(ByteBuffer.wrap(inAsBytes)); // // for(IProcessListener listener : listeners) { // listener.onProcessInput(this, in); // } // } // // public boolean run() { // NuProcessBuilder builder = new NuProcessBuilder(command); // builder.setCwd(Paths.get(workingDir)); // builder.setProcessListener(this); // builder.environment().putAll(environment); // process = builder.start(); // // if (wait) { // try { // process.waitFor(0, TimeUnit.SECONDS); // } catch (InterruptedException e) { // log.info("Interrupted while waiting for process to complete", e); // } // } // // return true; // } // // public boolean isRunning() { // return process.isRunning(); // } // // public void stop() { // process.destroy(true); // try { // process.waitFor(5, TimeUnit.SECONDS); // } // catch (InterruptedException e) { // log.info("Interrupted while waiting for process to shutdown", e); // } // } // // @Override // protected void onStdoutChars(CharBuffer buffer, boolean closed, CoderResult coderResult) { // outputBuffer.append(buffer); // } // // @Override // protected void onStderrChars(CharBuffer buffer, boolean closed, CoderResult coderResult) { // onStdoutChars(buffer, closed, coderResult); // } // // @Override // public void onExit(int exitCode) { // for (IProcessListener listener : listeners) { // listener.onProcessEnd(this); // } // } // // protected void receiveOutput(String out) { // for(IProcessListener listener : listeners) { // listener.onProcessOutput(this, out); // } // // lastLines.add(out); // if (lastLines.size() > MAX_LINE_STORAGE) // lastLines.remove(); // } // // private class OutputBuffer extends ProcessBuffer { // @Override // protected void onOutput(String output) { // receiveOutput(output); // } // } // }
import io.playpen.core.utils.process.IProcessListener; import io.playpen.core.utils.process.XProcess;
package io.playpen.core.coordinator.local; public class ConsoleMessageListener implements IProcessListener { private String consoleId = null;
// Path: src/main/java/io/playpen/core/utils/process/IProcessListener.java // public interface IProcessListener { // void onProcessAttach(XProcess proc); // void onProcessDetach(XProcess proc); // void onProcessOutput(XProcess proc, String out); // void onProcessInput(XProcess proc, String in); // void onProcessEnd(XProcess proc); // } // // Path: src/main/java/io/playpen/core/utils/process/XProcess.java // @Log4j2 // public class XProcess extends NuAbstractCharsetHandler { // public static final int MAX_LINE_STORAGE = 25; // // private final List<String> command; // private final String workingDir; // private NuProcess process = null; // private final List<IProcessListener> listeners = new CopyOnWriteArrayList<>(); // private final OutputBuffer outputBuffer = new OutputBuffer(); // private final Map<String, String> environment; // private boolean wait; // // @Getter // private ConcurrentLinkedQueue<String> lastLines = new ConcurrentLinkedQueue<>(); // // public XProcess(List<String> command, String workingDir, Map<String, String> environment, boolean wait) { // super(StandardCharsets.UTF_8); // this.command = command; // this.workingDir = workingDir; // this.environment = environment; // this.wait = wait; // } // // public void addListener(IProcessListener listener) { // listeners.add(listener); // listener.onProcessAttach(this); // } // // public void removeListener(IProcessListener listener) { // listeners.remove(listener); // listener.onProcessDetach(this); // } // // public void sendInput(String in) { // byte[] inAsBytes = in.getBytes(StandardCharsets.UTF_8); // process.writeStdin(ByteBuffer.wrap(inAsBytes)); // // for(IProcessListener listener : listeners) { // listener.onProcessInput(this, in); // } // } // // public boolean run() { // NuProcessBuilder builder = new NuProcessBuilder(command); // builder.setCwd(Paths.get(workingDir)); // builder.setProcessListener(this); // builder.environment().putAll(environment); // process = builder.start(); // // if (wait) { // try { // process.waitFor(0, TimeUnit.SECONDS); // } catch (InterruptedException e) { // log.info("Interrupted while waiting for process to complete", e); // } // } // // return true; // } // // public boolean isRunning() { // return process.isRunning(); // } // // public void stop() { // process.destroy(true); // try { // process.waitFor(5, TimeUnit.SECONDS); // } // catch (InterruptedException e) { // log.info("Interrupted while waiting for process to shutdown", e); // } // } // // @Override // protected void onStdoutChars(CharBuffer buffer, boolean closed, CoderResult coderResult) { // outputBuffer.append(buffer); // } // // @Override // protected void onStderrChars(CharBuffer buffer, boolean closed, CoderResult coderResult) { // onStdoutChars(buffer, closed, coderResult); // } // // @Override // public void onExit(int exitCode) { // for (IProcessListener listener : listeners) { // listener.onProcessEnd(this); // } // } // // protected void receiveOutput(String out) { // for(IProcessListener listener : listeners) { // listener.onProcessOutput(this, out); // } // // lastLines.add(out); // if (lastLines.size() > MAX_LINE_STORAGE) // lastLines.remove(); // } // // private class OutputBuffer extends ProcessBuffer { // @Override // protected void onOutput(String output) { // receiveOutput(output); // } // } // } // Path: src/main/java/io/playpen/core/coordinator/local/ConsoleMessageListener.java import io.playpen.core.utils.process.IProcessListener; import io.playpen.core.utils.process.XProcess; package io.playpen.core.coordinator.local; public class ConsoleMessageListener implements IProcessListener { private String consoleId = null;
private XProcess process = null;
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/Bucket4jCacheConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java // @Configuration // @ConditionalOnClass({ HazelcastInstance.class }) // @ConditionalOnBean(HazelcastInstance.class) // public class HazelcastBucket4jCacheConfiguration { // // private HazelcastInstance hazelcastInstance; // // public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Bean // public AsyncCacheResolver hazelcastCacheResolver() { // return new HazelcastCacheResolver(hazelcastInstance); // } // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheContainer.class) // public class InfinispanJCacheBucket4jConfiguration { // // private CacheContainer cacheContainer; // // public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new InfinispanJCacheCacheResolver(cacheContainer); // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // }
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast.HazelcastBucket4jCacheConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.InfinispanJCacheBucket4jConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration;
package com.giffing.bucket4j.spring.boot.starter.config.cache; @Configuration @AutoConfigureAfter(CacheAutoConfiguration.class)
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java // @Configuration // @ConditionalOnClass({ HazelcastInstance.class }) // @ConditionalOnBean(HazelcastInstance.class) // public class HazelcastBucket4jCacheConfiguration { // // private HazelcastInstance hazelcastInstance; // // public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Bean // public AsyncCacheResolver hazelcastCacheResolver() { // return new HazelcastCacheResolver(hazelcastInstance); // } // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheContainer.class) // public class InfinispanJCacheBucket4jConfiguration { // // private CacheContainer cacheContainer; // // public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new InfinispanJCacheCacheResolver(cacheContainer); // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/Bucket4jCacheConfiguration.java import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast.HazelcastBucket4jCacheConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.InfinispanJCacheBucket4jConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration; package com.giffing.bucket4j.spring.boot.starter.config.cache; @Configuration @AutoConfigureAfter(CacheAutoConfiguration.class)
@Import(value = {JCacheBucket4jConfiguration.class, InfinispanJCacheBucket4jConfiguration.class, HazelcastBucket4jCacheConfiguration.class})
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/Bucket4jCacheConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java // @Configuration // @ConditionalOnClass({ HazelcastInstance.class }) // @ConditionalOnBean(HazelcastInstance.class) // public class HazelcastBucket4jCacheConfiguration { // // private HazelcastInstance hazelcastInstance; // // public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Bean // public AsyncCacheResolver hazelcastCacheResolver() { // return new HazelcastCacheResolver(hazelcastInstance); // } // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheContainer.class) // public class InfinispanJCacheBucket4jConfiguration { // // private CacheContainer cacheContainer; // // public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new InfinispanJCacheCacheResolver(cacheContainer); // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // }
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast.HazelcastBucket4jCacheConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.InfinispanJCacheBucket4jConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration;
package com.giffing.bucket4j.spring.boot.starter.config.cache; @Configuration @AutoConfigureAfter(CacheAutoConfiguration.class)
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java // @Configuration // @ConditionalOnClass({ HazelcastInstance.class }) // @ConditionalOnBean(HazelcastInstance.class) // public class HazelcastBucket4jCacheConfiguration { // // private HazelcastInstance hazelcastInstance; // // public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Bean // public AsyncCacheResolver hazelcastCacheResolver() { // return new HazelcastCacheResolver(hazelcastInstance); // } // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheContainer.class) // public class InfinispanJCacheBucket4jConfiguration { // // private CacheContainer cacheContainer; // // public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new InfinispanJCacheCacheResolver(cacheContainer); // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/Bucket4jCacheConfiguration.java import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast.HazelcastBucket4jCacheConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.InfinispanJCacheBucket4jConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration; package com.giffing.bucket4j.spring.boot.starter.config.cache; @Configuration @AutoConfigureAfter(CacheAutoConfiguration.class)
@Import(value = {JCacheBucket4jConfiguration.class, InfinispanJCacheBucket4jConfiguration.class, HazelcastBucket4jCacheConfiguration.class})
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/Bucket4jCacheConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java // @Configuration // @ConditionalOnClass({ HazelcastInstance.class }) // @ConditionalOnBean(HazelcastInstance.class) // public class HazelcastBucket4jCacheConfiguration { // // private HazelcastInstance hazelcastInstance; // // public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Bean // public AsyncCacheResolver hazelcastCacheResolver() { // return new HazelcastCacheResolver(hazelcastInstance); // } // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheContainer.class) // public class InfinispanJCacheBucket4jConfiguration { // // private CacheContainer cacheContainer; // // public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new InfinispanJCacheCacheResolver(cacheContainer); // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // }
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast.HazelcastBucket4jCacheConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.InfinispanJCacheBucket4jConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration;
package com.giffing.bucket4j.spring.boot.starter.config.cache; @Configuration @AutoConfigureAfter(CacheAutoConfiguration.class)
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java // @Configuration // @ConditionalOnClass({ HazelcastInstance.class }) // @ConditionalOnBean(HazelcastInstance.class) // public class HazelcastBucket4jCacheConfiguration { // // private HazelcastInstance hazelcastInstance; // // public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { // this.hazelcastInstance = hazelcastInstance; // } // // @Bean // public AsyncCacheResolver hazelcastCacheResolver() { // return new HazelcastCacheResolver(hazelcastInstance); // } // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheContainer.class) // public class InfinispanJCacheBucket4jConfiguration { // // private CacheContainer cacheContainer; // // public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new InfinispanJCacheCacheResolver(cacheContainer); // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/Bucket4jCacheConfiguration.java import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast.HazelcastBucket4jCacheConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.InfinispanJCacheBucket4jConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration; package com.giffing.bucket4j.spring.boot.starter.config.cache; @Configuration @AutoConfigureAfter(CacheAutoConfiguration.class)
@Import(value = {JCacheBucket4jConfiguration.class, InfinispanJCacheBucket4jConfiguration.class, HazelcastBucket4jCacheConfiguration.class})
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // }
import javax.cache.CacheManager; import javax.cache.Caching; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver;
package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; @Configuration @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) @ConditionalOnBean(CacheManager.class) public class JCacheBucket4jConfiguration { private CacheManager cacheManager; public JCacheBucket4jConfiguration(CacheManager cacheManager){ this.cacheManager = cacheManager; } @Bean
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java import javax.cache.CacheManager; import javax.cache.Caching; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; @Configuration @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) @ConditionalOnBean(CacheManager.class) public class JCacheBucket4jConfiguration { private CacheManager cacheManager; public JCacheBucket4jConfiguration(CacheManager cacheManager){ this.cacheManager = cacheManager; } @Bean
public SyncCacheResolver bucket4jCacheResolver() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/MetricTag.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // }
import java.util.Arrays; import java.util.List; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType;
package com.giffing.bucket4j.spring.boot.starter.context.properties; public class MetricTag { private String key; private String expression;
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // } // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/MetricTag.java import java.util.Arrays; import java.util.List; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; package com.giffing.bucket4j.spring.boot.starter.context.properties; public class MetricTag { private String key; private String expression;
private List<MetricType> types = Arrays.asList(MetricType.values());
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/FilterConfiguration.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitCheck.java // @FunctionalInterface // public interface RateLimitCheck<R> { // // /** // * @param request the request information object // * // * @return null if no rate limit should be performed. (maybe skipped or shouldn't be executed). // */ // ConsumptionProbeHolder rateLimit(R request, boolean async); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java // public enum RateLimitConditionMatchingStrategy { // // /** // * All rate limits should be evaluated // */ // ALL, // /** // * Only the first matching rate limit will be evaluated // */ // FIRST, // // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitCheck; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy;
package com.giffing.bucket4j.spring.boot.starter.context.properties; /** * This class is the main configuration class which is used to build the servlet|webflux|gateway request filter * */ public class FilterConfiguration<R> { private RateLimitConditionMatchingStrategy strategy = RateLimitConditionMatchingStrategy.FIRST; /** * The url on which the filter should listen. */ private String url; /** * The order of the filter depending on other filters independently from the Bucket4j filters. */ private int order; /** * Hides the HTTP response headers * x-rate-limit-remaining * x-rate-limit-retry-after-seconds */ private Boolean hideHttpResponseHeaders = Boolean.FALSE; /** * The HTTP response body which should be returned when limiting the rate. */ private String httpResponseBody; private Map<String, String> httpResponseHeaders;
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitCheck.java // @FunctionalInterface // public interface RateLimitCheck<R> { // // /** // * @param request the request information object // * // * @return null if no rate limit should be performed. (maybe skipped or shouldn't be executed). // */ // ConsumptionProbeHolder rateLimit(R request, boolean async); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java // public enum RateLimitConditionMatchingStrategy { // // /** // * All rate limits should be evaluated // */ // ALL, // /** // * Only the first matching rate limit will be evaluated // */ // FIRST, // // } // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/FilterConfiguration.java import java.util.ArrayList; import java.util.List; import java.util.Map; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitCheck; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy; package com.giffing.bucket4j.spring.boot.starter.context.properties; /** * This class is the main configuration class which is used to build the servlet|webflux|gateway request filter * */ public class FilterConfiguration<R> { private RateLimitConditionMatchingStrategy strategy = RateLimitConditionMatchingStrategy.FIRST; /** * The url on which the filter should listen. */ private String url; /** * The order of the filter depending on other filters independently from the Bucket4j filters. */ private int order; /** * Hides the HTTP response headers * x-rate-limit-remaining * x-rate-limit-retry-after-seconds */ private Boolean hideHttpResponseHeaders = Boolean.FALSE; /** * The HTTP response body which should be returned when limiting the rate. */ private String httpResponseBody; private Map<String, String> httpResponseHeaders;
private List<RateLimitCheck<R>> rateLimitChecks = new ArrayList<>();
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/infinispan/InfinispanCacheResolver.java // public class InfinispanCacheResolver implements AsyncCacheResolver { // // private CacheContainer cacheContainer; // // public InfinispanCacheResolver(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Override // public ProxyManager<String> resolve(String cacheName) { // Cache<String, byte[]> cache = cacheContainer.getCache(cacheName); // // // // TODO how to create an instance of ReadWriteMap // return new InfinispanProxyManager<>(toMap(cache)); // } // // private static FunctionalMap.ReadWriteMap<String, byte[]> toMap(Cache<String, byte[]> cache) { // AdvancedCache<String, byte[]> advancedCache = cache.getAdvancedCache(); // FunctionalMapImpl<String, byte[]> functionalMap = FunctionalMapImpl.create(advancedCache); // return ReadWriteMapImpl.create(functionalMap); // } // // }
import javax.cache.Caching; import org.infinispan.manager.CacheContainer; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.config.cache.infinispan.InfinispanCacheResolver;
package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; /** * The configuration class for Infinispan. Infinispan is not directly supported by * bucket4j. See {@link InfinispanCacheResolver} for more informations. */ @Configuration @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) @ConditionalOnBean(CacheContainer.class) public class InfinispanJCacheBucket4jConfiguration { private CacheContainer cacheContainer; public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { this.cacheContainer = cacheContainer; } @Bean
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/infinispan/InfinispanCacheResolver.java // public class InfinispanCacheResolver implements AsyncCacheResolver { // // private CacheContainer cacheContainer; // // public InfinispanCacheResolver(CacheContainer cacheContainer) { // this.cacheContainer = cacheContainer; // } // // @Override // public ProxyManager<String> resolve(String cacheName) { // Cache<String, byte[]> cache = cacheContainer.getCache(cacheName); // // // // TODO how to create an instance of ReadWriteMap // return new InfinispanProxyManager<>(toMap(cache)); // } // // private static FunctionalMap.ReadWriteMap<String, byte[]> toMap(Cache<String, byte[]> cache) { // AdvancedCache<String, byte[]> advancedCache = cache.getAdvancedCache(); // FunctionalMapImpl<String, byte[]> functionalMap = FunctionalMapImpl.create(advancedCache); // return ReadWriteMapImpl.create(functionalMap); // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheBucket4jConfiguration.java import javax.cache.Caching; import org.infinispan.manager.CacheContainer; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.config.cache.infinispan.InfinispanCacheResolver; package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; /** * The configuration class for Infinispan. Infinispan is not directly supported by * bucket4j. See {@link InfinispanCacheResolver} for more informations. */ @Configuration @ConditionalOnClass({ CacheContainer.class, Caching.class, JCacheCacheManager.class }) @ConditionalOnBean(CacheContainer.class) public class InfinispanJCacheBucket4jConfiguration { private CacheContainer cacheContainer; public InfinispanJCacheBucket4jConfiguration(CacheContainer cacheContainer) { this.cacheContainer = cacheContainer; } @Bean
public SyncCacheResolver bucket4jCacheResolver() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/webflux/Bucket4JAutoConfigurationWebfluxFilterBeans.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // }
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelCompilerMode; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder;
package com.giffing.bucket4j.spring.boot.starter.config.webflux; @Configuration public class Bucket4JAutoConfigurationWebfluxFilterBeans { @Bean @Qualifier("WEBFLUX")
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/webflux/Bucket4JAutoConfigurationWebfluxFilterBeans.java import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelCompilerMode; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; package com.giffing.bucket4j.spring.boot.starter.config.webflux; @Configuration public class Bucket4JAutoConfigurationWebfluxFilterBeans { @Bean @Qualifier("WEBFLUX")
public Bucket4jConfigurationHolder servletConfigurationHolder() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/ignite/IgniteBucket4jCacheConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/AsyncCacheResolver.java // public interface AsyncCacheResolver extends CacheResolver { // // }
import org.apache.ignite.Ignite; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver;
package com.giffing.bucket4j.spring.boot.starter.config.cache.ignite; @Configuration @ConditionalOnClass({ Ignite.class }) @ConditionalOnBean(Ignite.class) public class IgniteBucket4jCacheConfiguration { private Ignite ignite; public IgniteBucket4jCacheConfiguration(Ignite ignite) { this.ignite = ignite; } @Bean
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/AsyncCacheResolver.java // public interface AsyncCacheResolver extends CacheResolver { // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/ignite/IgniteBucket4jCacheConfiguration.java import org.apache.ignite.Ignite; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver; package com.giffing.bucket4j.spring.boot.starter.config.cache.ignite; @Configuration @ConditionalOnClass({ Ignite.class }) @ConditionalOnBean(Ignite.class) public class IgniteBucket4jCacheConfiguration { private Ignite ignite; public IgniteBucket4jCacheConfiguration(Ignite ignite) { this.ignite = ignite; } @Bean
public AsyncCacheResolver hazelcastCacheResolver() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricHandler.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricTagResult.java // public class MetricTagResult { // // private String key; // // private String value; // // private List<MetricType> types; // // public MetricTagResult(String key, String value, List<MetricType> types) { // this.key = key; // this.value = value; // this.setTypes(types); // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public List<MetricType> getTypes() { // return types; // } // // public void setTypes(List<MetricType> types) { // this.types = types; // } // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // }
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; import io.micrometer.core.instrument.Metrics;
package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Component @Primary
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricTagResult.java // public class MetricTagResult { // // private String key; // // private String value; // // private List<MetricType> types; // // public MetricTagResult(String key, String value, List<MetricType> types) { // this.key = key; // this.value = value; // this.setTypes(types); // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public List<MetricType> getTypes() { // return types; // } // // public void setTypes(List<MetricType> types) { // this.types = types; // } // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricHandler.java import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; import io.micrometer.core.instrument.Metrics; package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Component @Primary
public class Bucket4jMetricHandler implements MetricHandler {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricHandler.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricTagResult.java // public class MetricTagResult { // // private String key; // // private String value; // // private List<MetricType> types; // // public MetricTagResult(String key, String value, List<MetricType> types) { // this.key = key; // this.value = value; // this.setTypes(types); // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public List<MetricType> getTypes() { // return types; // } // // public void setTypes(List<MetricType> types) { // this.types = types; // } // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // }
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; import io.micrometer.core.instrument.Metrics;
package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Component @Primary public class Bucket4jMetricHandler implements MetricHandler { @Override
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricTagResult.java // public class MetricTagResult { // // private String key; // // private String value; // // private List<MetricType> types; // // public MetricTagResult(String key, String value, List<MetricType> types) { // this.key = key; // this.value = value; // this.setTypes(types); // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public List<MetricType> getTypes() { // return types; // } // // public void setTypes(List<MetricType> types) { // this.types = types; // } // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricHandler.java import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; import io.micrometer.core.instrument.Metrics; package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Component @Primary public class Bucket4jMetricHandler implements MetricHandler { @Override
public void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags) {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricHandler.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricTagResult.java // public class MetricTagResult { // // private String key; // // private String value; // // private List<MetricType> types; // // public MetricTagResult(String key, String value, List<MetricType> types) { // this.key = key; // this.value = value; // this.setTypes(types); // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public List<MetricType> getTypes() { // return types; // } // // public void setTypes(List<MetricType> types) { // this.types = types; // } // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // }
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; import io.micrometer.core.instrument.Metrics;
package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Component @Primary public class Bucket4jMetricHandler implements MetricHandler { @Override
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricTagResult.java // public class MetricTagResult { // // private String key; // // private String value; // // private List<MetricType> types; // // public MetricTagResult(String key, String value, List<MetricType> types) { // this.key = key; // this.value = value; // this.setTypes(types); // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public List<MetricType> getTypes() { // return types; // } // // public void setTypes(List<MetricType> types) { // this.types = types; // } // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricHandler.java import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; import io.micrometer.core.instrument.Metrics; package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Component @Primary public class Bucket4jMetricHandler implements MetricHandler { @Override
public void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags) {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/AsyncCacheResolver.java // public interface AsyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // }
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration; import com.hazelcast.core.HazelcastInstance;
package com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast; /** * Configures the asynchronous support for Hazelcast. The synchronous support of Hazelcast * is already provided by the {@link JCacheBucket4jConfiguration}. It uses the {@link HazelcastInstance} * to access the {@link HazelcastInstance} to retrieve the cache. */ @Configuration @ConditionalOnClass({ HazelcastInstance.class }) @ConditionalOnBean(HazelcastInstance.class) public class HazelcastBucket4jCacheConfiguration { private HazelcastInstance hazelcastInstance; public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } @Bean
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/AsyncCacheResolver.java // public interface AsyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheBucket4jConfiguration.java // @Configuration // @ConditionalOnClass({ Caching.class, JCacheCacheManager.class }) // @ConditionalOnBean(CacheManager.class) // public class JCacheBucket4jConfiguration { // private CacheManager cacheManager; // // public JCacheBucket4jConfiguration(CacheManager cacheManager){ // this.cacheManager = cacheManager; // } // // @Bean // public SyncCacheResolver bucket4jCacheResolver() { // return new JCacheCacheResolver(cacheManager); // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/hazelcast/HazelcastBucket4jCacheConfiguration.java import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheBucket4jConfiguration; import com.hazelcast.core.HazelcastInstance; package com.giffing.bucket4j.spring.boot.starter.config.cache.hazelcast; /** * Configures the asynchronous support for Hazelcast. The synchronous support of Hazelcast * is already provided by the {@link JCacheBucket4jConfiguration}. It uses the {@link HazelcastInstance} * to access the {@link HazelcastInstance} to retrieve the cache. */ @Configuration @ConditionalOnClass({ HazelcastInstance.class }) @ConditionalOnBean(HazelcastInstance.class) public class HazelcastBucket4jCacheConfiguration { private HazelcastInstance hazelcastInstance; public HazelcastBucket4jCacheConfiguration(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } @Bean
public AsyncCacheResolver hazelcastCacheResolver() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Metrics.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType;
package com.giffing.bucket4j.spring.boot.starter.context.properties; public class Metrics { private boolean enabled = true;
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricType.java // public enum MetricType { // // CONSUMED_COUNTER, // REJECTED_COUNTER // } // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Metrics.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricType; package com.giffing.bucket4j.spring.boot.starter.context.properties; public class Metrics { private boolean enabled = true;
private List<MetricType> types = Arrays.asList(MetricType.values());
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/infinispan/InfinispanBucket4jCacheConfiguration.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/AsyncCacheResolver.java // public interface AsyncCacheResolver extends CacheResolver { // // }
import org.infinispan.manager.CacheContainer; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver;
package com.giffing.bucket4j.spring.boot.starter.config.cache.infinispan; @Configuration @ConditionalOnClass({ CacheContainer.class }) @ConditionalOnBean(CacheContainer.class) public class InfinispanBucket4jCacheConfiguration { private CacheContainer cacheContainer; public InfinispanBucket4jCacheConfiguration(CacheContainer cacheContainer) { this.cacheContainer = cacheContainer; } @Bean
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/AsyncCacheResolver.java // public interface AsyncCacheResolver extends CacheResolver { // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/infinispan/InfinispanBucket4jCacheConfiguration.java import org.infinispan.manager.CacheContainer; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver; package com.giffing.bucket4j.spring.boot.starter.config.cache.infinispan; @Configuration @ConditionalOnClass({ CacheContainer.class }) @ConditionalOnBean(CacheContainer.class) public class InfinispanBucket4jCacheConfiguration { private CacheContainer cacheContainer; public InfinispanBucket4jCacheConfiguration(CacheContainer cacheContainer) { this.cacheContainer = cacheContainer; } @Bean
public AsyncCacheResolver infinispanCacheResolver() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JConfiguration.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/FilterMethod.java // public enum FilterMethod { // // /** // * Servlet Request Filter // */ // SERVLET, // // /** // * Spring Boots 5 async WebFilter // */ // WEBFLUX, // // /** // * Spring Cloud Gateway GlobalFilter // */ // // GATEWAY; // // // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java // public enum RateLimitConditionMatchingStrategy { // // /** // * All rate limits should be evaluated // */ // ALL, // /** // * Only the first matching rate limit will be evaluated // */ // FIRST, // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.core.Ordered; import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy;
package com.giffing.bucket4j.spring.boot.starter.context.properties; public class Bucket4JConfiguration { /** * The cache name. Should be provided or an exception is thrown */ private String cacheName = "buckets"; /** * The default {@link FilterMethod} is {@link FilterMethod#SERVLET} */
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/FilterMethod.java // public enum FilterMethod { // // /** // * Servlet Request Filter // */ // SERVLET, // // /** // * Spring Boots 5 async WebFilter // */ // WEBFLUX, // // /** // * Spring Cloud Gateway GlobalFilter // */ // // GATEWAY; // // // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java // public enum RateLimitConditionMatchingStrategy { // // /** // * All rate limits should be evaluated // */ // ALL, // /** // * Only the first matching rate limit will be evaluated // */ // FIRST, // // } // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JConfiguration.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.core.Ordered; import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy; package com.giffing.bucket4j.spring.boot.starter.context.properties; public class Bucket4JConfiguration { /** * The cache name. Should be provided or an exception is thrown */ private String cacheName = "buckets"; /** * The default {@link FilterMethod} is {@link FilterMethod#SERVLET} */
private FilterMethod filterMethod = FilterMethod.SERVLET;
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JConfiguration.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/FilterMethod.java // public enum FilterMethod { // // /** // * Servlet Request Filter // */ // SERVLET, // // /** // * Spring Boots 5 async WebFilter // */ // WEBFLUX, // // /** // * Spring Cloud Gateway GlobalFilter // */ // // GATEWAY; // // // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java // public enum RateLimitConditionMatchingStrategy { // // /** // * All rate limits should be evaluated // */ // ALL, // /** // * Only the first matching rate limit will be evaluated // */ // FIRST, // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.core.Ordered; import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy;
package com.giffing.bucket4j.spring.boot.starter.context.properties; public class Bucket4JConfiguration { /** * The cache name. Should be provided or an exception is thrown */ private String cacheName = "buckets"; /** * The default {@link FilterMethod} is {@link FilterMethod#SERVLET} */ private FilterMethod filterMethod = FilterMethod.SERVLET; /** * The default strategy is {@link RateLimitConditionMatchingStrategy#FIRST}. */
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/FilterMethod.java // public enum FilterMethod { // // /** // * Servlet Request Filter // */ // SERVLET, // // /** // * Spring Boots 5 async WebFilter // */ // WEBFLUX, // // /** // * Spring Cloud Gateway GlobalFilter // */ // // GATEWAY; // // // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java // public enum RateLimitConditionMatchingStrategy { // // /** // * All rate limits should be evaluated // */ // ALL, // /** // * Only the first matching rate limit will be evaluated // */ // FIRST, // // } // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JConfiguration.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.core.Ordered; import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy; package com.giffing.bucket4j.spring.boot.starter.context.properties; public class Bucket4JConfiguration { /** * The cache name. Should be provided or an exception is thrown */ private String cacheName = "buckets"; /** * The default {@link FilterMethod} is {@link FilterMethod#SERVLET} */ private FilterMethod filterMethod = FilterMethod.SERVLET; /** * The default strategy is {@link RateLimitConditionMatchingStrategy#FIRST}. */
private RateLimitConditionMatchingStrategy strategy = RateLimitConditionMatchingStrategy.FIRST;
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheCacheResolver.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // }
import io.github.bucket4j.distributed.proxy.ProxyManager; import io.github.bucket4j.grid.infinispan.InfinispanProxyManager; import org.infinispan.Cache; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.manager.CacheContainer; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import io.github.bucket4j.Bucket4j;
package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; /** * To use Infinispan you need a special bucket4j-infinispan dependency. * * https://github.com/vladimir-bukhtoyarov/bucket4j/blob/master/doc-pages/infinispan.md * * Question: Bucket4j already supports JCache since version 1.2. Why it was needed to introduce direct support for Infinispan? * * Answer: When you want to use Bucket4j together with Infinispan, you must always use bucket4j-infinispan module instead of bucket4j-jcache, * because Infinispan does not provide mutual exclusion for entry-processors. Any attempt to use Infinispan via bucket4j-jcache will be * failed with UnsupportedOperationException exception at bucket construction time. * */ public class InfinispanJCacheCacheResolver implements SyncCacheResolver { private CacheContainer cacheContainer; public InfinispanJCacheCacheResolver(CacheContainer cacheContainer) { this.cacheContainer = cacheContainer; } public ProxyManager<String> resolve(String cacheName) { Cache<Object, Object> cache = cacheContainer.getCache(cacheName); if (cache == null) {
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/InfinispanJCacheCacheResolver.java import io.github.bucket4j.distributed.proxy.ProxyManager; import io.github.bucket4j.grid.infinispan.InfinispanProxyManager; import org.infinispan.Cache; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.manager.CacheContainer; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import io.github.bucket4j.Bucket4j; package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; /** * To use Infinispan you need a special bucket4j-infinispan dependency. * * https://github.com/vladimir-bukhtoyarov/bucket4j/blob/master/doc-pages/infinispan.md * * Question: Bucket4j already supports JCache since version 1.2. Why it was needed to introduce direct support for Infinispan? * * Answer: When you want to use Bucket4j together with Infinispan, you must always use bucket4j-infinispan module instead of bucket4j-jcache, * because Infinispan does not provide mutual exclusion for entry-processors. Any attempt to use Infinispan via bucket4j-jcache will be * failed with UnsupportedOperationException exception at bucket construction time. * */ public class InfinispanJCacheCacheResolver implements SyncCacheResolver { private CacheContainer cacheContainer; public InfinispanJCacheCacheResolver(CacheContainer cacheContainer) { this.cacheContainer = cacheContainer; } public ProxyManager<String> resolve(String cacheName) { Cache<Object, Object> cache = cacheContainer.getCache(cacheName); if (cache == null) {
throw new JCacheNotFoundException(cacheName);
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // }
import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder;
package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Configuration @ConditionalOnClass(Endpoint.class) public class Bucket4jEndpoint { @Configuration @Endpoint(id = "bucket4j") public static class Bucket4jEndpointConfig { @Autowired(required = false) @Qualifier("SERVLET")
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Configuration @ConditionalOnClass(Endpoint.class) public class Bucket4jEndpoint { @Configuration @Endpoint(id = "bucket4j") public static class Bucket4jEndpointConfig { @Autowired(required = false) @Qualifier("SERVLET")
private Bucket4jConfigurationHolder servletConfigs;
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // }
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelCompilerMode; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder;
package com.giffing.bucket4j.spring.boot.starter.config.gateway; @Configuration public class Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans { @Bean @Qualifier("GATEWAY")
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.java import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelCompilerMode; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; package com.giffing.bucket4j.spring.boot.starter.config.gateway; @Configuration public class Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans { @Bean @Qualifier("GATEWAY")
public Bucket4jConfigurationHolder gatewayConfigurationHolder() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // }
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException;
package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage();
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException; package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage();
if(cause instanceof JCacheNotFoundException) {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // }
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException;
package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage(); if(cause instanceof JCacheNotFoundException) { JCacheNotFoundException ex = (JCacheNotFoundException) cause; descriptionMessage = "The cache name name defined in the property is not configured in the caching provider"; actionMessage = "Cache name: " + ex.getCacheName() + newline + "Please configure your caching provider (ehcache, hazelcast, ...)"; }
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException; package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage(); if(cause instanceof JCacheNotFoundException) { JCacheNotFoundException ex = (JCacheNotFoundException) cause; descriptionMessage = "The cache name name defined in the property is not configured in the caching provider"; actionMessage = "Cache name: " + ex.getCacheName() + newline + "Please configure your caching provider (ehcache, hazelcast, ...)"; }
if(cause instanceof MissingKeyFilterExpressionException) {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // }
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException;
package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage(); if(cause instanceof JCacheNotFoundException) { JCacheNotFoundException ex = (JCacheNotFoundException) cause; descriptionMessage = "The cache name name defined in the property is not configured in the caching provider"; actionMessage = "Cache name: " + ex.getCacheName() + newline + "Please configure your caching provider (ehcache, hazelcast, ...)"; } if(cause instanceof MissingKeyFilterExpressionException) { descriptionMessage = "You've set the 'filter-key-type' to 'expression' but didn't set the property 'expression'"; actionMessage = "Please set the property 'expression' in your configuration file with a valid expression (see Spring Expression Language)" + newline; }
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException; package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage(); if(cause instanceof JCacheNotFoundException) { JCacheNotFoundException ex = (JCacheNotFoundException) cause; descriptionMessage = "The cache name name defined in the property is not configured in the caching provider"; actionMessage = "Cache name: " + ex.getCacheName() + newline + "Please configure your caching provider (ehcache, hazelcast, ...)"; } if(cause instanceof MissingKeyFilterExpressionException) { descriptionMessage = "You've set the 'filter-key-type' to 'expression' but didn't set the property 'expression'"; actionMessage = "Please set the property 'expression' in your configuration file with a valid expression (see Spring Expression Language)" + newline; }
if( cause instanceof FilterURLInvalidException) {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // }
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException;
package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage(); if(cause instanceof JCacheNotFoundException) { JCacheNotFoundException ex = (JCacheNotFoundException) cause; descriptionMessage = "The cache name name defined in the property is not configured in the caching provider"; actionMessage = "Cache name: " + ex.getCacheName() + newline + "Please configure your caching provider (ehcache, hazelcast, ...)"; } if(cause instanceof MissingKeyFilterExpressionException) { descriptionMessage = "You've set the 'filter-key-type' to 'expression' but didn't set the property 'expression'"; actionMessage = "Please set the property 'expression' in your configuration file with a valid expression (see Spring Expression Language)" + newline; } if( cause instanceof FilterURLInvalidException) { FilterURLInvalidException e = (FilterURLInvalidException) cause; descriptionMessage = "You've set an invalid regular expression in the 'filter'" + newline + "Description: " + e.getDescription(); actionMessage = "To Filter for all requests type .* or remove the property 'bucket4j.filters.url' completly." + newline; }
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/Bucket4jGeneralException.java // public abstract class Bucket4jGeneralException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterKeyTypeDeprectatedException.java // public class FilterKeyTypeDeprectatedException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/FilterURLInvalidException.java // public class FilterURLInvalidException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private final String filterRegex; // // private final String description; // // public FilterURLInvalidException(String filterRegex, String description) { // this.filterRegex = filterRegex; // this.description = description; // } // // public String getFilterRegex() { // return filterRegex; // } // // public String getDescription() { // return description; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/MissingKeyFilterExpressionException.java // public class MissingKeyFilterExpressionException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/failureanalyzer/Bucket4JAutoConfigFailureAnalyzer.java import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; import com.giffing.bucket4j.spring.boot.starter.exception.Bucket4jGeneralException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterKeyTypeDeprectatedException; import com.giffing.bucket4j.spring.boot.starter.exception.FilterURLInvalidException; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import com.giffing.bucket4j.spring.boot.starter.exception.MissingKeyFilterExpressionException; package com.giffing.bucket4j.spring.boot.starter.failureanalyzer; /** * The failure analyzer is responsible to provide readable information of exception which * occur on startup. All exception based on the {@link Bucket4jGeneralException} are handled here. */ public class Bucket4JAutoConfigFailureAnalyzer extends AbstractFailureAnalyzer<Bucket4jGeneralException>{ public static String newline = System.getProperty("line.separator"); @Override protected FailureAnalysis analyze(Throwable rootFailure, Bucket4jGeneralException cause) { String descriptionMessage = cause.getMessage(); String actionMessage = cause.getMessage(); if(cause instanceof JCacheNotFoundException) { JCacheNotFoundException ex = (JCacheNotFoundException) cause; descriptionMessage = "The cache name name defined in the property is not configured in the caching provider"; actionMessage = "Cache name: " + ex.getCacheName() + newline + "Please configure your caching provider (ehcache, hazelcast, ...)"; } if(cause instanceof MissingKeyFilterExpressionException) { descriptionMessage = "You've set the 'filter-key-type' to 'expression' but didn't set the property 'expression'"; actionMessage = "Please set the property 'expression' in your configuration file with a valid expression (see Spring Expression Language)" + newline; } if( cause instanceof FilterURLInvalidException) { FilterURLInvalidException e = (FilterURLInvalidException) cause; descriptionMessage = "You've set an invalid regular expression in the 'filter'" + newline + "Description: " + e.getDescription(); actionMessage = "To Filter for all requests type .* or remove the property 'bucket4j.filters.url' completly." + newline; }
if( cause instanceof FilterKeyTypeDeprectatedException) {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/springboot/SpringBootActuatorConfig.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java // @Configuration // @ConditionalOnClass(Endpoint.class) // public class Bucket4jEndpoint { // // @Configuration // @Endpoint(id = "bucket4j") // public static class Bucket4jEndpointConfig { // // @Autowired(required = false) // @Qualifier("SERVLET") // private Bucket4jConfigurationHolder servletConfigs; // // @Autowired(required = false) // @Qualifier("WEBFLUX") // private Bucket4jConfigurationHolder webfluxConfigs; // // @Autowired(required = false) // @Qualifier("GATEWAY") // private Bucket4jConfigurationHolder gatewayConfigs; // // // @ReadOperation // public Map<String, Object> bucket4jConfig() { // Map<String, Object> result = new HashMap<>(); // if(servletConfigs != null) { // result.put("servlet", servletConfigs.getFilterConfiguration()); // } // if(webfluxConfigs != null) { // result.put("webflux", webfluxConfigs.getFilterConfiguration()); // } // // if(gatewayConfigs != null) { // result.put("gateway", gatewayConfigs.getFilterConfiguration()); // } // // return result; // } // // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricsConfiguration.java // @Configuration // @ConditionalOnClass(value = {Metrics.class}) // @ConditionalOnProperty(prefix = Bucket4JBootProperties.PROPERTY_PREFIX + ".metrics", value = { "enabled" }, matchIfMissing = true) // public class Bucket4jMetricsConfiguration { // // @Bean // @Primary // public MetricHandler springBoot2Bucket4jMetricHandler() { // return new Bucket4jMetricHandler(); // } // // }
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.Bucket4jEndpoint; import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.Bucket4jMetricsConfiguration;
package com.giffing.bucket4j.spring.boot.starter.config.springboot; @Configuration @ConditionalOnClass(value = { Bucket4jEndpoint.class})
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java // @Configuration // @ConditionalOnClass(Endpoint.class) // public class Bucket4jEndpoint { // // @Configuration // @Endpoint(id = "bucket4j") // public static class Bucket4jEndpointConfig { // // @Autowired(required = false) // @Qualifier("SERVLET") // private Bucket4jConfigurationHolder servletConfigs; // // @Autowired(required = false) // @Qualifier("WEBFLUX") // private Bucket4jConfigurationHolder webfluxConfigs; // // @Autowired(required = false) // @Qualifier("GATEWAY") // private Bucket4jConfigurationHolder gatewayConfigs; // // // @ReadOperation // public Map<String, Object> bucket4jConfig() { // Map<String, Object> result = new HashMap<>(); // if(servletConfigs != null) { // result.put("servlet", servletConfigs.getFilterConfiguration()); // } // if(webfluxConfigs != null) { // result.put("webflux", webfluxConfigs.getFilterConfiguration()); // } // // if(gatewayConfigs != null) { // result.put("gateway", gatewayConfigs.getFilterConfiguration()); // } // // return result; // } // // } // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricsConfiguration.java // @Configuration // @ConditionalOnClass(value = {Metrics.class}) // @ConditionalOnProperty(prefix = Bucket4JBootProperties.PROPERTY_PREFIX + ".metrics", value = { "enabled" }, matchIfMissing = true) // public class Bucket4jMetricsConfiguration { // // @Bean // @Primary // public MetricHandler springBoot2Bucket4jMetricHandler() { // return new Bucket4jMetricHandler(); // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/springboot/SpringBootActuatorConfig.java import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.Bucket4jEndpoint; import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.Bucket4jMetricsConfiguration; package com.giffing.bucket4j.spring.boot.starter.config.springboot; @Configuration @ConditionalOnClass(value = { Bucket4jEndpoint.class})
@Import( value = {Bucket4jEndpoint.class, Bucket4jMetricsConfiguration.class})
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricsConfiguration.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java // @ConfigurationProperties(prefix = Bucket4JBootProperties.PROPERTY_PREFIX) // public class Bucket4JBootProperties { // // public static final String PROPERTY_PREFIX = "bucket4j"; // // /** // * Enables or disables the Bucket4j Spring Boot Starter. // */ // private Boolean enabled = true; // // private List<Bucket4JConfiguration> filters = new ArrayList<>(); // // // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // public static String getPropertyPrefix() { // return PROPERTY_PREFIX; // } // // public List<Bucket4JConfiguration> getFilters() { // return filters; // } // // public void setFilters(List<Bucket4JConfiguration> filters) { // this.filters = filters; // } // // }
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; import io.micrometer.core.instrument.Metrics;
package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Configuration @ConditionalOnClass(value = {Metrics.class})
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java // @ConfigurationProperties(prefix = Bucket4JBootProperties.PROPERTY_PREFIX) // public class Bucket4JBootProperties { // // public static final String PROPERTY_PREFIX = "bucket4j"; // // /** // * Enables or disables the Bucket4j Spring Boot Starter. // */ // private Boolean enabled = true; // // private List<Bucket4JConfiguration> filters = new ArrayList<>(); // // // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // public static String getPropertyPrefix() { // return PROPERTY_PREFIX; // } // // public List<Bucket4JConfiguration> getFilters() { // return filters; // } // // public void setFilters(List<Bucket4JConfiguration> filters) { // this.filters = filters; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricsConfiguration.java import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; import io.micrometer.core.instrument.Metrics; package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Configuration @ConditionalOnClass(value = {Metrics.class})
@ConditionalOnProperty(prefix = Bucket4JBootProperties.PROPERTY_PREFIX + ".metrics", value = { "enabled" }, matchIfMissing = true)
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricsConfiguration.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java // @ConfigurationProperties(prefix = Bucket4JBootProperties.PROPERTY_PREFIX) // public class Bucket4JBootProperties { // // public static final String PROPERTY_PREFIX = "bucket4j"; // // /** // * Enables or disables the Bucket4j Spring Boot Starter. // */ // private Boolean enabled = true; // // private List<Bucket4JConfiguration> filters = new ArrayList<>(); // // // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // public static String getPropertyPrefix() { // return PROPERTY_PREFIX; // } // // public List<Bucket4JConfiguration> getFilters() { // return filters; // } // // public void setFilters(List<Bucket4JConfiguration> filters) { // this.filters = filters; // } // // }
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; import io.micrometer.core.instrument.Metrics;
package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Configuration @ConditionalOnClass(value = {Metrics.class}) @ConditionalOnProperty(prefix = Bucket4JBootProperties.PROPERTY_PREFIX + ".metrics", value = { "enabled" }, matchIfMissing = true) public class Bucket4jMetricsConfiguration { @Bean @Primary
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/metrics/MetricHandler.java // public interface MetricHandler { // // void handle(MetricType type, String name, long tokens, List<MetricTagResult> tags); // // } // // Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java // @ConfigurationProperties(prefix = Bucket4JBootProperties.PROPERTY_PREFIX) // public class Bucket4JBootProperties { // // public static final String PROPERTY_PREFIX = "bucket4j"; // // /** // * Enables or disables the Bucket4j Spring Boot Starter. // */ // private Boolean enabled = true; // // private List<Bucket4JConfiguration> filters = new ArrayList<>(); // // // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // public static String getPropertyPrefix() { // return PROPERTY_PREFIX; // } // // public List<Bucket4JConfiguration> getFilters() { // return filters; // } // // public void setFilters(List<Bucket4JConfiguration> filters) { // this.filters = filters; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jMetricsConfiguration.java import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; import io.micrometer.core.instrument.Metrics; package com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator; @Configuration @ConditionalOnClass(value = {Metrics.class}) @ConditionalOnProperty(prefix = Bucket4JBootProperties.PROPERTY_PREFIX + ".metrics", value = { "enabled" }, matchIfMissing = true) public class Bucket4jMetricsConfiguration { @Bean @Primary
public MetricHandler springBoot2Bucket4jMetricHandler() {
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheCacheResolver.java
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/CacheResolver.java // public abstract interface CacheResolver { // // ProxyManager<String> resolve(String cacheName); // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // }
import javax.cache.Cache; import javax.cache.CacheManager; import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheResolver; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import io.github.bucket4j.Bucket4j; import io.github.bucket4j.distributed.proxy.ProxyManager; import io.github.bucket4j.grid.jcache.JCacheProxyManager;
package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; /** * This class is the JCache (JSR-107) implementation of the {@link CacheResolver}. * It uses Bucket4Js {@link JCacheProxyManager} to implement the {@link ProxyManager}. * */ public class JCacheCacheResolver implements SyncCacheResolver { private CacheManager cacheManager; public JCacheCacheResolver(CacheManager cacheManager) { this.cacheManager = cacheManager; } public ProxyManager<String> resolve(String cacheName) { Cache springCache = cacheManager.getCache(cacheName); if (springCache == null) {
// Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/CacheResolver.java // public abstract interface CacheResolver { // // ProxyManager<String> resolve(String cacheName); // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/SyncCacheResolver.java // public interface SyncCacheResolver extends CacheResolver { // // } // // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/exception/JCacheNotFoundException.java // public class JCacheNotFoundException extends Bucket4jGeneralException { // // private static final long serialVersionUID = 1L; // // private String cacheName; // // /** // * @param cacheName the missing cache key // */ // public JCacheNotFoundException(String cacheName) { // this.cacheName = cacheName; // } // // public String getCacheName() { // return cacheName; // } // // public void setCacheName(String cacheName) { // this.cacheName = cacheName; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/cache/jcache/JCacheCacheResolver.java import javax.cache.Cache; import javax.cache.CacheManager; import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheResolver; import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; import com.giffing.bucket4j.spring.boot.starter.exception.JCacheNotFoundException; import io.github.bucket4j.Bucket4j; import io.github.bucket4j.distributed.proxy.ProxyManager; import io.github.bucket4j.grid.jcache.JCacheProxyManager; package com.giffing.bucket4j.spring.boot.starter.config.cache.jcache; /** * This class is the JCache (JSR-107) implementation of the {@link CacheResolver}. * It uses Bucket4Js {@link JCacheProxyManager} to implement the {@link ProxyManager}. * */ public class JCacheCacheResolver implements SyncCacheResolver { private CacheManager cacheManager; public JCacheCacheResolver(CacheManager cacheManager) { this.cacheManager = cacheManager; } public ProxyManager<String> resolve(String cacheName) { Cache springCache = cacheManager.getCache(cacheName); if (springCache == null) {
throw new JCacheNotFoundException(cacheName);
MarcGiffing/bucket4j-spring-boot-starter
bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/servlet/Bucket4JAutoConfigurationServletFilterBeans.java
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // }
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelCompilerMode; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder;
package com.giffing.bucket4j.spring.boot.starter.config.servlet; @Configuration public class Bucket4JAutoConfigurationServletFilterBeans { @Bean @Qualifier("SERVLET")
// Path: bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Bucket4jConfigurationHolder.java // public class Bucket4jConfigurationHolder { // // private List<Bucket4JConfiguration> filterConfiguration = new ArrayList<>(); // // public void addFilterConfiguration(Bucket4JConfiguration filterConfiguration) { // getFilterConfiguration().add(filterConfiguration); // } // // public List<Bucket4JConfiguration> getFilterConfiguration() { // return filterConfiguration; // } // // public void setFilterConfiguration(List<Bucket4JConfiguration> filterConfiguration) { // this.filterConfiguration = filterConfiguration; // } // // } // Path: bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/servlet/Bucket4JAutoConfigurationServletFilterBeans.java import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelCompilerMode; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; package com.giffing.bucket4j.spring.boot.starter.config.servlet; @Configuration public class Bucket4JAutoConfigurationServletFilterBeans { @Bean @Qualifier("SERVLET")
public Bucket4jConfigurationHolder servletConfigurationHolder() {
MovingBlocks/WorldViewer
src/main/java/org/terasology/world/viewer/core/FacetPanel.java
// Path: src/main/java/org/terasology/world/viewer/gui/UIBindings.java // public final class UIBindings { // // private static final Logger logger = LoggerFactory.getLogger(UIBindings.class); // // private UIBindings() { // // no instances // } // // public static JCheckBox processCheckboxAnnotation(Object config, Field field, String text) { // Checkbox checkbox = field.getAnnotation(Checkbox.class); // // if (checkbox != null) { // try { // boolean initial = field.getBoolean(config); // JCheckBox component = createCheckbox(text, initial); // component.setName(checkbox.label().isEmpty() ? field.getName() : checkbox.label()); // component.setToolTipText(checkbox.description().isEmpty() ? null : checkbox.description()); // // return component; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static JCheckBox createCheckbox(String text, boolean initial) { // JCheckBox checkBox = new JCheckBox(text); // checkBox.setSelected(initial); // // return checkBox; // } // // public static JSpinner processRangeAnnotation(Object config, Field field) { // Range range = field.getAnnotation(Range.class); // // if (range != null) { // double min = range.min(); // double max = range.max(); // double stepSize = range.increment(); // try { // double initial = field.getDouble(config); // JSpinner spinner = createSpinner(min, stepSize, max, initial); // spinner.setName(range.label().isEmpty() ? field.getName() : range.label()); // spinner.setToolTipText(range.description().isEmpty() ? null : range.description()); // // return spinner; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static JSpinner createSpinner(double min, double stepSize, double max, double initial) { // // SpinnerNumberModel model = new SpinnerNumberModel(initial, min, max, stepSize); // JSpinner spinner = new JSpinner(model); // return spinner; // } // // /** // * Maps an @Enum field to a combobox // * @param config the object instance that is bound // * @param field the (potentially annotated field) // * @return a combobox for the annotated field or <code>null</code> if not applicable // */ // public static JComboBox<?> processEnumAnnotation(Object config, Field field) { // Enum en = field.getAnnotation(Enum.class); // Class<?> clazz = field.getType(); // the enum class // // if (en != null && clazz.isEnum()) { // try { // Object init = field.get(config); // JComboBox<?> combo = createCombo(clazz.getEnumConstants(), init); // combo.setName(en.label().isEmpty() ? field.getName() : en.label()); // combo.setToolTipText(en.description().isEmpty() ? null : en.description()); // return combo; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static JComboBox<String> processListAnnotation(Object config, Field field) { // List list = field.getAnnotation(List.class); // // if (list != null) { // try { // String init = field.get(config).toString(); // this should be a String already // JComboBox<String> combo = createCombo(list.items(), init); // combo.setName(list.label().isEmpty() ? field.getName() : list.label()); // combo.setToolTipText(list.description().isEmpty() ? null : list.description()); // return combo; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static <T> JComboBox<T> createCombo(T[] elements, T initValue) { // // ComboBoxModel<T> model = new DefaultComboBoxModel<T>(elements); // JComboBox<T> combo = new JComboBox<T>(model); // combo.setSelectedItem(initValue); // return combo; // } // }
import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.lang.reflect.Field; import java.util.List; import javax.swing.BorderFactory; import javax.swing.DefaultListSelectionModel; import javax.swing.DropMode; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.table.TableModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.world.viewer.gui.UIBindings; import org.terasology.world.viewer.layers.FacetLayer; import org.terasology.world.viewer.layers.FacetLayerConfig;
} }); } protected JPanel createConfigs(FacetLayer layer) { JPanel panelWrap = new JPanel(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 2)); FacetLayerConfig config = layer.getConfig(); if (config != null) { for (Field field : config.getClass().getDeclaredFields()) { if (field.getAnnotations().length > 0) { field.setAccessible(true); processAnnotations(panel, layer, field); } } } panel.setBorder(new EmptyBorder(0, 5, 0, 0)); panelWrap.add(panel, BorderLayout.NORTH); return panelWrap; } private void processAnnotations(JPanel panel, FacetLayer layer, Field field) { FacetLayerConfig config = layer.getConfig(); JComponent comp = null;
// Path: src/main/java/org/terasology/world/viewer/gui/UIBindings.java // public final class UIBindings { // // private static final Logger logger = LoggerFactory.getLogger(UIBindings.class); // // private UIBindings() { // // no instances // } // // public static JCheckBox processCheckboxAnnotation(Object config, Field field, String text) { // Checkbox checkbox = field.getAnnotation(Checkbox.class); // // if (checkbox != null) { // try { // boolean initial = field.getBoolean(config); // JCheckBox component = createCheckbox(text, initial); // component.setName(checkbox.label().isEmpty() ? field.getName() : checkbox.label()); // component.setToolTipText(checkbox.description().isEmpty() ? null : checkbox.description()); // // return component; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static JCheckBox createCheckbox(String text, boolean initial) { // JCheckBox checkBox = new JCheckBox(text); // checkBox.setSelected(initial); // // return checkBox; // } // // public static JSpinner processRangeAnnotation(Object config, Field field) { // Range range = field.getAnnotation(Range.class); // // if (range != null) { // double min = range.min(); // double max = range.max(); // double stepSize = range.increment(); // try { // double initial = field.getDouble(config); // JSpinner spinner = createSpinner(min, stepSize, max, initial); // spinner.setName(range.label().isEmpty() ? field.getName() : range.label()); // spinner.setToolTipText(range.description().isEmpty() ? null : range.description()); // // return spinner; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static JSpinner createSpinner(double min, double stepSize, double max, double initial) { // // SpinnerNumberModel model = new SpinnerNumberModel(initial, min, max, stepSize); // JSpinner spinner = new JSpinner(model); // return spinner; // } // // /** // * Maps an @Enum field to a combobox // * @param config the object instance that is bound // * @param field the (potentially annotated field) // * @return a combobox for the annotated field or <code>null</code> if not applicable // */ // public static JComboBox<?> processEnumAnnotation(Object config, Field field) { // Enum en = field.getAnnotation(Enum.class); // Class<?> clazz = field.getType(); // the enum class // // if (en != null && clazz.isEnum()) { // try { // Object init = field.get(config); // JComboBox<?> combo = createCombo(clazz.getEnumConstants(), init); // combo.setName(en.label().isEmpty() ? field.getName() : en.label()); // combo.setToolTipText(en.description().isEmpty() ? null : en.description()); // return combo; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static JComboBox<String> processListAnnotation(Object config, Field field) { // List list = field.getAnnotation(List.class); // // if (list != null) { // try { // String init = field.get(config).toString(); // this should be a String already // JComboBox<String> combo = createCombo(list.items(), init); // combo.setName(list.label().isEmpty() ? field.getName() : list.label()); // combo.setToolTipText(list.description().isEmpty() ? null : list.description()); // return combo; // } catch (IllegalAccessException e) { // logger.warn("Unable to read field {}", field); // } // } // // return null; // } // // public static <T> JComboBox<T> createCombo(T[] elements, T initValue) { // // ComboBoxModel<T> model = new DefaultComboBoxModel<T>(elements); // JComboBox<T> combo = new JComboBox<T>(model); // combo.setSelectedItem(initValue); // return combo; // } // } // Path: src/main/java/org/terasology/world/viewer/core/FacetPanel.java import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.lang.reflect.Field; import java.util.List; import javax.swing.BorderFactory; import javax.swing.DefaultListSelectionModel; import javax.swing.DropMode; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.table.TableModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.world.viewer.gui.UIBindings; import org.terasology.world.viewer.layers.FacetLayer; import org.terasology.world.viewer.layers.FacetLayerConfig; } }); } protected JPanel createConfigs(FacetLayer layer) { JPanel panelWrap = new JPanel(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 2)); FacetLayerConfig config = layer.getConfig(); if (config != null) { for (Field field : config.getClass().getDeclaredFields()) { if (field.getAnnotations().length > 0) { field.setAccessible(true); processAnnotations(panel, layer, field); } } } panel.setBorder(new EmptyBorder(0, 5, 0, 0)); panelWrap.add(panel, BorderLayout.NORTH); return panelWrap; } private void processAnnotations(JPanel panel, FacetLayer layer, Field field) { FacetLayerConfig config = layer.getConfig(); JComponent comp = null;
JSpinner spinner = UIBindings.processRangeAnnotation(config, field);
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseActionbarActivity.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // }
import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout;
protected Toolbar getToolBar(){ return toolbar; } protected ActionBar getActionbar(){ return actionBar; } /** * * Below is an actionbar * ------------------------------------------------------- * | ----- | * | |<--| Action bar title | * | ----- | * ------------------------------------------------------- * @param title * @param color specify the actionbar actual title color, can not be color resourceId. */ protected void setActionbarTitle(CharSequence title, int color){ getActionbar().setTitle(title); getToolBar().setTitleTextColor(color); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void setActionbarThemeColor(){ Drawable drawable = setupThemeColor();
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseActionbarActivity.java import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; protected Toolbar getToolBar(){ return toolbar; } protected ActionBar getActionbar(){ return actionBar; } /** * * Below is an actionbar * ------------------------------------------------------- * | ----- | * | |<--| Action bar title | * | ----- | * ------------------------------------------------------- * @param title * @param color specify the actionbar actual title color, can not be color resourceId. */ protected void setActionbarTitle(CharSequence title, int color){ getActionbar().setTitle(title); getToolBar().setTitleTextColor(color); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void setActionbarThemeColor(){ Drawable drawable = setupThemeColor();
if (drawable == null) drawable = DrawableUtil.getDrawable(this, R.color.base_theme_blue);
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/widget/MaterialFlatButton.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // }
import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.Converter; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.TextView;
package com.daililol.material.appbase.widget; public class MaterialFlatButton extends TextView{ public static enum Theme{ LIGHT, DARK } public MaterialFlatButton(Context context){ this(context, null); } public MaterialFlatButton(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub int theme = 0; int padding = -1; int paddingLeft = -1; int paddingRight = -1; int paddingTop = -1; int paddingBottom = -1; if (attrs != null){ TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialButton); theme = t.getInt(R.styleable.MaterialButton_button_theme, 0); padding = (int)t.getDimension(R.styleable.MaterialButton_android_padding, padding); paddingLeft = (int)t.getDimension(R.styleable.MaterialButton_android_paddingLeft, paddingLeft); paddingRight = (int)t.getDimension(R.styleable.MaterialButton_android_paddingRight, paddingRight); paddingTop = (int)t.getDimension(R.styleable.MaterialButton_android_paddingTop, paddingTop); paddingBottom = (int)t.getDimension(R.styleable.MaterialButton_android_paddingBottom, paddingBottom); t.recycle(); } this.setClickable(true);
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/widget/MaterialFlatButton.java import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.Converter; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.TextView; package com.daililol.material.appbase.widget; public class MaterialFlatButton extends TextView{ public static enum Theme{ LIGHT, DARK } public MaterialFlatButton(Context context){ this(context, null); } public MaterialFlatButton(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub int theme = 0; int padding = -1; int paddingLeft = -1; int paddingRight = -1; int paddingTop = -1; int paddingBottom = -1; if (attrs != null){ TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialButton); theme = t.getInt(R.styleable.MaterialButton_button_theme, 0); padding = (int)t.getDimension(R.styleable.MaterialButton_android_padding, padding); paddingLeft = (int)t.getDimension(R.styleable.MaterialButton_android_paddingLeft, paddingLeft); paddingRight = (int)t.getDimension(R.styleable.MaterialButton_android_paddingRight, paddingRight); paddingTop = (int)t.getDimension(R.styleable.MaterialButton_android_paddingTop, paddingTop); paddingBottom = (int)t.getDimension(R.styleable.MaterialButton_android_paddingBottom, paddingBottom); t.recycle(); } this.setClickable(true);
int defaultPaddingLeft = Converter.dp2px(context, 16);
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/component/BaseNavigationDrawerListAdapter.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // }
import java.util.ArrayList; import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.Converter; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView;
public BaseNavigationDrawerListAdapter(Context context){ this.context = context; this.menuList = new ArrayList<MenuItem>(); } @Override public int getCount() { // TODO Auto-generated method stub return menuList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { MenuItem.Type type = menuList.get(position).type; if (type == MenuItem.Type.DIVIDER){ AbsListView.LayoutParams convertViewParams = new AbsListView.LayoutParams(
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/component/BaseNavigationDrawerListAdapter.java import java.util.ArrayList; import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.Converter; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public BaseNavigationDrawerListAdapter(Context context){ this.context = context; this.menuList = new ArrayList<MenuItem>(); } @Override public int getCount() { // TODO Auto-generated method stub return menuList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { MenuItem.Type type = menuList.get(position).type; if (type == MenuItem.Type.DIVIDER){ AbsListView.LayoutParams convertViewParams = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, Converter.dp2px(context, 17));
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseTabbableActionbarActivity.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // }
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout;
protected FloatingActionButton getFabButton(){ return fabButton; } /** * * @param title * @param color specify the actionbar actual title color, can not be color resourceId. */ protected void setActionbarTitle(CharSequence title, int color){ getActionbar().setTitle(title); getToolBar().setTitleTextColor(color); } protected void requestHomeIcon(Drawable drawable){ getActionbar().setHomeAsUpIndicator(drawable); getActionbar().setDisplayHomeAsUpEnabled(true); } protected void requestBackIcon(Drawable drawable){ getActionbar().setHomeAsUpIndicator(drawable); getActionbar().setDisplayHomeAsUpEnabled(true); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void setActionbarThemeColor(){ Drawable drawable = setupThemeColor();
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseTabbableActionbarActivity.java import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; protected FloatingActionButton getFabButton(){ return fabButton; } /** * * @param title * @param color specify the actionbar actual title color, can not be color resourceId. */ protected void setActionbarTitle(CharSequence title, int color){ getActionbar().setTitle(title); getToolBar().setTitleTextColor(color); } protected void requestHomeIcon(Drawable drawable){ getActionbar().setHomeAsUpIndicator(drawable); getActionbar().setDisplayHomeAsUpEnabled(true); } protected void requestBackIcon(Drawable drawable){ getActionbar().setHomeAsUpIndicator(drawable); getActionbar().setDisplayHomeAsUpEnabled(true); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void setActionbarThemeColor(){ Drawable drawable = setupThemeColor();
if (drawable == null) drawable = DrawableUtil.getDrawable(this, R.color.base_theme_blue);;
DanielShum/MaterialAppBase
app/src/main/java/com/daililol/material/appbase/example/ExampleListViewAdapter.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // }
import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.daililol.material.appbase.utility.Converter; import java.util.Vector;
package com.daililol.material.appbase.example; /** * Created by DennyShum on 8/22/15. */ public class ExampleListViewAdapter extends BaseAdapter{ private Vector<String> dataSet; public ExampleListViewAdapter(Vector<String> dataSet){ this.dataSet = dataSet; } @Override public int getCount() { return dataSet.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View itemView, ViewGroup viewGroup) { ViewHolder viewHolder; if (itemView == null){ itemView = new LinearLayout(viewGroup.getContext()); ((LinearLayout)itemView).setOrientation(LinearLayout.HORIZONTAL); AbsListView.LayoutParams layoutParams =
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // Path: app/src/main/java/com/daililol/material/appbase/example/ExampleListViewAdapter.java import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.daililol.material.appbase.utility.Converter; import java.util.Vector; package com.daililol.material.appbase.example; /** * Created by DennyShum on 8/22/15. */ public class ExampleListViewAdapter extends BaseAdapter{ private Vector<String> dataSet; public ExampleListViewAdapter(Vector<String> dataSet){ this.dataSet = dataSet; } @Override public int getCount() { return dataSet.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View itemView, ViewGroup viewGroup) { ViewHolder viewHolder; if (itemView == null){ itemView = new LinearLayout(viewGroup.getContext()); ((LinearLayout)itemView).setOrientation(LinearLayout.HORIZONTAL); AbsListView.LayoutParams layoutParams =
new AbsListView.LayoutParams(AdapterView.LayoutParams.MATCH_PARENT, Converter.dp2px(itemView.getContext(), 56));
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseCollapsingActionbarActivity.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // }
import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.annotation.SuppressLint; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout;
/** * * Below is an actionbar * ------------------------------------------------------- * | ----- | * | |<--| Action bar title | * | ----- | * ------------------------------------------------------- * @param title * @param color specify the actionbar actual title color, can not be color resourceId. */ protected void setActionbarTitle(CharSequence title, int color){ getToolbarLayout().setTitle(title); getToolbarLayout().setExpandedTitleColor(color); getToolBar().setTitleTextColor(color); } protected void setTransitionName(int viewId, String transitionName){ if (transitionName != null) { ViewCompat.setTransitionName(findViewById(viewId), transitionName); } } private void setActionbarThemeColor(){ int color = setupThemeColor(); if (color == 0) color = getResources().getColor(R.color.base_theme_blue); getToolbarLayout().setContentScrimColor(color); getToolbarLayout().setStatusBarScrimColor(color);
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseCollapsingActionbarActivity.java import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.annotation.SuppressLint; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; /** * * Below is an actionbar * ------------------------------------------------------- * | ----- | * | |<--| Action bar title | * | ----- | * ------------------------------------------------------- * @param title * @param color specify the actionbar actual title color, can not be color resourceId. */ protected void setActionbarTitle(CharSequence title, int color){ getToolbarLayout().setTitle(title); getToolbarLayout().setExpandedTitleColor(color); getToolBar().setTitleTextColor(color); } protected void setTransitionName(int viewId, String transitionName){ if (transitionName != null) { ViewCompat.setTransitionName(findViewById(viewId), transitionName); } } private void setActionbarThemeColor(){ int color = setupThemeColor(); if (color == 0) color = getResources().getColor(R.color.base_theme_blue); getToolbarLayout().setContentScrimColor(color); getToolbarLayout().setStatusBarScrimColor(color);
ColorStateList colorStateList = DrawableUtil.createColorStateList(color, color, color, color, color);
DanielShum/MaterialAppBase
app/src/main/java/com/daililol/material/appbase/example/ExampleRecyclerViewAdapter.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DeviceUtil.java // public class DeviceUtil { // // public static Point getScreenSize(Context context){ // Point size = new Point(); // DisplayMetrics display = context.getResources().getDisplayMetrics(); // size.x = display.widthPixels; // size.y = display.heightPixels; // // return size; // } // // /** // * Return pseudo unique ID // * @return ID // */ // public static String getUniquePsuedoID() { // // String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) // + (Build.BRAND.length() % 10) // + (Build.CPU_ABI.length() % 10) // + (Build.DEVICE.length() % 10) // + (Build.MANUFACTURER.length() % 10) // + (Build.MODEL.length() % 10) // + (Build.PRODUCT.length() % 10); // // String serial = null; // try { // serial = android.os.Build.class.getField("SERIAL").get(null).toString(); // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } catch (Exception exception) { // // String needs to be initialized // serial = "serial"; // some value // } // // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } // // }
import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.daililol.material.appbase.utility.Converter; import com.daililol.material.appbase.utility.DeviceUtil; import java.util.Vector;
package com.daililol.material.appbase.example; /** * Created by DennyShum on 8/21/15. */ public class ExampleRecyclerViewAdapter extends RecyclerView.Adapter<ExampleRecyclerViewAdapter.ViewHolder>{ private Vector<String> listItems; private RecyclerView.LayoutManager layoutManager; public ExampleRecyclerViewAdapter(Vector<String> dataSet, RecyclerView.LayoutManager layoutManager){ this.layoutManager = layoutManager; listItems = dataSet; if (listItems == null) listItems = new Vector<String>(); } public void addItem(String itemText){ listItems.add(itemText); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LinearLayout itemView = new LinearLayout(parent.getContext()); TextView textView = new TextView(parent.getContext()); textView.setTextSize(18); textView.setId(android.R.id.text1); RecyclerView.LayoutParams layoutParams =
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DeviceUtil.java // public class DeviceUtil { // // public static Point getScreenSize(Context context){ // Point size = new Point(); // DisplayMetrics display = context.getResources().getDisplayMetrics(); // size.x = display.widthPixels; // size.y = display.heightPixels; // // return size; // } // // /** // * Return pseudo unique ID // * @return ID // */ // public static String getUniquePsuedoID() { // // String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) // + (Build.BRAND.length() % 10) // + (Build.CPU_ABI.length() % 10) // + (Build.DEVICE.length() % 10) // + (Build.MANUFACTURER.length() % 10) // + (Build.MODEL.length() % 10) // + (Build.PRODUCT.length() % 10); // // String serial = null; // try { // serial = android.os.Build.class.getField("SERIAL").get(null).toString(); // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } catch (Exception exception) { // // String needs to be initialized // serial = "serial"; // some value // } // // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } // // } // Path: app/src/main/java/com/daililol/material/appbase/example/ExampleRecyclerViewAdapter.java import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.daililol.material.appbase.utility.Converter; import com.daililol.material.appbase.utility.DeviceUtil; import java.util.Vector; package com.daililol.material.appbase.example; /** * Created by DennyShum on 8/21/15. */ public class ExampleRecyclerViewAdapter extends RecyclerView.Adapter<ExampleRecyclerViewAdapter.ViewHolder>{ private Vector<String> listItems; private RecyclerView.LayoutManager layoutManager; public ExampleRecyclerViewAdapter(Vector<String> dataSet, RecyclerView.LayoutManager layoutManager){ this.layoutManager = layoutManager; listItems = dataSet; if (listItems == null) listItems = new Vector<String>(); } public void addItem(String itemText){ listItems.add(itemText); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LinearLayout itemView = new LinearLayout(parent.getContext()); TextView textView = new TextView(parent.getContext()); textView.setTextSize(18); textView.setId(android.R.id.text1); RecyclerView.LayoutParams layoutParams =
new RecyclerView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Converter.dp2px(itemView.getContext(), 56));
DanielShum/MaterialAppBase
app/src/main/java/com/daililol/material/appbase/example/ExampleRecyclerViewAdapter.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DeviceUtil.java // public class DeviceUtil { // // public static Point getScreenSize(Context context){ // Point size = new Point(); // DisplayMetrics display = context.getResources().getDisplayMetrics(); // size.x = display.widthPixels; // size.y = display.heightPixels; // // return size; // } // // /** // * Return pseudo unique ID // * @return ID // */ // public static String getUniquePsuedoID() { // // String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) // + (Build.BRAND.length() % 10) // + (Build.CPU_ABI.length() % 10) // + (Build.DEVICE.length() % 10) // + (Build.MANUFACTURER.length() % 10) // + (Build.MODEL.length() % 10) // + (Build.PRODUCT.length() % 10); // // String serial = null; // try { // serial = android.os.Build.class.getField("SERIAL").get(null).toString(); // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } catch (Exception exception) { // // String needs to be initialized // serial = "serial"; // some value // } // // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } // // }
import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.daililol.material.appbase.utility.Converter; import com.daililol.material.appbase.utility.DeviceUtil; import java.util.Vector;
textView.setId(android.R.id.text1); RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Converter.dp2px(itemView.getContext(), 56)); itemView.setPadding(Converter.dp2px(itemView.getContext(), 16), 0, Converter.dp2px(itemView.getContext(), 16), 0); itemView.setGravity(Gravity.LEFT | Gravity.START | Gravity.CENTER); itemView.setBackgroundResource(R.drawable.touch_feedback_holo_light); itemView.addView(textView); itemView.setLayoutParams(layoutParams); if (this.layoutManager instanceof GridLayoutManager){ calculateGridItemSize(itemView); } return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.textView.setText(listItems.get(position)); } @Override public int getItemCount() { return listItems.size(); } private int calculateGridItemSize(View itemView){
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DeviceUtil.java // public class DeviceUtil { // // public static Point getScreenSize(Context context){ // Point size = new Point(); // DisplayMetrics display = context.getResources().getDisplayMetrics(); // size.x = display.widthPixels; // size.y = display.heightPixels; // // return size; // } // // /** // * Return pseudo unique ID // * @return ID // */ // public static String getUniquePsuedoID() { // // String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) // + (Build.BRAND.length() % 10) // + (Build.CPU_ABI.length() % 10) // + (Build.DEVICE.length() % 10) // + (Build.MANUFACTURER.length() % 10) // + (Build.MODEL.length() % 10) // + (Build.PRODUCT.length() % 10); // // String serial = null; // try { // serial = android.os.Build.class.getField("SERIAL").get(null).toString(); // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } catch (Exception exception) { // // String needs to be initialized // serial = "serial"; // some value // } // // return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); // } // // } // Path: app/src/main/java/com/daililol/material/appbase/example/ExampleRecyclerViewAdapter.java import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.daililol.material.appbase.utility.Converter; import com.daililol.material.appbase.utility.DeviceUtil; import java.util.Vector; textView.setId(android.R.id.text1); RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Converter.dp2px(itemView.getContext(), 56)); itemView.setPadding(Converter.dp2px(itemView.getContext(), 16), 0, Converter.dp2px(itemView.getContext(), 16), 0); itemView.setGravity(Gravity.LEFT | Gravity.START | Gravity.CENTER); itemView.setBackgroundResource(R.drawable.touch_feedback_holo_light); itemView.addView(textView); itemView.setLayoutParams(layoutParams); if (this.layoutManager instanceof GridLayoutManager){ calculateGridItemSize(itemView); } return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.textView.setText(listItems.get(position)); } @Override public int getItemCount() { return listItems.size(); } private int calculateGridItemSize(View itemView){
int size = (DeviceUtil.getScreenSize(itemView.getContext()).x - Converter.dp2px(itemView.getContext(), 20)) / 2;
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/widget/RetriableListFooter.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // }
import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.Converter; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.TextView;
package com.daililol.material.appbase.widget; public class RetriableListFooter extends LinearLayout{ private View footerView; private LinearLayout loadingView; private MaterialRaisedButton retryButton; private TextView noMoreText; private ViewType loadType = ViewType.LOADING; public static enum ViewType{ LOADING, RETRY, NO_MORE } public RetriableListFooter(Context context){ this(context, null); } public RetriableListFooter(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/Converter.java // public class Converter { // // public static int dp2px(Context context, float dp){ // return (int)(dp * context.getResources().getDisplayMetrics().density); // } // // public static int px2dp(Context context, float px){ // return (int)(px / context.getResources().getDisplayMetrics().density); // } // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/widget/RetriableListFooter.java import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.Converter; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.TextView; package com.daililol.material.appbase.widget; public class RetriableListFooter extends LinearLayout{ private View footerView; private LinearLayout loadingView; private MaterialRaisedButton retryButton; private TextView noMoreText; private ViewType loadType = ViewType.LOADING; public static enum ViewType{ LOADING, RETRY, NO_MORE } public RetriableListFooter(Context context){ this(context, null); } public RetriableListFooter(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub
this.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, Converter.dp2px(getContext(), 72)));
DanielShum/MaterialAppBase
materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/widget/MaterialRaisedButton.java
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // }
import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.os.Build; import android.support.v7.widget.AppCompatButton; import android.util.AttributeSet;
int textColor; if (attrs != null){ TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialButton); theme = t.getInt(R.styleable.MaterialButton_button_theme, 0); t.recycle(); } if (theme == 0){ normalStateColor = getContext().getResources().getColor(R.color.base_ui_white); pressedStateColor = getContext().getResources().getColor(R.color.base_ui_light_grey); textColor = getContext().getResources().getColor(R.color.base_text_color_dark); }else{ normalStateColor = getContext().getResources().getColor(R.color.base_ui_blue); pressedStateColor = getContext().getResources().getColor(R.color.base_ui_blue_pressed); textColor = getContext().getResources().getColor(R.color.base_ui_white); } if (attrs != null){ TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialButton); normalStateColor = t.getColor(R.styleable.MaterialButton_normal_state_color, normalStateColor); pressedStateColor = t.getColor(R.styleable.MaterialButton_pressed_state_color, pressedStateColor); textColor = t.getColor(R.styleable.MaterialButton_android_textColor, textColor); t.recycle(); } ColorStateList colorList; if (Build.VERSION.SDK_INT >= 21){
// Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/utility/DrawableUtil.java // public class DrawableUtil { // // public static Drawable changeDrawableColor(Drawable drawable, int destinationColor){ // drawable.setColorFilter(destinationColor, android.graphics.PorterDuff.Mode.MULTIPLY); // return drawable; // } // // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static Drawable getDrawable(Context context, int resourceId){ // // if (Build.VERSION.SDK_INT >= 21){ // return context.getDrawable(resourceId); // }else{ // return context.getResources().getDrawable(resourceId); // } // } // // public static Drawable getDrawable(Context context, int resourceId, int convertToColor){ // Drawable drawable = getDrawable(context, resourceId); // return changeDrawableColor(drawable, convertToColor); // // } // // public static ColorStateList createColorStateListAPI21(int normal) { // int[] colors = new int[] {normal}; // int[][] states = new int[1][]; // states[0] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static ColorStateList createColorStateList(int normal, int selected, int pressed, int focused, int unable) { // int[] colors = new int[] { pressed, focused, selected, focused, unable, normal, normal }; // int[][] states = new int[7][]; // states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }; // states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; // states[2] = new int[] { android.R.attr.state_selected }; // states[3] = new int[] { android.R.attr.state_focused }; // states[4] = new int[] { android.R.attr.state_window_focused }; // states[5] = new int[] { android.R.attr.state_enabled }; // states[6] = new int[] {}; // ColorStateList colorList = new ColorStateList(states, colors); // return colorList; // } // // public static StateListDrawable createStateListDrawable(Context context, int normalResourceId, int activeResourceId){ // Drawable drawableNormal = getDrawable(context, normalResourceId); // Drawable drawableActive = getDrawable(context, activeResourceId); // return createStateListDrawable(context, drawableNormal, drawableActive, // drawableActive, drawableActive, drawableNormal); // } // // public static StateListDrawable createStateListDrawable(Context contet, // Drawable normal, Drawable selected, Drawable pressed, Drawable focused, Drawable unable){ // // StateListDrawable drawableList = new StateListDrawable(); // drawableList.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, pressed); // drawableList.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_selected }, selected); // drawableList.addState(new int[] { android.R.attr.state_focused }, focused); // drawableList.addState(new int[] { android.R.attr.state_window_focused }, unable); // drawableList.addState(new int[] { android.R.attr.state_enabled }, normal); // drawableList.addState(new int[] {}, normal); // // return drawableList; // // // } // // } // Path: materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/widget/MaterialRaisedButton.java import com.daililol.material.appbase.R; import com.daililol.material.appbase.utility.DrawableUtil; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.os.Build; import android.support.v7.widget.AppCompatButton; import android.util.AttributeSet; int textColor; if (attrs != null){ TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialButton); theme = t.getInt(R.styleable.MaterialButton_button_theme, 0); t.recycle(); } if (theme == 0){ normalStateColor = getContext().getResources().getColor(R.color.base_ui_white); pressedStateColor = getContext().getResources().getColor(R.color.base_ui_light_grey); textColor = getContext().getResources().getColor(R.color.base_text_color_dark); }else{ normalStateColor = getContext().getResources().getColor(R.color.base_ui_blue); pressedStateColor = getContext().getResources().getColor(R.color.base_ui_blue_pressed); textColor = getContext().getResources().getColor(R.color.base_ui_white); } if (attrs != null){ TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialButton); normalStateColor = t.getColor(R.styleable.MaterialButton_normal_state_color, normalStateColor); pressedStateColor = t.getColor(R.styleable.MaterialButton_pressed_state_color, pressedStateColor); textColor = t.getColor(R.styleable.MaterialButton_android_textColor, textColor); t.recycle(); } ColorStateList colorList; if (Build.VERSION.SDK_INT >= 21){
colorList = DrawableUtil.createColorStateListAPI21(normalStateColor);
jbgi/eventsrc4j
core/src/main/java/eventsrc4j/CommandAPI.java
// Path: core/src/main/java/eventsrc4j/QueryAPI.java // public static <K, S, E, V> QueryAPI<K, S, E, V> queryAPI(F<E, F<V, V>> applyEvent, V initialState) { // return new QueryAPI<>((event, snapshot) -> event.apply(applyEvent, getView(snapshot).orSome(initialState))); // }
import fj.F; import fj.data.List; import java.time.Instant; import static eventsrc4j.CommandDecisions.caseOf; import static eventsrc4j.QueryAPI.queryAPI; import static eventsrc4j.Snapshots.getSeq; import static eventsrc4j.WriteResults.caseOf;
package eventsrc4j; public class CommandAPI<C, K, S, E, V, R> implements ESAction.Factory<K, S, E, V> { private final F<C, F<Snapshot<S, V>, CommandDecision<R, E>>> decideFunction;
// Path: core/src/main/java/eventsrc4j/QueryAPI.java // public static <K, S, E, V> QueryAPI<K, S, E, V> queryAPI(F<E, F<V, V>> applyEvent, V initialState) { // return new QueryAPI<>((event, snapshot) -> event.apply(applyEvent, getView(snapshot).orSome(initialState))); // } // Path: core/src/main/java/eventsrc4j/CommandAPI.java import fj.F; import fj.data.List; import java.time.Instant; import static eventsrc4j.CommandDecisions.caseOf; import static eventsrc4j.QueryAPI.queryAPI; import static eventsrc4j.Snapshots.getSeq; import static eventsrc4j.WriteResults.caseOf; package eventsrc4j; public class CommandAPI<C, K, S, E, V, R> implements ESAction.Factory<K, S, E, V> { private final F<C, F<Snapshot<S, V>, CommandDecision<R, E>>> decideFunction;
private final QueryAPI<K, S, E, V> queryAPI;
jbgi/eventsrc4j
core/src/test/java/eventsrc4j/memory/MemoryEventStorageTest.java
// Path: core/src/test/java/eventsrc4j/EventStorageSpec.java // public final class EventStorageSpec<K, S, E> implements WStreamAction.Factory<K, S, E> { // // private final Gen<K> keys; // // private final Gen<E> events; // // public EventStorageSpec(Gen<K> keys, Gen<E> events) { // this.keys = keys; // this.events = events; // } // // public Property read_return_write(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // WriteResult<K, S, E> writeResult = stream // .write(lastSeq, Instant.EPOCH, singletonList(event)) // .runUnchecked(); // // return prop( // writeResult.events().map( // writtenEvents -> writtenEvents.length() == 1 // && writtenEvents.equals(stream // .read(lastSeq, Fold.toList()) // .runUnchecked()) // ).orSome(false) // ); // }); // } // // public Property read_return_write_actions( // Function<K, Predicate<WStreamAction<K, S, E, Boolean>>> actionInterpreter) { // return property(keys, events, key -> event -> { // // WStreamAction<K, S, E, Option<S>> lastSeqA = ReadEventStream(Option.none(), Fold.last()) // .map(last -> last.map(Events::getSeq)); // // WStreamAction<K, S, E, Boolean> compareEventsA = lastSeqA.bind(lastSeq -> { // // WStreamAction<K, S, E, List<Event<K, S, E>>> writeEventsA = // WriteEvents(lastSeq, Instant.EPOCH, single(event)) // .map(WriteResults::getEvents) // .map(es -> es.orSome(nil())); // // WStreamAction<K, S, E, List<Event<K, S, E>>> readEventsA = ReadEventStream(lastSeq, Fold.toList()); // // return writeEventsA.bind(writtenEvents -> // readEventsA.map(readEvents -> writtenEvents.length() == 1 && writtenEvents.equals(readEvents)) // ); // } // ); // // return prop(actionInterpreter.apply(key).test(compareEventsA)); // }); // } // // public Property concurrent_write_fails(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // WriteResult<K, S, E> concurrentWrite = stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // return prop(concurrentWrite.events().isNone()); // }); // } // } // // Path: core/src/main/java/eventsrc4j/Sequence.java // public interface Sequence<S> extends Comparator<S> { // // S first(); // // S next(S seq); // // Sequence<Long> longs = new Sequence<Long>() { // // public int compare(Long seq1, Long seq2) { // return seq1.compareTo(seq2); // } // // public Long first() { // return 1L; // } // // public Long next(Long seq) { // return seq + 1; // } // }; // }
import eventsrc4j.EventStorageSpec; import eventsrc4j.Sequence; import fj.test.Arbitrary; import fj.test.Property; import fj.test.reflect.CheckParams; import fj.test.runner.PropertyTestRunner; import org.junit.runner.RunWith; import static fj.test.Gen.elements;
package eventsrc4j.memory; @RunWith(PropertyTestRunner.class) @CheckParams(maxSize = 10000, minSuccessful = 200) public final class MemoryEventStorageTest {
// Path: core/src/test/java/eventsrc4j/EventStorageSpec.java // public final class EventStorageSpec<K, S, E> implements WStreamAction.Factory<K, S, E> { // // private final Gen<K> keys; // // private final Gen<E> events; // // public EventStorageSpec(Gen<K> keys, Gen<E> events) { // this.keys = keys; // this.events = events; // } // // public Property read_return_write(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // WriteResult<K, S, E> writeResult = stream // .write(lastSeq, Instant.EPOCH, singletonList(event)) // .runUnchecked(); // // return prop( // writeResult.events().map( // writtenEvents -> writtenEvents.length() == 1 // && writtenEvents.equals(stream // .read(lastSeq, Fold.toList()) // .runUnchecked()) // ).orSome(false) // ); // }); // } // // public Property read_return_write_actions( // Function<K, Predicate<WStreamAction<K, S, E, Boolean>>> actionInterpreter) { // return property(keys, events, key -> event -> { // // WStreamAction<K, S, E, Option<S>> lastSeqA = ReadEventStream(Option.none(), Fold.last()) // .map(last -> last.map(Events::getSeq)); // // WStreamAction<K, S, E, Boolean> compareEventsA = lastSeqA.bind(lastSeq -> { // // WStreamAction<K, S, E, List<Event<K, S, E>>> writeEventsA = // WriteEvents(lastSeq, Instant.EPOCH, single(event)) // .map(WriteResults::getEvents) // .map(es -> es.orSome(nil())); // // WStreamAction<K, S, E, List<Event<K, S, E>>> readEventsA = ReadEventStream(lastSeq, Fold.toList()); // // return writeEventsA.bind(writtenEvents -> // readEventsA.map(readEvents -> writtenEvents.length() == 1 && writtenEvents.equals(readEvents)) // ); // } // ); // // return prop(actionInterpreter.apply(key).test(compareEventsA)); // }); // } // // public Property concurrent_write_fails(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // WriteResult<K, S, E> concurrentWrite = stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // return prop(concurrentWrite.events().isNone()); // }); // } // } // // Path: core/src/main/java/eventsrc4j/Sequence.java // public interface Sequence<S> extends Comparator<S> { // // S first(); // // S next(S seq); // // Sequence<Long> longs = new Sequence<Long>() { // // public int compare(Long seq1, Long seq2) { // return seq1.compareTo(seq2); // } // // public Long first() { // return 1L; // } // // public Long next(Long seq) { // return seq + 1; // } // }; // } // Path: core/src/test/java/eventsrc4j/memory/MemoryEventStorageTest.java import eventsrc4j.EventStorageSpec; import eventsrc4j.Sequence; import fj.test.Arbitrary; import fj.test.Property; import fj.test.reflect.CheckParams; import fj.test.runner.PropertyTestRunner; import org.junit.runner.RunWith; import static fj.test.Gen.elements; package eventsrc4j.memory; @RunWith(PropertyTestRunner.class) @CheckParams(maxSize = 10000, minSuccessful = 200) public final class MemoryEventStorageTest {
private static final EventStorageSpec<Integer, Long, MemoryEventStorageTest.Event> spec =
jbgi/eventsrc4j
core/src/test/java/eventsrc4j/memory/MemoryEventStorageTest.java
// Path: core/src/test/java/eventsrc4j/EventStorageSpec.java // public final class EventStorageSpec<K, S, E> implements WStreamAction.Factory<K, S, E> { // // private final Gen<K> keys; // // private final Gen<E> events; // // public EventStorageSpec(Gen<K> keys, Gen<E> events) { // this.keys = keys; // this.events = events; // } // // public Property read_return_write(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // WriteResult<K, S, E> writeResult = stream // .write(lastSeq, Instant.EPOCH, singletonList(event)) // .runUnchecked(); // // return prop( // writeResult.events().map( // writtenEvents -> writtenEvents.length() == 1 // && writtenEvents.equals(stream // .read(lastSeq, Fold.toList()) // .runUnchecked()) // ).orSome(false) // ); // }); // } // // public Property read_return_write_actions( // Function<K, Predicate<WStreamAction<K, S, E, Boolean>>> actionInterpreter) { // return property(keys, events, key -> event -> { // // WStreamAction<K, S, E, Option<S>> lastSeqA = ReadEventStream(Option.none(), Fold.last()) // .map(last -> last.map(Events::getSeq)); // // WStreamAction<K, S, E, Boolean> compareEventsA = lastSeqA.bind(lastSeq -> { // // WStreamAction<K, S, E, List<Event<K, S, E>>> writeEventsA = // WriteEvents(lastSeq, Instant.EPOCH, single(event)) // .map(WriteResults::getEvents) // .map(es -> es.orSome(nil())); // // WStreamAction<K, S, E, List<Event<K, S, E>>> readEventsA = ReadEventStream(lastSeq, Fold.toList()); // // return writeEventsA.bind(writtenEvents -> // readEventsA.map(readEvents -> writtenEvents.length() == 1 && writtenEvents.equals(readEvents)) // ); // } // ); // // return prop(actionInterpreter.apply(key).test(compareEventsA)); // }); // } // // public Property concurrent_write_fails(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // WriteResult<K, S, E> concurrentWrite = stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // return prop(concurrentWrite.events().isNone()); // }); // } // } // // Path: core/src/main/java/eventsrc4j/Sequence.java // public interface Sequence<S> extends Comparator<S> { // // S first(); // // S next(S seq); // // Sequence<Long> longs = new Sequence<Long>() { // // public int compare(Long seq1, Long seq2) { // return seq1.compareTo(seq2); // } // // public Long first() { // return 1L; // } // // public Long next(Long seq) { // return seq + 1; // } // }; // }
import eventsrc4j.EventStorageSpec; import eventsrc4j.Sequence; import fj.test.Arbitrary; import fj.test.Property; import fj.test.reflect.CheckParams; import fj.test.runner.PropertyTestRunner; import org.junit.runner.RunWith; import static fj.test.Gen.elements;
package eventsrc4j.memory; @RunWith(PropertyTestRunner.class) @CheckParams(maxSize = 10000, minSuccessful = 200) public final class MemoryEventStorageTest { private static final EventStorageSpec<Integer, Long, MemoryEventStorageTest.Event> spec = new EventStorageSpec<>(Arbitrary.arbInteger, elements(Event.values())); public Property read_return_write() {
// Path: core/src/test/java/eventsrc4j/EventStorageSpec.java // public final class EventStorageSpec<K, S, E> implements WStreamAction.Factory<K, S, E> { // // private final Gen<K> keys; // // private final Gen<E> events; // // public EventStorageSpec(Gen<K> keys, Gen<E> events) { // this.keys = keys; // this.events = events; // } // // public Property read_return_write(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // WriteResult<K, S, E> writeResult = stream // .write(lastSeq, Instant.EPOCH, singletonList(event)) // .runUnchecked(); // // return prop( // writeResult.events().map( // writtenEvents -> writtenEvents.length() == 1 // && writtenEvents.equals(stream // .read(lastSeq, Fold.toList()) // .runUnchecked()) // ).orSome(false) // ); // }); // } // // public Property read_return_write_actions( // Function<K, Predicate<WStreamAction<K, S, E, Boolean>>> actionInterpreter) { // return property(keys, events, key -> event -> { // // WStreamAction<K, S, E, Option<S>> lastSeqA = ReadEventStream(Option.none(), Fold.last()) // .map(last -> last.map(Events::getSeq)); // // WStreamAction<K, S, E, Boolean> compareEventsA = lastSeqA.bind(lastSeq -> { // // WStreamAction<K, S, E, List<Event<K, S, E>>> writeEventsA = // WriteEvents(lastSeq, Instant.EPOCH, single(event)) // .map(WriteResults::getEvents) // .map(es -> es.orSome(nil())); // // WStreamAction<K, S, E, List<Event<K, S, E>>> readEventsA = ReadEventStream(lastSeq, Fold.toList()); // // return writeEventsA.bind(writtenEvents -> // readEventsA.map(readEvents -> writtenEvents.length() == 1 && writtenEvents.equals(readEvents)) // ); // } // ); // // return prop(actionInterpreter.apply(key).test(compareEventsA)); // }); // } // // public Property concurrent_write_fails(EventStorage<K, S, E> eventStorage) { // return property(keys, events, key -> event -> { // // WritableEventStream<K, S, E> stream = eventStorage.stream(key); // // Option<S> lastSeq = // stream.read(none(), Fold.last()) // .runUnchecked() // .map(Events::getSeq); // // stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // WriteResult<K, S, E> concurrentWrite = stream // .write(lastSeq, Instant.EPOCH, single(event)) // .runUnchecked(); // // return prop(concurrentWrite.events().isNone()); // }); // } // } // // Path: core/src/main/java/eventsrc4j/Sequence.java // public interface Sequence<S> extends Comparator<S> { // // S first(); // // S next(S seq); // // Sequence<Long> longs = new Sequence<Long>() { // // public int compare(Long seq1, Long seq2) { // return seq1.compareTo(seq2); // } // // public Long first() { // return 1L; // } // // public Long next(Long seq) { // return seq + 1; // } // }; // } // Path: core/src/test/java/eventsrc4j/memory/MemoryEventStorageTest.java import eventsrc4j.EventStorageSpec; import eventsrc4j.Sequence; import fj.test.Arbitrary; import fj.test.Property; import fj.test.reflect.CheckParams; import fj.test.runner.PropertyTestRunner; import org.junit.runner.RunWith; import static fj.test.Gen.elements; package eventsrc4j.memory; @RunWith(PropertyTestRunner.class) @CheckParams(maxSize = 10000, minSuccessful = 200) public final class MemoryEventStorageTest { private static final EventStorageSpec<Integer, Long, MemoryEventStorageTest.Event> spec = new EventStorageSpec<>(Arbitrary.arbInteger, elements(Event.values())); public Property read_return_write() {
return spec.read_return_write(new MemoryEventStorage<>(Sequence.longs));