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
maxanier/MinecraftSecondScreenMod
src/main/java/de/maxgb/minecraft/second_screen/commands/GetIPCommand.java
// Path: src/main/java/de/maxgb/minecraft/second_screen/SecondScreenMod.java // @Mod(modid = Constants.MOD_ID, name = Constants.NAME, version = Constants.VERSION, dependencies = "required-after:FML", guiFactory = Constants.GUI_FACTORY_CLASS, acceptableRemoteVersions="*") // public class SecondScreenMod { // // public WebSocketListener webSocketListener; // public int port; // public String hostname; // public String latestOnlinePlayer="None since last restart"; // // @Mod.Instance(Constants.MOD_ID) // public static SecondScreenMod instance; // // private final String TAG = "Main"; // // @EventHandler // public void init(FMLInitializationEvent event) { // MSSEventHandler handler = new MSSEventHandler(); // FMLCommonHandler.instance().bus().register(new Configs()); // FMLCommonHandler.instance().bus().register(handler); // MinecraftForge.EVENT_BUS.register(handler); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // Configs.init(event.getSuggestedConfigurationFile()); // // //Sends message to VersionChecker if installed // FMLInterModComms.sendRuntimeMessage(Constants.MOD_ID, "VersionChecker", "addVersionCheck", // Constants.UPDATE_FILE_LINK); // // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent e) { // // hostname = Configs.hostname; // port = Configs.port; // // // loadData(); // // //Register actions // ActionManager.registerStandardActions(); // // //Register Commands // MssCommand mssc = new MssCommand(); // mssc.addSubCommand(new RegisterRedstoneInfoCommand()); // mssc.addSubCommand(new RegisterUserCommand()); // mssc.addSubCommand(new RegisterObserverCommand()); // e.registerServerCommand(mssc); // e.registerServerCommand(new GetIPCommand()); // e.registerServerCommand(new GetMSSPortCommand()); // e.registerServerCommand(new TestCommand()); // e.registerServerCommand(new ListInterfacesCommand()); // // start(); // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent e) { // stop(); // saveData(); // ActionManager.removeAllActions(); // } // // /** // * Creates and starts the websocket // */ // private void start() { // Logger.i(TAG, "Starting SecondScreenMod"); // // webSocketListener = new WebSocketListener(); // webSocketListener.start(); // } // // /** // * Stops the websocket // */ // private void stop() { // Logger.i(TAG, "Stopping SecondScreenMod"); // webSocketListener.stop(); // // webSocketListener = null; // } // // /** // * Loads saved informations from files // */ // private void loadData(){ // //Loads observation files // ObservingManager.loadObservingFile(); // // //Load users // UserManager.loadUsers(); // } // // /** // * Saves all informations to files // */ // public void saveData(){ // ObservingManager.saveObservingFile(); // UserManager.saveUsers(); // } // // // // }
import de.maxgb.minecraft.second_screen.SecondScreenMod; import net.minecraft.command.CommandException; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List;
public int compareTo(ICommand arg0) { return 0; } @Override public String getUsage(ICommandSender var1) { return "/getIP"; } @Override public boolean isUsernameIndex(String[] var1, int var2) { return false; } @Override public String getName() { return "getIP"; } @Override public List getAliases() { return aliases; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
// Path: src/main/java/de/maxgb/minecraft/second_screen/SecondScreenMod.java // @Mod(modid = Constants.MOD_ID, name = Constants.NAME, version = Constants.VERSION, dependencies = "required-after:FML", guiFactory = Constants.GUI_FACTORY_CLASS, acceptableRemoteVersions="*") // public class SecondScreenMod { // // public WebSocketListener webSocketListener; // public int port; // public String hostname; // public String latestOnlinePlayer="None since last restart"; // // @Mod.Instance(Constants.MOD_ID) // public static SecondScreenMod instance; // // private final String TAG = "Main"; // // @EventHandler // public void init(FMLInitializationEvent event) { // MSSEventHandler handler = new MSSEventHandler(); // FMLCommonHandler.instance().bus().register(new Configs()); // FMLCommonHandler.instance().bus().register(handler); // MinecraftForge.EVENT_BUS.register(handler); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // Configs.init(event.getSuggestedConfigurationFile()); // // //Sends message to VersionChecker if installed // FMLInterModComms.sendRuntimeMessage(Constants.MOD_ID, "VersionChecker", "addVersionCheck", // Constants.UPDATE_FILE_LINK); // // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent e) { // // hostname = Configs.hostname; // port = Configs.port; // // // loadData(); // // //Register actions // ActionManager.registerStandardActions(); // // //Register Commands // MssCommand mssc = new MssCommand(); // mssc.addSubCommand(new RegisterRedstoneInfoCommand()); // mssc.addSubCommand(new RegisterUserCommand()); // mssc.addSubCommand(new RegisterObserverCommand()); // e.registerServerCommand(mssc); // e.registerServerCommand(new GetIPCommand()); // e.registerServerCommand(new GetMSSPortCommand()); // e.registerServerCommand(new TestCommand()); // e.registerServerCommand(new ListInterfacesCommand()); // // start(); // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent e) { // stop(); // saveData(); // ActionManager.removeAllActions(); // } // // /** // * Creates and starts the websocket // */ // private void start() { // Logger.i(TAG, "Starting SecondScreenMod"); // // webSocketListener = new WebSocketListener(); // webSocketListener.start(); // } // // /** // * Stops the websocket // */ // private void stop() { // Logger.i(TAG, "Stopping SecondScreenMod"); // webSocketListener.stop(); // // webSocketListener = null; // } // // /** // * Loads saved informations from files // */ // private void loadData(){ // //Loads observation files // ObservingManager.loadObservingFile(); // // //Load users // UserManager.loadUsers(); // } // // /** // * Saves all informations to files // */ // public void saveData(){ // ObservingManager.saveObservingFile(); // UserManager.saveUsers(); // } // // // // } // Path: src/main/java/de/maxgb/minecraft/second_screen/commands/GetIPCommand.java import de.maxgb.minecraft.second_screen.SecondScreenMod; import net.minecraft.command.CommandException; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; public int compareTo(ICommand arg0) { return 0; } @Override public String getUsage(ICommandSender var1) { return "/getIP"; } @Override public boolean isUsernameIndex(String[] var1, int var2) { return false; } @Override public String getName() { return "getIP"; } @Override public List getAliases() { return aliases; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
if (SecondScreenMod.instance.webSocketListener.isRunning()) {
maxanier/MinecraftSecondScreenMod
src/api/java/org/java_websocket/framing/CloseFrame.java
// Path: src/api/java/org/java_websocket/exceptions/InvalidDataException.java // public class InvalidDataException extends Exception { // /** // * Serializable // */ // private static final long serialVersionUID = 3731842424390998726L; // // private int closecode; // // public InvalidDataException(int closecode) { // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s) { // super(s); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s, Throwable t) { // super(s, t); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, Throwable t) { // super(t); // this.closecode = closecode; // } // // public int getCloseCode() { // return closecode; // } // // } // // Path: src/api/java/org/java_websocket/exceptions/InvalidFrameException.java // public class InvalidFrameException extends InvalidDataException { // // /** // * Serializable // */ // private static final long serialVersionUID = -9016496369828887591L; // // public InvalidFrameException() { // super(CloseFrame.PROTOCOL_ERROR); // } // // public InvalidFrameException(String arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // // public InvalidFrameException(String arg0, Throwable arg1) { // super(CloseFrame.PROTOCOL_ERROR, arg0, arg1); // } // // public InvalidFrameException(Throwable arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // }
import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException;
package org.java_websocket.framing; public interface CloseFrame extends Framedata { /** * indicates a normal closure, meaning whatever purpose the connection was * established for has been fulfilled. */ public static final int NORMAL = 1000; /** * 1001 indicates that an endpoint is "going away", such as a server going * down, or a browser having navigated away from a page. */ public static final int GOING_AWAY = 1001; /** * 1002 indicates that an endpoint is terminating the connection due to a * protocol error. */ public static final int PROTOCOL_ERROR = 1002; /** * 1003 indicates that an endpoint is terminating the connection because it * has received a type of data it cannot accept (e.g. an endpoint that * understands only text data MAY send this if it receives a binary * message). */ public static final int REFUSE = 1003; /* 1004: Reserved. The specific meaning might be defined in the future. */ /** * 1005 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that no status code was actually * present. */ public static final int NOCODE = 1005; /** * 1006 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed * abnormally, e.g. without sending or receiving a Close control frame. */ public static final int ABNORMAL_CLOSE = 1006; /** * 1007 indicates that an endpoint is terminating the connection because it * has received data within a message that was not consistent with the type * of the message (e.g., non-UTF-8 [RFC3629] data within a text message). */ public static final int NO_UTF8 = 1007; /** * 1008 indicates that an endpoint is terminating the connection because it * has received a message that violates its policy. This is a generic status * code that can be returned when there is no other more suitable status * code (e.g. 1003 or 1009), or if there is a need to hide specific details * about the policy. */ public static final int POLICY_VALIDATION = 1008; /** * 1009 indicates that an endpoint is terminating the connection because it * has received a message which is too big for it to process. */ public static final int TOOBIG = 1009; /** * 1010 indicates that an endpoint (client) is terminating the connection * because it has expected the server to negotiate one or more extension, * but the server didn't return them in the response message of the * WebSocket handshake. The list of extensions which are needed SHOULD * appear in the /reason/ part of the Close frame. Note that this status * code is not used by the server, because it can fail the WebSocket * handshake instead. */ public static final int EXTENSION = 1010; /** * 1011 indicates that a server is terminating the connection because it * encountered an unexpected condition that prevented it from fulfilling the * request. **/ public static final int UNEXPECTED_CONDITION = 1011; /** * 1015 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed due to * a failure to perform a TLS handshake (e.g., the server certificate can't * be verified). **/ public static final int TLS_ERROR = 1015; /** The connection had never been established */ public static final int NEVER_CONNECTED = -1; public static final int BUGGYCLOSE = -2; public static final int FLASHPOLICY = -3;
// Path: src/api/java/org/java_websocket/exceptions/InvalidDataException.java // public class InvalidDataException extends Exception { // /** // * Serializable // */ // private static final long serialVersionUID = 3731842424390998726L; // // private int closecode; // // public InvalidDataException(int closecode) { // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s) { // super(s); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s, Throwable t) { // super(s, t); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, Throwable t) { // super(t); // this.closecode = closecode; // } // // public int getCloseCode() { // return closecode; // } // // } // // Path: src/api/java/org/java_websocket/exceptions/InvalidFrameException.java // public class InvalidFrameException extends InvalidDataException { // // /** // * Serializable // */ // private static final long serialVersionUID = -9016496369828887591L; // // public InvalidFrameException() { // super(CloseFrame.PROTOCOL_ERROR); // } // // public InvalidFrameException(String arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // // public InvalidFrameException(String arg0, Throwable arg1) { // super(CloseFrame.PROTOCOL_ERROR, arg0, arg1); // } // // public InvalidFrameException(Throwable arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // } // Path: src/api/java/org/java_websocket/framing/CloseFrame.java import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; package org.java_websocket.framing; public interface CloseFrame extends Framedata { /** * indicates a normal closure, meaning whatever purpose the connection was * established for has been fulfilled. */ public static final int NORMAL = 1000; /** * 1001 indicates that an endpoint is "going away", such as a server going * down, or a browser having navigated away from a page. */ public static final int GOING_AWAY = 1001; /** * 1002 indicates that an endpoint is terminating the connection due to a * protocol error. */ public static final int PROTOCOL_ERROR = 1002; /** * 1003 indicates that an endpoint is terminating the connection because it * has received a type of data it cannot accept (e.g. an endpoint that * understands only text data MAY send this if it receives a binary * message). */ public static final int REFUSE = 1003; /* 1004: Reserved. The specific meaning might be defined in the future. */ /** * 1005 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that no status code was actually * present. */ public static final int NOCODE = 1005; /** * 1006 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed * abnormally, e.g. without sending or receiving a Close control frame. */ public static final int ABNORMAL_CLOSE = 1006; /** * 1007 indicates that an endpoint is terminating the connection because it * has received data within a message that was not consistent with the type * of the message (e.g., non-UTF-8 [RFC3629] data within a text message). */ public static final int NO_UTF8 = 1007; /** * 1008 indicates that an endpoint is terminating the connection because it * has received a message that violates its policy. This is a generic status * code that can be returned when there is no other more suitable status * code (e.g. 1003 or 1009), or if there is a need to hide specific details * about the policy. */ public static final int POLICY_VALIDATION = 1008; /** * 1009 indicates that an endpoint is terminating the connection because it * has received a message which is too big for it to process. */ public static final int TOOBIG = 1009; /** * 1010 indicates that an endpoint (client) is terminating the connection * because it has expected the server to negotiate one or more extension, * but the server didn't return them in the response message of the * WebSocket handshake. The list of extensions which are needed SHOULD * appear in the /reason/ part of the Close frame. Note that this status * code is not used by the server, because it can fail the WebSocket * handshake instead. */ public static final int EXTENSION = 1010; /** * 1011 indicates that a server is terminating the connection because it * encountered an unexpected condition that prevented it from fulfilling the * request. **/ public static final int UNEXPECTED_CONDITION = 1011; /** * 1015 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed due to * a failure to perform a TLS handshake (e.g., the server certificate can't * be verified). **/ public static final int TLS_ERROR = 1015; /** The connection had never been established */ public static final int NEVER_CONNECTED = -1; public static final int BUGGYCLOSE = -2; public static final int FLASHPOLICY = -3;
public int getCloseCode() throws InvalidFrameException;
maxanier/MinecraftSecondScreenMod
src/api/java/org/java_websocket/framing/CloseFrame.java
// Path: src/api/java/org/java_websocket/exceptions/InvalidDataException.java // public class InvalidDataException extends Exception { // /** // * Serializable // */ // private static final long serialVersionUID = 3731842424390998726L; // // private int closecode; // // public InvalidDataException(int closecode) { // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s) { // super(s); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s, Throwable t) { // super(s, t); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, Throwable t) { // super(t); // this.closecode = closecode; // } // // public int getCloseCode() { // return closecode; // } // // } // // Path: src/api/java/org/java_websocket/exceptions/InvalidFrameException.java // public class InvalidFrameException extends InvalidDataException { // // /** // * Serializable // */ // private static final long serialVersionUID = -9016496369828887591L; // // public InvalidFrameException() { // super(CloseFrame.PROTOCOL_ERROR); // } // // public InvalidFrameException(String arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // // public InvalidFrameException(String arg0, Throwable arg1) { // super(CloseFrame.PROTOCOL_ERROR, arg0, arg1); // } // // public InvalidFrameException(Throwable arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // }
import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException;
package org.java_websocket.framing; public interface CloseFrame extends Framedata { /** * indicates a normal closure, meaning whatever purpose the connection was * established for has been fulfilled. */ public static final int NORMAL = 1000; /** * 1001 indicates that an endpoint is "going away", such as a server going * down, or a browser having navigated away from a page. */ public static final int GOING_AWAY = 1001; /** * 1002 indicates that an endpoint is terminating the connection due to a * protocol error. */ public static final int PROTOCOL_ERROR = 1002; /** * 1003 indicates that an endpoint is terminating the connection because it * has received a type of data it cannot accept (e.g. an endpoint that * understands only text data MAY send this if it receives a binary * message). */ public static final int REFUSE = 1003; /* 1004: Reserved. The specific meaning might be defined in the future. */ /** * 1005 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that no status code was actually * present. */ public static final int NOCODE = 1005; /** * 1006 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed * abnormally, e.g. without sending or receiving a Close control frame. */ public static final int ABNORMAL_CLOSE = 1006; /** * 1007 indicates that an endpoint is terminating the connection because it * has received data within a message that was not consistent with the type * of the message (e.g., non-UTF-8 [RFC3629] data within a text message). */ public static final int NO_UTF8 = 1007; /** * 1008 indicates that an endpoint is terminating the connection because it * has received a message that violates its policy. This is a generic status * code that can be returned when there is no other more suitable status * code (e.g. 1003 or 1009), or if there is a need to hide specific details * about the policy. */ public static final int POLICY_VALIDATION = 1008; /** * 1009 indicates that an endpoint is terminating the connection because it * has received a message which is too big for it to process. */ public static final int TOOBIG = 1009; /** * 1010 indicates that an endpoint (client) is terminating the connection * because it has expected the server to negotiate one or more extension, * but the server didn't return them in the response message of the * WebSocket handshake. The list of extensions which are needed SHOULD * appear in the /reason/ part of the Close frame. Note that this status * code is not used by the server, because it can fail the WebSocket * handshake instead. */ public static final int EXTENSION = 1010; /** * 1011 indicates that a server is terminating the connection because it * encountered an unexpected condition that prevented it from fulfilling the * request. **/ public static final int UNEXPECTED_CONDITION = 1011; /** * 1015 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed due to * a failure to perform a TLS handshake (e.g., the server certificate can't * be verified). **/ public static final int TLS_ERROR = 1015; /** The connection had never been established */ public static final int NEVER_CONNECTED = -1; public static final int BUGGYCLOSE = -2; public static final int FLASHPOLICY = -3; public int getCloseCode() throws InvalidFrameException;
// Path: src/api/java/org/java_websocket/exceptions/InvalidDataException.java // public class InvalidDataException extends Exception { // /** // * Serializable // */ // private static final long serialVersionUID = 3731842424390998726L; // // private int closecode; // // public InvalidDataException(int closecode) { // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s) { // super(s); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, String s, Throwable t) { // super(s, t); // this.closecode = closecode; // } // // public InvalidDataException(int closecode, Throwable t) { // super(t); // this.closecode = closecode; // } // // public int getCloseCode() { // return closecode; // } // // } // // Path: src/api/java/org/java_websocket/exceptions/InvalidFrameException.java // public class InvalidFrameException extends InvalidDataException { // // /** // * Serializable // */ // private static final long serialVersionUID = -9016496369828887591L; // // public InvalidFrameException() { // super(CloseFrame.PROTOCOL_ERROR); // } // // public InvalidFrameException(String arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // // public InvalidFrameException(String arg0, Throwable arg1) { // super(CloseFrame.PROTOCOL_ERROR, arg0, arg1); // } // // public InvalidFrameException(Throwable arg0) { // super(CloseFrame.PROTOCOL_ERROR, arg0); // } // } // Path: src/api/java/org/java_websocket/framing/CloseFrame.java import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; package org.java_websocket.framing; public interface CloseFrame extends Framedata { /** * indicates a normal closure, meaning whatever purpose the connection was * established for has been fulfilled. */ public static final int NORMAL = 1000; /** * 1001 indicates that an endpoint is "going away", such as a server going * down, or a browser having navigated away from a page. */ public static final int GOING_AWAY = 1001; /** * 1002 indicates that an endpoint is terminating the connection due to a * protocol error. */ public static final int PROTOCOL_ERROR = 1002; /** * 1003 indicates that an endpoint is terminating the connection because it * has received a type of data it cannot accept (e.g. an endpoint that * understands only text data MAY send this if it receives a binary * message). */ public static final int REFUSE = 1003; /* 1004: Reserved. The specific meaning might be defined in the future. */ /** * 1005 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that no status code was actually * present. */ public static final int NOCODE = 1005; /** * 1006 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed * abnormally, e.g. without sending or receiving a Close control frame. */ public static final int ABNORMAL_CLOSE = 1006; /** * 1007 indicates that an endpoint is terminating the connection because it * has received data within a message that was not consistent with the type * of the message (e.g., non-UTF-8 [RFC3629] data within a text message). */ public static final int NO_UTF8 = 1007; /** * 1008 indicates that an endpoint is terminating the connection because it * has received a message that violates its policy. This is a generic status * code that can be returned when there is no other more suitable status * code (e.g. 1003 or 1009), or if there is a need to hide specific details * about the policy. */ public static final int POLICY_VALIDATION = 1008; /** * 1009 indicates that an endpoint is terminating the connection because it * has received a message which is too big for it to process. */ public static final int TOOBIG = 1009; /** * 1010 indicates that an endpoint (client) is terminating the connection * because it has expected the server to negotiate one or more extension, * but the server didn't return them in the response message of the * WebSocket handshake. The list of extensions which are needed SHOULD * appear in the /reason/ part of the Close frame. Note that this status * code is not used by the server, because it can fail the WebSocket * handshake instead. */ public static final int EXTENSION = 1010; /** * 1011 indicates that a server is terminating the connection because it * encountered an unexpected condition that prevented it from fulfilling the * request. **/ public static final int UNEXPECTED_CONDITION = 1011; /** * 1015 is a reserved value and MUST NOT be set as a status code in a Close * control frame by an endpoint. It is designated for use in applications * expecting a status code to indicate that the connection was closed due to * a failure to perform a TLS handshake (e.g., the server certificate can't * be verified). **/ public static final int TLS_ERROR = 1015; /** The connection had never been established */ public static final int NEVER_CONNECTED = -1; public static final int BUGGYCLOSE = -2; public static final int FLASHPOLICY = -3; public int getCloseCode() throws InvalidFrameException;
public String getMessage() throws InvalidDataException;
maxanier/MinecraftSecondScreenMod
src/main/java/de/maxgb/minecraft/second_screen/commands/GetMSSPortCommand.java
// Path: src/main/java/de/maxgb/minecraft/second_screen/SecondScreenMod.java // @Mod(modid = Constants.MOD_ID, name = Constants.NAME, version = Constants.VERSION, dependencies = "required-after:FML", guiFactory = Constants.GUI_FACTORY_CLASS, acceptableRemoteVersions="*") // public class SecondScreenMod { // // public WebSocketListener webSocketListener; // public int port; // public String hostname; // public String latestOnlinePlayer="None since last restart"; // // @Mod.Instance(Constants.MOD_ID) // public static SecondScreenMod instance; // // private final String TAG = "Main"; // // @EventHandler // public void init(FMLInitializationEvent event) { // MSSEventHandler handler = new MSSEventHandler(); // FMLCommonHandler.instance().bus().register(new Configs()); // FMLCommonHandler.instance().bus().register(handler); // MinecraftForge.EVENT_BUS.register(handler); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // Configs.init(event.getSuggestedConfigurationFile()); // // //Sends message to VersionChecker if installed // FMLInterModComms.sendRuntimeMessage(Constants.MOD_ID, "VersionChecker", "addVersionCheck", // Constants.UPDATE_FILE_LINK); // // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent e) { // // hostname = Configs.hostname; // port = Configs.port; // // // loadData(); // // //Register actions // ActionManager.registerStandardActions(); // // //Register Commands // MssCommand mssc = new MssCommand(); // mssc.addSubCommand(new RegisterRedstoneInfoCommand()); // mssc.addSubCommand(new RegisterUserCommand()); // mssc.addSubCommand(new RegisterObserverCommand()); // e.registerServerCommand(mssc); // e.registerServerCommand(new GetIPCommand()); // e.registerServerCommand(new GetMSSPortCommand()); // e.registerServerCommand(new TestCommand()); // e.registerServerCommand(new ListInterfacesCommand()); // // start(); // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent e) { // stop(); // saveData(); // ActionManager.removeAllActions(); // } // // /** // * Creates and starts the websocket // */ // private void start() { // Logger.i(TAG, "Starting SecondScreenMod"); // // webSocketListener = new WebSocketListener(); // webSocketListener.start(); // } // // /** // * Stops the websocket // */ // private void stop() { // Logger.i(TAG, "Stopping SecondScreenMod"); // webSocketListener.stop(); // // webSocketListener = null; // } // // /** // * Loads saved informations from files // */ // private void loadData(){ // //Loads observation files // ObservingManager.loadObservingFile(); // // //Load users // UserManager.loadUsers(); // } // // /** // * Saves all informations to files // */ // public void saveData(){ // ObservingManager.saveObservingFile(); // UserManager.saveUsers(); // } // // // // }
import de.maxgb.minecraft.second_screen.SecondScreenMod; import net.minecraft.command.CommandException; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List;
public int compareTo(ICommand o) { return 0; } @Override public String getUsage(ICommandSender var1) { return "/getMssPort"; } @Override public boolean isUsernameIndex(String[] var1, int var2) { return false; } @Override public String getName() { return "getMssPort"; } @Override public List getAliases() { return aliase; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
// Path: src/main/java/de/maxgb/minecraft/second_screen/SecondScreenMod.java // @Mod(modid = Constants.MOD_ID, name = Constants.NAME, version = Constants.VERSION, dependencies = "required-after:FML", guiFactory = Constants.GUI_FACTORY_CLASS, acceptableRemoteVersions="*") // public class SecondScreenMod { // // public WebSocketListener webSocketListener; // public int port; // public String hostname; // public String latestOnlinePlayer="None since last restart"; // // @Mod.Instance(Constants.MOD_ID) // public static SecondScreenMod instance; // // private final String TAG = "Main"; // // @EventHandler // public void init(FMLInitializationEvent event) { // MSSEventHandler handler = new MSSEventHandler(); // FMLCommonHandler.instance().bus().register(new Configs()); // FMLCommonHandler.instance().bus().register(handler); // MinecraftForge.EVENT_BUS.register(handler); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // Configs.init(event.getSuggestedConfigurationFile()); // // //Sends message to VersionChecker if installed // FMLInterModComms.sendRuntimeMessage(Constants.MOD_ID, "VersionChecker", "addVersionCheck", // Constants.UPDATE_FILE_LINK); // // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent e) { // // hostname = Configs.hostname; // port = Configs.port; // // // loadData(); // // //Register actions // ActionManager.registerStandardActions(); // // //Register Commands // MssCommand mssc = new MssCommand(); // mssc.addSubCommand(new RegisterRedstoneInfoCommand()); // mssc.addSubCommand(new RegisterUserCommand()); // mssc.addSubCommand(new RegisterObserverCommand()); // e.registerServerCommand(mssc); // e.registerServerCommand(new GetIPCommand()); // e.registerServerCommand(new GetMSSPortCommand()); // e.registerServerCommand(new TestCommand()); // e.registerServerCommand(new ListInterfacesCommand()); // // start(); // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent e) { // stop(); // saveData(); // ActionManager.removeAllActions(); // } // // /** // * Creates and starts the websocket // */ // private void start() { // Logger.i(TAG, "Starting SecondScreenMod"); // // webSocketListener = new WebSocketListener(); // webSocketListener.start(); // } // // /** // * Stops the websocket // */ // private void stop() { // Logger.i(TAG, "Stopping SecondScreenMod"); // webSocketListener.stop(); // // webSocketListener = null; // } // // /** // * Loads saved informations from files // */ // private void loadData(){ // //Loads observation files // ObservingManager.loadObservingFile(); // // //Load users // UserManager.loadUsers(); // } // // /** // * Saves all informations to files // */ // public void saveData(){ // ObservingManager.saveObservingFile(); // UserManager.saveUsers(); // } // // // // } // Path: src/main/java/de/maxgb/minecraft/second_screen/commands/GetMSSPortCommand.java import de.maxgb.minecraft.second_screen.SecondScreenMod; import net.minecraft.command.CommandException; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; public int compareTo(ICommand o) { return 0; } @Override public String getUsage(ICommandSender var1) { return "/getMssPort"; } @Override public boolean isUsernameIndex(String[] var1, int var2) { return false; } @Override public String getName() { return "getMssPort"; } @Override public List getAliases() { return aliase; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
if (SecondScreenMod.instance.webSocketListener.isRunning()) {
gwtproject/gwt-places
processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryMapperProcessingStep.java
// Path: src/main/java/org/gwtproject/place/impl/AbstractPlaceHistoryMapper.java // public abstract class AbstractPlaceHistoryMapper implements PlaceHistoryMapper { // // /** Return value for {@link AbstractPlaceHistoryMapper#getPrefixAndToken(Place)}. */ // public static class PrefixAndToken { // public final String prefix; // public final String token; // // public PrefixAndToken(String prefix, String token) { // assert prefix != null && !prefix.contains(":"); // this.prefix = prefix; // this.token = token; // } // // @Override // public String toString() { // return (prefix.length() == 0) ? token : prefix + ":" + token; // } // } // // @Override // public Place getPlace(String token) { // int colonAt = token.indexOf(':'); // String initial; // String rest; // if (colonAt >= 0) { // initial = token.substring(0, colonAt); // rest = token.substring(colonAt + 1); // } else { // initial = ""; // rest = token; // } // PlaceTokenizer<?> tokenizer = getTokenizer(initial); // if (tokenizer != null) { // return tokenizer.getPlace(rest); // } // return null; // } // // @Override // public String getToken(Place place) { // PrefixAndToken token = getPrefixAndToken(place); // if (token != null) { // return token.toString(); // } // return null; // } // // /** // * Returns the token, or null. // * // * @param newPlace what needs tokenizing // */ // protected abstract PrefixAndToken getPrefixAndToken(Place newPlace); // // /** // * Returns the {@link PlaceTokenizer} registered with that token, or null. // * // * @param prefix the prefix found on the history token // */ // protected abstract PlaceTokenizer<?> getTokenizer(String prefix); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // }
import com.google.auto.common.BasicAnnotationProcessor.Step; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Sets; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.impl.AbstractPlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryMapperProcessingStep implements Step { private static final ClassName PREFIX_AND_TOKEN_CLASS_NAME =
// Path: src/main/java/org/gwtproject/place/impl/AbstractPlaceHistoryMapper.java // public abstract class AbstractPlaceHistoryMapper implements PlaceHistoryMapper { // // /** Return value for {@link AbstractPlaceHistoryMapper#getPrefixAndToken(Place)}. */ // public static class PrefixAndToken { // public final String prefix; // public final String token; // // public PrefixAndToken(String prefix, String token) { // assert prefix != null && !prefix.contains(":"); // this.prefix = prefix; // this.token = token; // } // // @Override // public String toString() { // return (prefix.length() == 0) ? token : prefix + ":" + token; // } // } // // @Override // public Place getPlace(String token) { // int colonAt = token.indexOf(':'); // String initial; // String rest; // if (colonAt >= 0) { // initial = token.substring(0, colonAt); // rest = token.substring(colonAt + 1); // } else { // initial = ""; // rest = token; // } // PlaceTokenizer<?> tokenizer = getTokenizer(initial); // if (tokenizer != null) { // return tokenizer.getPlace(rest); // } // return null; // } // // @Override // public String getToken(Place place) { // PrefixAndToken token = getPrefixAndToken(place); // if (token != null) { // return token.toString(); // } // return null; // } // // /** // * Returns the token, or null. // * // * @param newPlace what needs tokenizing // */ // protected abstract PrefixAndToken getPrefixAndToken(Place newPlace); // // /** // * Returns the {@link PlaceTokenizer} registered with that token, or null. // * // * @param prefix the prefix found on the history token // */ // protected abstract PlaceTokenizer<?> getTokenizer(String prefix); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // } // Path: processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryMapperProcessingStep.java import com.google.auto.common.BasicAnnotationProcessor.Step; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Sets; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.impl.AbstractPlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryMapperProcessingStep implements Step { private static final ClassName PREFIX_AND_TOKEN_CLASS_NAME =
ClassName.get(AbstractPlaceHistoryMapper.PrefixAndToken.class);
gwtproject/gwt-places
processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryMapperProcessingStep.java
// Path: src/main/java/org/gwtproject/place/impl/AbstractPlaceHistoryMapper.java // public abstract class AbstractPlaceHistoryMapper implements PlaceHistoryMapper { // // /** Return value for {@link AbstractPlaceHistoryMapper#getPrefixAndToken(Place)}. */ // public static class PrefixAndToken { // public final String prefix; // public final String token; // // public PrefixAndToken(String prefix, String token) { // assert prefix != null && !prefix.contains(":"); // this.prefix = prefix; // this.token = token; // } // // @Override // public String toString() { // return (prefix.length() == 0) ? token : prefix + ":" + token; // } // } // // @Override // public Place getPlace(String token) { // int colonAt = token.indexOf(':'); // String initial; // String rest; // if (colonAt >= 0) { // initial = token.substring(0, colonAt); // rest = token.substring(colonAt + 1); // } else { // initial = ""; // rest = token; // } // PlaceTokenizer<?> tokenizer = getTokenizer(initial); // if (tokenizer != null) { // return tokenizer.getPlace(rest); // } // return null; // } // // @Override // public String getToken(Place place) { // PrefixAndToken token = getPrefixAndToken(place); // if (token != null) { // return token.toString(); // } // return null; // } // // /** // * Returns the token, or null. // * // * @param newPlace what needs tokenizing // */ // protected abstract PrefixAndToken getPrefixAndToken(Place newPlace); // // /** // * Returns the {@link PlaceTokenizer} registered with that token, or null. // * // * @param prefix the prefix found on the history token // */ // protected abstract PlaceTokenizer<?> getTokenizer(String prefix); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // }
import com.google.auto.common.BasicAnnotationProcessor.Step; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Sets; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.impl.AbstractPlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryMapperProcessingStep implements Step { private static final ClassName PREFIX_AND_TOKEN_CLASS_NAME = ClassName.get(AbstractPlaceHistoryMapper.PrefixAndToken.class);
// Path: src/main/java/org/gwtproject/place/impl/AbstractPlaceHistoryMapper.java // public abstract class AbstractPlaceHistoryMapper implements PlaceHistoryMapper { // // /** Return value for {@link AbstractPlaceHistoryMapper#getPrefixAndToken(Place)}. */ // public static class PrefixAndToken { // public final String prefix; // public final String token; // // public PrefixAndToken(String prefix, String token) { // assert prefix != null && !prefix.contains(":"); // this.prefix = prefix; // this.token = token; // } // // @Override // public String toString() { // return (prefix.length() == 0) ? token : prefix + ":" + token; // } // } // // @Override // public Place getPlace(String token) { // int colonAt = token.indexOf(':'); // String initial; // String rest; // if (colonAt >= 0) { // initial = token.substring(0, colonAt); // rest = token.substring(colonAt + 1); // } else { // initial = ""; // rest = token; // } // PlaceTokenizer<?> tokenizer = getTokenizer(initial); // if (tokenizer != null) { // return tokenizer.getPlace(rest); // } // return null; // } // // @Override // public String getToken(Place place) { // PrefixAndToken token = getPrefixAndToken(place); // if (token != null) { // return token.toString(); // } // return null; // } // // /** // * Returns the token, or null. // * // * @param newPlace what needs tokenizing // */ // protected abstract PrefixAndToken getPrefixAndToken(Place newPlace); // // /** // * Returns the {@link PlaceTokenizer} registered with that token, or null. // * // * @param prefix the prefix found on the history token // */ // protected abstract PlaceTokenizer<?> getTokenizer(String prefix); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // } // Path: processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryMapperProcessingStep.java import com.google.auto.common.BasicAnnotationProcessor.Step; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Sets; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.impl.AbstractPlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryMapperProcessingStep implements Step { private static final ClassName PREFIX_AND_TOKEN_CLASS_NAME = ClassName.get(AbstractPlaceHistoryMapper.PrefixAndToken.class);
private static final ClassName PLACE_TOKENIZER_CLASS_NAME = ClassName.get(PlaceTokenizer.class);
gwtproject/gwt-places
processor/src/main/java/org/gwtproject/place/processor/PrefixProcessingStep.java
// Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // }
import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.Prefix; import com.google.auto.common.AnnotationMirrors; import com.google.auto.common.BasicAnnotationProcessor.Step; import com.google.auto.common.MoreElements; import com.google.common.collect.ImmutableSetMultimap; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class PrefixProcessingStep implements Step { private final Messager messager; private final Types types; private final TypeElement placeTokenizerTypeElement; public PrefixProcessingStep(Messager messager, Types types, Elements elements) { this.messager = messager; this.types = types; this.placeTokenizerTypeElement =
// Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // } // Path: processor/src/main/java/org/gwtproject/place/processor/PrefixProcessingStep.java import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.Prefix; import com.google.auto.common.AnnotationMirrors; import com.google.auto.common.BasicAnnotationProcessor.Step; import com.google.auto.common.MoreElements; import com.google.common.collect.ImmutableSetMultimap; import java.util.Collections; import java.util.Set; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class PrefixProcessingStep implements Step { private final Messager messager; private final Types types; private final TypeElement placeTokenizerTypeElement; public PrefixProcessingStep(Messager messager, Types types, Elements elements) { this.messager = messager; this.types = types; this.placeTokenizerTypeElement =
elements.getTypeElement(PlaceTokenizer.class.getCanonicalName());
gwtproject/gwt-places
processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // }
import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator();
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // } // Path: processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator();
place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName());
gwtproject/gwt-places
processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // }
import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull();
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // } // Path: processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull();
place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName());
gwtproject/gwt-places
processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // }
import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull();
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // } // Path: processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull();
place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName());
gwtproject/gwt-places
processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // }
import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull(); place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName()); assertThat(place2).isNotNull();
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // } // Path: processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull(); place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName()); assertThat(place2).isNotNull();
place3 = compilationRule.getElements().getTypeElement(Place3.class.getCanonicalName());
gwtproject/gwt-places
processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // }
import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull(); place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName()); assertThat(place2).isNotNull(); place3 = compilationRule.getElements().getTypeElement(Place3.class.getCanonicalName()); assertThat(place3).isNotNull();
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // } // Path: processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull(); place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName()); assertThat(place2).isNotNull(); place3 = compilationRule.getElements().getTypeElement(Place3.class.getCanonicalName()); assertThat(place3).isNotNull();
place4 = compilationRule.getElements().getTypeElement(Place4.class.getCanonicalName());
gwtproject/gwt-places
processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // }
import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull(); place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName()); assertThat(place2).isNotNull(); place3 = compilationRule.getElements().getTypeElement(Place3.class.getCanonicalName()); assertThat(place3).isNotNull(); place4 = compilationRule.getElements().getTypeElement(Place4.class.getCanonicalName()); assertThat(place4).isNotNull();
// Path: src/main/java/org/gwtproject/place/shared/Place.java // public abstract class Place { // // /** The null place. */ // public static final Place NOWHERE = new Place() {}; // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place1.java // public class Place1 extends Place { // public final String content; // // public Place1(String token) { // this.content = token; // } // // /** Tokenizer. */ // @Prefix(Tokenizer.PREFIX) // public static class Tokenizer implements PlaceTokenizer<Place1> { // public static final String PREFIX = "T1"; // // @Override // public Place1 getPlace(String token) { // return new Place1(token); // } // // @Override // public String getToken(Place1 place) { // return place.content; // } // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place2.java // public class Place2 extends Place { // public final String content; // // public Place2(String token) { // this.content = token; // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place3.java // public class Place3 extends Place1 { // // public Place3(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place4.java // public class Place4 extends Place1 { // // public Place4(String token) { // super(token); // } // } // // Path: processor/src/testSupport/java/org/gwtproject/place/testplaces/Place5.java // public class Place5 extends Place3 { // // public Place5(String token) { // super(token); // } // } // Path: processor/src/test/java/org/gwtproject/place/processor/MostToLeastDerivedPlaceTypeComparatorTest.java import static com.google.common.truth.Truth.*; import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.List; import javax.lang.model.element.TypeElement; import org.gwtproject.place.shared.Place; import org.gwtproject.place.testplaces.Place1; import org.gwtproject.place.testplaces.Place2; import org.gwtproject.place.testplaces.Place3; import org.gwtproject.place.testplaces.Place4; import org.gwtproject.place.testplaces.Place5; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; public class MostToLeastDerivedPlaceTypeComparatorTest { @Rule public CompilationRule compilationRule = new CompilationRule(); private MostToLeastDerivedPlaceTypeComparator comparator; private TypeElement place; private TypeElement place1; private TypeElement place2; private TypeElement place3; private TypeElement place4; private TypeElement place5; @Before public void setUp() { comparator = new MostToLeastDerivedPlaceTypeComparator(); place = compilationRule.getElements().getTypeElement(Place.class.getCanonicalName()); assertThat(place).isNotNull(); place1 = compilationRule.getElements().getTypeElement(Place1.class.getCanonicalName()); assertThat(place1).isNotNull(); place2 = compilationRule.getElements().getTypeElement(Place2.class.getCanonicalName()); assertThat(place2).isNotNull(); place3 = compilationRule.getElements().getTypeElement(Place3.class.getCanonicalName()); assertThat(place3).isNotNull(); place4 = compilationRule.getElements().getTypeElement(Place4.class.getCanonicalName()); assertThat(place4).isNotNull();
place5 = compilationRule.getElements().getTypeElement(Place5.class.getCanonicalName());
gwtproject/gwt-places
processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryGeneratorContext.java
// Path: src/main/java/org/gwtproject/place/shared/PlaceHistoryMapper.java // public interface PlaceHistoryMapper { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} instance // */ // Place getPlace(String token); // // /** // * Returns the String token associated with the given {@link Place}. // * // * @param place a {@link Place} instance // * @return a String token // */ // String getToken(Place place); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // }
import com.google.auto.common.AnnotationMirrors; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.shared.PlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.Prefix; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryGeneratorContext { final TypeElement stringType; final TypeElement placeTokenizerType; final Messager messager; final Types types; final Elements elements; final TypeElement interfaceType; final DeclaredType factoryType; final String implName; final String packageName; private HashMap<String, Element> tokenizers; private TreeMap<TypeElement, String> placeTypes = new TreeMap<>(new MostToLeastDerivedPlaceTypeComparator()); static PlaceHistoryGeneratorContext create( Messager messager, Types types, Elements elements, Element element) { TypeElement stringType = requireType(elements, String.class);
// Path: src/main/java/org/gwtproject/place/shared/PlaceHistoryMapper.java // public interface PlaceHistoryMapper { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} instance // */ // Place getPlace(String token); // // /** // * Returns the String token associated with the given {@link Place}. // * // * @param place a {@link Place} instance // * @return a String token // */ // String getToken(Place place); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // } // Path: processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryGeneratorContext.java import com.google.auto.common.AnnotationMirrors; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.shared.PlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.Prefix; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryGeneratorContext { final TypeElement stringType; final TypeElement placeTokenizerType; final Messager messager; final Types types; final Elements elements; final TypeElement interfaceType; final DeclaredType factoryType; final String implName; final String packageName; private HashMap<String, Element> tokenizers; private TreeMap<TypeElement, String> placeTypes = new TreeMap<>(new MostToLeastDerivedPlaceTypeComparator()); static PlaceHistoryGeneratorContext create( Messager messager, Types types, Elements elements, Element element) { TypeElement stringType = requireType(elements, String.class);
TypeElement placeTokenizerType = requireType(elements, PlaceTokenizer.class);
gwtproject/gwt-places
processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryGeneratorContext.java
// Path: src/main/java/org/gwtproject/place/shared/PlaceHistoryMapper.java // public interface PlaceHistoryMapper { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} instance // */ // Place getPlace(String token); // // /** // * Returns the String token associated with the given {@link Place}. // * // * @param place a {@link Place} instance // * @return a String token // */ // String getToken(Place place); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // }
import com.google.auto.common.AnnotationMirrors; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.shared.PlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.Prefix; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers;
/* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryGeneratorContext { final TypeElement stringType; final TypeElement placeTokenizerType; final Messager messager; final Types types; final Elements elements; final TypeElement interfaceType; final DeclaredType factoryType; final String implName; final String packageName; private HashMap<String, Element> tokenizers; private TreeMap<TypeElement, String> placeTypes = new TreeMap<>(new MostToLeastDerivedPlaceTypeComparator()); static PlaceHistoryGeneratorContext create( Messager messager, Types types, Elements elements, Element element) { TypeElement stringType = requireType(elements, String.class); TypeElement placeTokenizerType = requireType(elements, PlaceTokenizer.class);
// Path: src/main/java/org/gwtproject/place/shared/PlaceHistoryMapper.java // public interface PlaceHistoryMapper { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} instance // */ // Place getPlace(String token); // // /** // * Returns the String token associated with the given {@link Place}. // * // * @param place a {@link Place} instance // * @return a String token // */ // String getToken(Place place); // } // // Path: src/main/java/org/gwtproject/place/shared/PlaceTokenizer.java // public interface PlaceTokenizer<P extends Place> { // // /** // * Returns the {@link Place} associated with the given token. // * // * @param token a String token // * @return a {@link Place} of type P // */ // P getPlace(String token); // // /** // * Returns the token associated with the given {@link Place}. // * // * @param place a {@link Place} of type P // * @return a String token // */ // String getToken(P place); // } // Path: processor/src/main/java/org/gwtproject/place/processor/PlaceHistoryGeneratorContext.java import com.google.auto.common.AnnotationMirrors; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.gwtproject.place.shared.PlaceHistoryMapper; import org.gwtproject.place.shared.PlaceTokenizer; import org.gwtproject.place.shared.Prefix; import org.gwtproject.place.shared.WithFactory; import org.gwtproject.place.shared.WithTokenizers; /* * Copyright 2017 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.place.processor; class PlaceHistoryGeneratorContext { final TypeElement stringType; final TypeElement placeTokenizerType; final Messager messager; final Types types; final Elements elements; final TypeElement interfaceType; final DeclaredType factoryType; final String implName; final String packageName; private HashMap<String, Element> tokenizers; private TreeMap<TypeElement, String> placeTypes = new TreeMap<>(new MostToLeastDerivedPlaceTypeComparator()); static PlaceHistoryGeneratorContext create( Messager messager, Types types, Elements elements, Element element) { TypeElement stringType = requireType(elements, String.class); TypeElement placeTokenizerType = requireType(elements, PlaceTokenizer.class);
TypeElement placeHistoryMapperType = requireType(elements, PlaceHistoryMapper.class);
hlavki/g-suite-identity-sync
services/synchronize/client/src/main/java/eu/hlavki/identity/services/sync/client/CleanExternalUsersCommand.java
// Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.sync.client; @Service @Command(scope = "identity", name = "clean-external-users", description = "Remove all unassigned external users") public class CleanExternalUsersCommand implements Action { @Reference
// Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/synchronize/client/src/main/java/eu/hlavki/identity/services/sync/client/CleanExternalUsersCommand.java import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.sync.client; @Service @Command(scope = "identity", name = "clean-external-users", description = "Remove all unassigned external users") public class CleanExternalUsersCommand implements Action { @Reference
AccountSyncService syncService;
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // }
import eu.hlavki.identity.services.google.NoPrivateKeyException; import java.io.File; import java.security.PrivateKey; import java.time.Duration; import java.util.Set;
package eu.hlavki.identity.services.google.config; public interface Configuration { String getGSuiteDomain(); String getGSuiteImplicitGroup(); boolean isSetGSuiteImplicitGroup(); String getServiceAccountEmail(); String getServiceAccountSubject(); Set<String> getServiceAccountScopes();
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java import eu.hlavki.identity.services.google.NoPrivateKeyException; import java.io.File; import java.security.PrivateKey; import java.time.Duration; import java.util.Set; package eu.hlavki.identity.services.google.config; public interface Configuration { String getGSuiteDomain(); String getGSuiteImplicitGroup(); boolean isSetGSuiteImplicitGroup(); String getServiceAccountEmail(); String getServiceAccountSubject(); Set<String> getServiceAccountScopes();
PrivateKey readServiceAccountKey() throws NoPrivateKeyException;
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/GSuiteDirectoryServiceImpl.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/GSuiteDirectoryService.java // public interface GSuiteDirectoryService { // // /** // * Retrieve all groups for a member. // * // * @param userKey The userKey can be the user's primary email address, the user's alias email address, a // * group's primary email address, a group's email alias, or the user's unique id. // * @return all groups for a member // */ // GroupList getUserGroups(String userKey); // // // /** // * Read basic group information. This result does not contain group members. Call // * {@link #getGroupMembers(java.lang.String)} to obtain members. // * // * @param groupKey group identifier (email or ID) // * @return group info // * @throws eu.hlavki.identity.services.google.ResourceNotFoundException // */ // GSuiteGroup getGroup(String groupKey) throws ResourceNotFoundException; // // // /** // * Read all members for group. // * // * @param groupKey group identifier (email or ID) // * @return group info and members // */ // GroupMembership getGroupMembers(String groupKey) throws ResourceNotFoundException; // // // /** // * Read all GSuite groups. This result does not contain group members. Call // * {@link #getGroupMembers(java.lang.String)} to obtain members. // * // * @return all GSuite groups // */ // GroupList getAllGroups(); // // // /** // * Read members for all GSuite groups. Because it is very expesive operation, you can use cached values. // * Cache expires in 15 minutes. To use cache set useCache parameter to true. // * // * // * @return members for all GSuite groups. Key is group info object and value is membership // */ // Map<GSuiteGroup, GroupMembership> getAllGroupMembership(); // // // /** // * Retrieves a gsuite user from Directory API // * // * @param userKey Identifies the user in the API request. The value can be the user's primary email // * address, alias email address, or unique user ID. // * @return gsuite user // */ // GSuiteUser getUser(String userKey); // // // /** // * Retrieves list of users or all users in a domain. // * // * @return list of gsuite users // */ // GSuiteUsers getAllUsers(); // // // void updateUserPassword(String userKey, String password) throws InvalidPasswordException; // // // String getDomainName(); // // // String getImplicitGroup(); // // // String completeGroupEmail(String groupName); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/InvalidPasswordException.java // public class InvalidPasswordException extends Exception { // // private static final long serialVersionUID = 2712920621905135028L; // // public InvalidPasswordException() { // super(); // } // // // public InvalidPasswordException(String message) { // super(message); // } // // // public InvalidPasswordException(String message, Throwable cause) { // super(message, cause); // } // // // public InvalidPasswordException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // }
import eu.hlavki.identity.services.google.GSuiteDirectoryService; import eu.hlavki.identity.services.google.InvalidPasswordException; import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.*; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.google.impl; public class GSuiteDirectoryServiceImpl implements GSuiteDirectoryService { private static final Logger LOG = LoggerFactory.getLogger(GSuiteDirectoryServiceImpl.class); private final TokenCache tokenCache; private final WebClient directoryApiClient;
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/GSuiteDirectoryService.java // public interface GSuiteDirectoryService { // // /** // * Retrieve all groups for a member. // * // * @param userKey The userKey can be the user's primary email address, the user's alias email address, a // * group's primary email address, a group's email alias, or the user's unique id. // * @return all groups for a member // */ // GroupList getUserGroups(String userKey); // // // /** // * Read basic group information. This result does not contain group members. Call // * {@link #getGroupMembers(java.lang.String)} to obtain members. // * // * @param groupKey group identifier (email or ID) // * @return group info // * @throws eu.hlavki.identity.services.google.ResourceNotFoundException // */ // GSuiteGroup getGroup(String groupKey) throws ResourceNotFoundException; // // // /** // * Read all members for group. // * // * @param groupKey group identifier (email or ID) // * @return group info and members // */ // GroupMembership getGroupMembers(String groupKey) throws ResourceNotFoundException; // // // /** // * Read all GSuite groups. This result does not contain group members. Call // * {@link #getGroupMembers(java.lang.String)} to obtain members. // * // * @return all GSuite groups // */ // GroupList getAllGroups(); // // // /** // * Read members for all GSuite groups. Because it is very expesive operation, you can use cached values. // * Cache expires in 15 minutes. To use cache set useCache parameter to true. // * // * // * @return members for all GSuite groups. Key is group info object and value is membership // */ // Map<GSuiteGroup, GroupMembership> getAllGroupMembership(); // // // /** // * Retrieves a gsuite user from Directory API // * // * @param userKey Identifies the user in the API request. The value can be the user's primary email // * address, alias email address, or unique user ID. // * @return gsuite user // */ // GSuiteUser getUser(String userKey); // // // /** // * Retrieves list of users or all users in a domain. // * // * @return list of gsuite users // */ // GSuiteUsers getAllUsers(); // // // void updateUserPassword(String userKey, String password) throws InvalidPasswordException; // // // String getDomainName(); // // // String getImplicitGroup(); // // // String completeGroupEmail(String groupName); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/InvalidPasswordException.java // public class InvalidPasswordException extends Exception { // // private static final long serialVersionUID = 2712920621905135028L; // // public InvalidPasswordException() { // super(); // } // // // public InvalidPasswordException(String message) { // super(message); // } // // // public InvalidPasswordException(String message, Throwable cause) { // super(message, cause); // } // // // public InvalidPasswordException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/GSuiteDirectoryServiceImpl.java import eu.hlavki.identity.services.google.GSuiteDirectoryService; import eu.hlavki.identity.services.google.InvalidPasswordException; import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.*; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.google.impl; public class GSuiteDirectoryServiceImpl implements GSuiteDirectoryService { private static final Logger LOG = LoggerFactory.getLogger(GSuiteDirectoryServiceImpl.class); private final TokenCache tokenCache; private final WebClient directoryApiClient;
private final Configuration config;
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/config/impl/ConfigurationImpl.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // }
import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Duration; import java.util.*; import java.util.function.Consumer; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
public String getGSuiteImplicitGroup() { return get(GSUITE_IMPLICIT_GROUP); } @Override public boolean isSetGSuiteImplicitGroup() { return isSet(GSUITE_IMPLICIT_GROUP); } @Override public String getServiceAccountEmail() { return get(SERVICE_ACCOUNT_EMAIL_PROP); } @Override public String getServiceAccountSubject() { return get(SERVICE_ACCOUNT_SUBJECT_PROP); } @Override public Set<String> getServiceAccountScopes() { return getSet(SERVICE_ACCOUNT_SCOPES_PROP); } @Override
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/impl/ConfigurationImpl.java import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Duration; import java.util.*; import java.util.function.Consumer; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public String getGSuiteImplicitGroup() { return get(GSUITE_IMPLICIT_GROUP); } @Override public boolean isSetGSuiteImplicitGroup() { return isSet(GSUITE_IMPLICIT_GROUP); } @Override public String getServiceAccountEmail() { return get(SERVICE_ACCOUNT_EMAIL_PROP); } @Override public String getServiceAccountSubject() { return get(SERVICE_ACCOUNT_SUBJECT_PROP); } @Override public Set<String> getServiceAccountScopes() { return getSet(SERVICE_ACCOUNT_SCOPES_PROP); } @Override
public PrivateKey readServiceAccountKey() throws NoPrivateKeyException {
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/PushNotificationService.java
// Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // }
import eu.hlavki.identity.services.push.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.push; public class PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class);
// Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/PushNotificationService.java import eu.hlavki.identity.services.push.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.push; public class PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class);
private final Configuration config;
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/exception/ValidationExceptionMapper.java
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AppError.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class AppError { // // String code; // String message; // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new AppError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message) { // return Response.ok(new AppError(code, message)).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message, Response.Status status) { // return Response.ok(new AppError(code, message)).status(status); // } // }
import eu.hlavki.identity.services.rest.model.AppError; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider;
package eu.hlavki.identity.services.rest.exception; @Provider public class ValidationExceptionMapper extends org.apache.cxf.jaxrs.validation.ValidationExceptionMapper { public ValidationExceptionMapper() { } @Override protected Response buildResponse(Response.Status errorStatus, String responseText) {
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AppError.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class AppError { // // String code; // String message; // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new AppError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message) { // return Response.ok(new AppError(code, message)).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message, Response.Status status) { // return Response.ok(new AppError(code, message)).status(status); // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/exception/ValidationExceptionMapper.java import eu.hlavki.identity.services.rest.model.AppError; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; package eu.hlavki.identity.services.rest.exception; @Provider public class ValidationExceptionMapper extends org.apache.cxf.jaxrs.validation.ValidationExceptionMapper { public ValidationExceptionMapper() { } @Override protected Response buildResponse(Response.Status errorStatus, String responseText) {
return AppError.toResponse("VALIDATION_ERR", responseText, errorStatus).build();
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/security/SetupAuthorizationFilter.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/ServerError.java // @XmlRootElement // public class ServerError { // // String code; // String message; // // // public ServerError() { // } // // // public ServerError(String code, String message) { // this.code = code; // this.message = message; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public String getMessage() { // return message; // } // // // public void setMessage(String message) { // this.message = message; // } // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new ServerError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) { // String message = t != null ? t.getMessage() : null; // return serverError(status, code, message, t); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message) { // return serverError(status, code, message, null); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) { // return new ServerErrorException(Response.status(status) // .type(MediaType.APPLICATION_JSON) // .entity(new ServerError(code, message)).build(), t); // } // }
import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.rest.model.ServerError; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.apache.cxf.rs.security.oidc.rp.OidcSecurityContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.security; @Priority(Priorities.AUTHORIZATION) public class SetupAuthorizationFilter implements ContainerRequestFilter { private static final Logger log = LoggerFactory.getLogger(SetupAuthorizationFilter.class);
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/ServerError.java // @XmlRootElement // public class ServerError { // // String code; // String message; // // // public ServerError() { // } // // // public ServerError(String code, String message) { // this.code = code; // this.message = message; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public String getMessage() { // return message; // } // // // public void setMessage(String message) { // this.message = message; // } // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new ServerError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) { // String message = t != null ? t.getMessage() : null; // return serverError(status, code, message, t); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message) { // return serverError(status, code, message, null); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) { // return new ServerErrorException(Response.status(status) // .type(MediaType.APPLICATION_JSON) // .entity(new ServerError(code, message)).build(), t); // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/SetupAuthorizationFilter.java import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.rest.model.ServerError; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.apache.cxf.rs.security.oidc.rp.OidcSecurityContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.rest.security; @Priority(Priorities.AUTHORIZATION) public class SetupAuthorizationFilter implements ContainerRequestFilter { private static final Logger log = LoggerFactory.getLogger(SetupAuthorizationFilter.class);
private final Configuration googleConfig;
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/security/SetupAuthorizationFilter.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/ServerError.java // @XmlRootElement // public class ServerError { // // String code; // String message; // // // public ServerError() { // } // // // public ServerError(String code, String message) { // this.code = code; // this.message = message; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public String getMessage() { // return message; // } // // // public void setMessage(String message) { // this.message = message; // } // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new ServerError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) { // String message = t != null ? t.getMessage() : null; // return serverError(status, code, message, t); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message) { // return serverError(status, code, message, null); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) { // return new ServerErrorException(Response.status(status) // .type(MediaType.APPLICATION_JSON) // .entity(new ServerError(code, message)).build(), t); // } // }
import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.rest.model.ServerError; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.apache.cxf.rs.security.oidc.rp.OidcSecurityContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.security; @Priority(Priorities.AUTHORIZATION) public class SetupAuthorizationFilter implements ContainerRequestFilter { private static final Logger log = LoggerFactory.getLogger(SetupAuthorizationFilter.class); private final Configuration googleConfig; public SetupAuthorizationFilter(Configuration googleConfig) { this.googleConfig = googleConfig; } @Override public void filter(ContainerRequestContext requestContext) throws IOException { OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext(); OidcClientTokenContext tokenCtx = secCtx.getOidcContext(); IdToken idToken = tokenCtx.getIdToken(); String email = idToken.getEmail(); boolean configured = false; try { configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null;
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/ServerError.java // @XmlRootElement // public class ServerError { // // String code; // String message; // // // public ServerError() { // } // // // public ServerError(String code, String message) { // this.code = code; // this.message = message; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public String getMessage() { // return message; // } // // // public void setMessage(String message) { // this.message = message; // } // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new ServerError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) { // String message = t != null ? t.getMessage() : null; // return serverError(status, code, message, t); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message) { // return serverError(status, code, message, null); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) { // return new ServerErrorException(Response.status(status) // .type(MediaType.APPLICATION_JSON) // .entity(new ServerError(code, message)).build(), t); // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/SetupAuthorizationFilter.java import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.rest.model.ServerError; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.apache.cxf.rs.security.oidc.rp.OidcSecurityContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.rest.security; @Priority(Priorities.AUTHORIZATION) public class SetupAuthorizationFilter implements ContainerRequestFilter { private static final Logger log = LoggerFactory.getLogger(SetupAuthorizationFilter.class); private final Configuration googleConfig; public SetupAuthorizationFilter(Configuration googleConfig) { this.googleConfig = googleConfig; } @Override public void filter(ContainerRequestContext requestContext) throws IOException { OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext(); OidcClientTokenContext tokenCtx = secCtx.getOidcContext(); IdToken idToken = tokenCtx.getIdToken(); String email = idToken.getEmail(); boolean configured = false; try { configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null;
} catch (NoPrivateKeyException e) {
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/security/SetupAuthorizationFilter.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/ServerError.java // @XmlRootElement // public class ServerError { // // String code; // String message; // // // public ServerError() { // } // // // public ServerError(String code, String message) { // this.code = code; // this.message = message; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public String getMessage() { // return message; // } // // // public void setMessage(String message) { // this.message = message; // } // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new ServerError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) { // String message = t != null ? t.getMessage() : null; // return serverError(status, code, message, t); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message) { // return serverError(status, code, message, null); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) { // return new ServerErrorException(Response.status(status) // .type(MediaType.APPLICATION_JSON) // .entity(new ServerError(code, message)).build(), t); // } // }
import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.rest.model.ServerError; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.apache.cxf.rs.security.oidc.rp.OidcSecurityContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.security; @Priority(Priorities.AUTHORIZATION) public class SetupAuthorizationFilter implements ContainerRequestFilter { private static final Logger log = LoggerFactory.getLogger(SetupAuthorizationFilter.class); private final Configuration googleConfig; public SetupAuthorizationFilter(Configuration googleConfig) { this.googleConfig = googleConfig; } @Override public void filter(ContainerRequestContext requestContext) throws IOException { OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext(); OidcClientTokenContext tokenCtx = secCtx.getOidcContext(); IdToken idToken = tokenCtx.getIdToken(); String email = idToken.getEmail(); boolean configured = false; try { configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null; } catch (NoPrivateKeyException e) { } if (configured) { log.error("Unauthorized access from {}. Application is already configured!", email);
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/ServerError.java // @XmlRootElement // public class ServerError { // // String code; // String message; // // // public ServerError() { // } // // // public ServerError(String code, String message) { // this.code = code; // this.message = message; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public String getMessage() { // return message; // } // // // public void setMessage(String message) { // this.message = message; // } // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new ServerError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) { // String message = t != null ? t.getMessage() : null; // return serverError(status, code, message, t); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message) { // return serverError(status, code, message, null); // } // // // public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) { // return new ServerErrorException(Response.status(status) // .type(MediaType.APPLICATION_JSON) // .entity(new ServerError(code, message)).build(), t); // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/SetupAuthorizationFilter.java import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.rest.model.ServerError; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.apache.cxf.rs.security.oidc.rp.OidcSecurityContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.rest.security; @Priority(Priorities.AUTHORIZATION) public class SetupAuthorizationFilter implements ContainerRequestFilter { private static final Logger log = LoggerFactory.getLogger(SetupAuthorizationFilter.class); private final Configuration googleConfig; public SetupAuthorizationFilter(Configuration googleConfig) { this.googleConfig = googleConfig; } @Override public void filter(ContainerRequestContext requestContext) throws IOException { OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext(); OidcClientTokenContext tokenCtx = secCtx.getOidcContext(); IdToken idToken = tokenCtx.getIdToken(); String email = idToken.getEmail(); boolean configured = false; try { configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null; } catch (NoPrivateKeyException e) { } if (configured) { log.error("Unauthorized access from {}. Application is already configured!", email);
ServerError err = new ServerError("E002", "Unauthorized access to Configuration API");
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // }
import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.google.impl; public class PushNotificationServiceImpl implements PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationServiceImpl.class); private static final String PUSH_SCHEDULER_JOB = "PushNotificationJob";
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.google.impl; public class PushNotificationServiceImpl implements PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationServiceImpl.class); private static final String PUSH_SCHEDULER_JOB = "PushNotificationJob";
private Optional<PushChannel> channel = empty();
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // }
import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.google.impl; public class PushNotificationServiceImpl implements PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationServiceImpl.class); private static final String PUSH_SCHEDULER_JOB = "PushNotificationJob"; private Optional<PushChannel> channel = empty();
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.google.impl; public class PushNotificationServiceImpl implements PushNotificationService { private static final Logger log = LoggerFactory.getLogger(PushNotificationServiceImpl.class); private static final String PUSH_SCHEDULER_JOB = "PushNotificationJob"; private Optional<PushChannel> channel = empty();
private final Configuration config;
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // }
import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
public synchronized void disablePushNotifications() { channel.ifPresent(this::stopPushChannel); channel = empty(); scheduler.unschedule(PUSH_SCHEDULER_JOB); config.setPushEnabled(false); log.info("Push notifications disabled"); } @Override public synchronized void refreshPushNotifications() { if (isEnabled()) { if (channel.isEmpty()) { startPushChannel(config.getPushServiceHostname()); } else if (isExpired()) { String expiredId = channel.get().getId(); String resourceId = channel.get().getResourceId(); startPushChannel(config.getPushServiceHostname()); stopPushChannel(expiredId, resourceId); log.info("Push notification channel sucessfully refreshed"); } else { log.info("Push notification channel is fresh"); } } } @Override public void stopPushChannel(String id, String resourceId) {
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public synchronized void disablePushNotifications() { channel.ifPresent(this::stopPushChannel); channel = empty(); scheduler.unschedule(PUSH_SCHEDULER_JOB); config.setPushEnabled(false); log.info("Push notifications disabled"); } @Override public synchronized void refreshPushNotifications() { if (isEnabled()) { if (channel.isEmpty()) { startPushChannel(config.getPushServiceHostname()); } else if (isExpired()) { String expiredId = channel.get().getId(); String resourceId = channel.get().getResourceId(); startPushChannel(config.getPushServiceHostname()); stopPushChannel(expiredId, resourceId); log.info("Push notification channel sucessfully refreshed"); } else { log.info("Push notification channel is fresh"); } } } @Override public void stopPushChannel(String id, String resourceId) {
stopPushChannel(new StopPushChannel(id, resourceId));
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // }
import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
return config.isPushEnabled(); } private void startPushNotifications() { if (isEnabled()) { refreshPushNotifications(); startRefreshScheduler(); } } private void startRefreshScheduler() { try { if (!scheduler.getJobs().containsKey(PUSH_SCHEDULER_JOB)) { ScheduleOptions opts = scheduler.EXPR("0 0 * * * ?").name(PUSH_SCHEDULER_JOB); scheduler.schedule(new RefreshPushNotificationJob(this), opts); } } catch (SchedulerError e) { log.error("Cannot enable push notifications", e); } } private void startPushChannel(String hostname) { WebClient webClient = WebClient.fromClient(directoryApiClient, true) .path("/admin/reports/v1/activity/users/all/applications/admin/watch"); ClientAccessToken accessToken = tokenCache.getToken(); webClient.authorization(accessToken); String url = "https://" + hostname + "/cxf/push/notify";
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/PushChannel.java // @Getter // @Setter // @EqualsAndHashCode(onlyExplicitlyIncluded = true) // @ToString // @NoArgsConstructor // @XmlRootElement(name = "channel") // @XmlAccessorType(XmlAccessType.FIELD) // public class PushChannel { // // @EqualsAndHashCode.Include // @XmlElement // private String id; // @XmlElement // private String kind; // @XmlElement // private String resourceId; // @XmlElement // private String resourceUri; // @XmlElement // private String token; // @XmlElement // private Long expiration; // // // public boolean expiresIn(Duration bestBefore) { // return expiration - System.currentTimeMillis() < bestBefore.toMillis(); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StartPushChannel.java // @Data // @XmlRootElement // public class StartPushChannel { // // private String id; // private String type = "web_hook"; // private String address; // private String token; // private long expiration; // private Params params; // // // public StartPushChannel() { // id = UUID.randomUUID().toString(); // } // // // public StartPushChannel(String address, Duration duration) { // this(); // this.address = address; // this.expiration = System.currentTimeMillis() + duration.toMillis(); // // this.params = new Params(); // // this.params.ttl = duration.getSeconds(); // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // public static class Params { // // private long ttl; // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/model/StopPushChannel.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class StopPushChannel { // // private String id; // private String resourceId; // // // public StopPushChannel(PushChannel watching) { // this.id = watching.getId(); // this.resourceId = watching.getResourceId(); // } // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/PushNotificationServiceImpl.java import eu.hlavki.identity.services.google.PushNotificationService; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.PushChannel; import eu.hlavki.identity.services.google.model.StartPushChannel; import eu.hlavki.identity.services.google.model.StopPushChannel; import java.io.File; import java.time.Duration; import java.util.Optional; import static java.util.Optional.empty; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.karaf.scheduler.ScheduleOptions; import org.apache.karaf.scheduler.Scheduler; import org.apache.karaf.scheduler.SchedulerError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; return config.isPushEnabled(); } private void startPushNotifications() { if (isEnabled()) { refreshPushNotifications(); startRefreshScheduler(); } } private void startRefreshScheduler() { try { if (!scheduler.getJobs().containsKey(PUSH_SCHEDULER_JOB)) { ScheduleOptions opts = scheduler.EXPR("0 0 * * * ?").name(PUSH_SCHEDULER_JOB); scheduler.schedule(new RefreshPushNotificationJob(this), opts); } } catch (SchedulerError e) { log.error("Cannot enable push notifications", e); } } private void startPushChannel(String hostname) { WebClient webClient = WebClient.fromClient(directoryApiClient, true) .path("/admin/reports/v1/activity/users/all/applications/admin/watch"); ClientAccessToken accessToken = tokenCache.getToken(); webClient.authorization(accessToken); String url = "https://" + hostname + "/cxf/push/notify";
StartPushChannel watchRequest = new StartPushChannel(url, Duration.ofHours(6));
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/service/UserInfoService.java
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/UserInfo.java // @Getter // @Setter // @NoArgsConstructor // @XmlRootElement // public class UserInfo { // // private String name; // private String email; // private URI imageUri; // private boolean amAdmin; // // // public UserInfo(String name, String email) { // this.name = name; // this.email = email; // } // // // public UserInfo(String name, String email, boolean amAdmin, URI imageUri) { // this.name = name; // this.email = email; // this.amAdmin = amAdmin; // this.imageUri = imageUri; // } // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/AuthzRole.java // public interface AuthzRole { // // public static final String INTERNAL = "internal"; // public static final String EXTERNAL = "external"; // public static final String ADMIN = "admin"; // }
import eu.hlavki.identity.services.rest.model.UserInfo; import eu.hlavki.identity.services.rest.security.AuthzRole; import java.net.URI; import java.nio.charset.Charset; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriBuilder; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.service; @Path("user") public class UserInfoService { private static final Logger log = LoggerFactory.getLogger(UserInfoService.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); @Context private OidcClientTokenContext oidcContext; public UserInfoService() { } @GET
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/UserInfo.java // @Getter // @Setter // @NoArgsConstructor // @XmlRootElement // public class UserInfo { // // private String name; // private String email; // private URI imageUri; // private boolean amAdmin; // // // public UserInfo(String name, String email) { // this.name = name; // this.email = email; // } // // // public UserInfo(String name, String email, boolean amAdmin, URI imageUri) { // this.name = name; // this.email = email; // this.amAdmin = amAdmin; // this.imageUri = imageUri; // } // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/AuthzRole.java // public interface AuthzRole { // // public static final String INTERNAL = "internal"; // public static final String EXTERNAL = "external"; // public static final String ADMIN = "admin"; // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/service/UserInfoService.java import eu.hlavki.identity.services.rest.model.UserInfo; import eu.hlavki.identity.services.rest.security.AuthzRole; import java.net.URI; import java.nio.charset.Charset; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriBuilder; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.rest.service; @Path("user") public class UserInfoService { private static final Logger log = LoggerFactory.getLogger(UserInfoService.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); @Context private OidcClientTokenContext oidcContext; public UserInfoService() { } @GET
public UserInfo getUserInfo() {
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/service/UserInfoService.java
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/UserInfo.java // @Getter // @Setter // @NoArgsConstructor // @XmlRootElement // public class UserInfo { // // private String name; // private String email; // private URI imageUri; // private boolean amAdmin; // // // public UserInfo(String name, String email) { // this.name = name; // this.email = email; // } // // // public UserInfo(String name, String email, boolean amAdmin, URI imageUri) { // this.name = name; // this.email = email; // this.amAdmin = amAdmin; // this.imageUri = imageUri; // } // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/AuthzRole.java // public interface AuthzRole { // // public static final String INTERNAL = "internal"; // public static final String EXTERNAL = "external"; // public static final String ADMIN = "admin"; // }
import eu.hlavki.identity.services.rest.model.UserInfo; import eu.hlavki.identity.services.rest.security.AuthzRole; import java.net.URI; import java.nio.charset.Charset; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriBuilder; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.service; @Path("user") public class UserInfoService { private static final Logger log = LoggerFactory.getLogger(UserInfoService.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); @Context private OidcClientTokenContext oidcContext; public UserInfoService() { } @GET public UserInfo getUserInfo() { org.apache.cxf.rs.security.oidc.common.UserInfo userInfo = oidcContext.getUserInfo(); URI profilePicture = resizeProfilePicture(userInfo.getPicture()); Set<String> roles = (Set) userInfo.getProperty("securityRoles");
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/UserInfo.java // @Getter // @Setter // @NoArgsConstructor // @XmlRootElement // public class UserInfo { // // private String name; // private String email; // private URI imageUri; // private boolean amAdmin; // // // public UserInfo(String name, String email) { // this.name = name; // this.email = email; // } // // // public UserInfo(String name, String email, boolean amAdmin, URI imageUri) { // this.name = name; // this.email = email; // this.amAdmin = amAdmin; // this.imageUri = imageUri; // } // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/security/AuthzRole.java // public interface AuthzRole { // // public static final String INTERNAL = "internal"; // public static final String EXTERNAL = "external"; // public static final String ADMIN = "admin"; // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/service/UserInfoService.java import eu.hlavki.identity.services.rest.model.UserInfo; import eu.hlavki.identity.services.rest.security.AuthzRole; import java.net.URI; import java.nio.charset.Charset; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriBuilder; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.rest.service; @Path("user") public class UserInfoService { private static final Logger log = LoggerFactory.getLogger(UserInfoService.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); @Context private OidcClientTokenContext oidcContext; public UserInfoService() { } @GET public UserInfo getUserInfo() { org.apache.cxf.rs.security.oidc.common.UserInfo userInfo = oidcContext.getUserInfo(); URI profilePicture = resizeProfilePicture(userInfo.getPicture()); Set<String> roles = (Set) userInfo.getProperty("securityRoles");
boolean amAdmin = roles.contains(AuthzRole.ADMIN);
hlavki/g-suite-identity-sync
services/synchronize/scheduler/src/main/java/eu/hlavki/identity/services/scheduler/SyncGroupsJob.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.scheduler.Job; import org.apache.karaf.scheduler.JobContext; import org.apache.karaf.scheduler.Scheduler; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.scheduler; @Component(immediate = true, property = { Scheduler.PROPERTY_SCHEDULER_EXPRESSION + "=0 0 * * * ?", Scheduler.PROPERTY_SCHEDULER_NAME + "=SyncGroups", Scheduler.PROPERTY_SCHEDULER_CONCURRENT + ":Boolean=false"}) public class SyncGroupsJob implements Job { private static final Logger LOG = LoggerFactory.getLogger(SyncGroupsJob.class); @Reference
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/synchronize/scheduler/src/main/java/eu/hlavki/identity/services/scheduler/SyncGroupsJob.java import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.scheduler.Job; import org.apache.karaf.scheduler.JobContext; import org.apache.karaf.scheduler.Scheduler; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.scheduler; @Component(immediate = true, property = { Scheduler.PROPERTY_SCHEDULER_EXPRESSION + "=0 0 * * * ?", Scheduler.PROPERTY_SCHEDULER_NAME + "=SyncGroups", Scheduler.PROPERTY_SCHEDULER_CONCURRENT + ":Boolean=false"}) public class SyncGroupsJob implements Job { private static final Logger LOG = LoggerFactory.getLogger(SyncGroupsJob.class); @Reference
private AccountSyncService syncService;
hlavki/g-suite-identity-sync
services/synchronize/scheduler/src/main/java/eu/hlavki/identity/services/scheduler/SyncGroupsJob.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.scheduler.Job; import org.apache.karaf.scheduler.JobContext; import org.apache.karaf.scheduler.Scheduler; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.scheduler; @Component(immediate = true, property = { Scheduler.PROPERTY_SCHEDULER_EXPRESSION + "=0 0 * * * ?", Scheduler.PROPERTY_SCHEDULER_NAME + "=SyncGroups", Scheduler.PROPERTY_SCHEDULER_CONCURRENT + ":Boolean=false"}) public class SyncGroupsJob implements Job { private static final Logger LOG = LoggerFactory.getLogger(SyncGroupsJob.class); @Reference private AccountSyncService syncService; @Override public void execute(JobContext context) { try { LOG.info("Running scheduler for synchronizing all group"); syncService.synchronizeAllGroups();
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/synchronize/scheduler/src/main/java/eu/hlavki/identity/services/scheduler/SyncGroupsJob.java import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.scheduler.Job; import org.apache.karaf.scheduler.JobContext; import org.apache.karaf.scheduler.Scheduler; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.scheduler; @Component(immediate = true, property = { Scheduler.PROPERTY_SCHEDULER_EXPRESSION + "=0 0 * * * ?", Scheduler.PROPERTY_SCHEDULER_NAME + "=SyncGroups", Scheduler.PROPERTY_SCHEDULER_CONCURRENT + ":Boolean=false"}) public class SyncGroupsJob implements Job { private static final Logger LOG = LoggerFactory.getLogger(SyncGroupsJob.class); @Reference private AccountSyncService syncService; @Override public void execute(JobContext context) { try { LOG.info("Running scheduler for synchronizing all group"); syncService.synchronizeAllGroups();
} catch (LdapSystemException e) {
hlavki/g-suite-identity-sync
services/google/client/src/main/java/eu/hlavki/identity/services/google/client/ConfigureServiceAccountCommand.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // }
import eu.hlavki.identity.services.google.config.Configuration; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "configure-service-account", description = "Configure service account") public class ConfigureServiceAccountCommand implements Action { @Argument(index = 0, name = "clientEmail", description = "Service account client email", required = true, multiValued = false) String clientEmail; @Argument(index = 1, name = "privateKey", description = "Base64 encoded private key", required = true, multiValued = false) String privateKey; @Argument(index = 2, name = "subject", description = "Subject email", required = true, multiValued = false) String subject; @Argument(index = 3, name = "tokenUri", description = "Uri to obtain security token", required = true, multiValued = false) String tokenUri; @Reference
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // Path: services/google/client/src/main/java/eu/hlavki/identity/services/google/client/ConfigureServiceAccountCommand.java import eu.hlavki.identity.services.google.config.Configuration; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "configure-service-account", description = "Configure service account") public class ConfigureServiceAccountCommand implements Action { @Argument(index = 0, name = "clientEmail", description = "Service account client email", required = true, multiValued = false) String clientEmail; @Argument(index = 1, name = "privateKey", description = "Base64 encoded private key", required = true, multiValued = false) String privateKey; @Argument(index = 2, name = "subject", description = "Subject email", required = true, multiValued = false) String subject; @Argument(index = 3, name = "tokenUri", description = "Uri to obtain security token", required = true, multiValued = false) String tokenUri; @Reference
Configuration config;
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AccountInfo.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // }
import eu.hlavki.identity.services.ldap.model.LdapAccount; import java.util.Set; import javax.xml.bind.annotation.XmlRootElement; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter;
package eu.hlavki.identity.services.rest.model; @Getter @Setter @NoArgsConstructor @XmlRootElement public class AccountInfo { private String username; private Set<String> emails; private String subject; private String givenName; private String familyName; private String name; private Role role; private boolean syncGsuitePassword;
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AccountInfo.java import eu.hlavki.identity.services.ldap.model.LdapAccount; import java.util.Set; import javax.xml.bind.annotation.XmlRootElement; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; package eu.hlavki.identity.services.rest.model; @Getter @Setter @NoArgsConstructor @XmlRootElement public class AccountInfo { private String username; private Set<String> emails; private String subject; private String givenName; private String familyName; private String name; private Role role; private boolean syncGsuitePassword;
public AccountInfo(LdapAccount ldapAccount) {
hlavki/g-suite-identity-sync
services/google/client/src/main/java/eu/hlavki/identity/services/google/client/WatchDomainCommand.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // }
import eu.hlavki.identity.services.google.PushNotificationService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "watch-domain", description = "Watch domain") public class WatchDomainCommand implements Action { @Argument(index = 0, name = "hostname", description = "Hostname of REST service where google send notifications", required = true, multiValued = false) String hostname; @Reference
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // Path: services/google/client/src/main/java/eu/hlavki/identity/services/google/client/WatchDomainCommand.java import eu.hlavki.identity.services.google.PushNotificationService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "watch-domain", description = "Watch domain") public class WatchDomainCommand implements Action { @Argument(index = 0, name = "hostname", description = "Hostname of REST service where google send notifications", required = true, multiValued = false) String hostname; @Reference
PushNotificationService pushService;
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java
// Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/impl/ZonedDateTimeAdapter.java // public class ZonedDateTimeAdapter extends XmlAdapter<String, ZonedDateTime> { // // @Override // public ZonedDateTime unmarshal(String value) { // return (XMLDateTimeAdapter.parseDateTime(value)); // } // // @Override // public String marshal(ZonedDateTime value) { // return (XMLDateTimeAdapter.printDateTime(value)); // } // }
import eu.hlavki.identity.services.push.config.impl.ZonedDateTimeAdapter; import java.time.ZonedDateTime; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString;
package eu.hlavki.identity.services.push.model; @Getter @Setter @NoArgsConstructor @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class AuditRecord { private String kind; private Id id; private String etag; private String ipAddress; private List<Event> events; @Getter @Setter @NoArgsConstructor @XmlAccessorType(XmlAccessType.FIELD) public static class Id {
// Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/impl/ZonedDateTimeAdapter.java // public class ZonedDateTimeAdapter extends XmlAdapter<String, ZonedDateTime> { // // @Override // public ZonedDateTime unmarshal(String value) { // return (XMLDateTimeAdapter.parseDateTime(value)); // } // // @Override // public String marshal(ZonedDateTime value) { // return (XMLDateTimeAdapter.printDateTime(value)); // } // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java import eu.hlavki.identity.services.push.config.impl.ZonedDateTimeAdapter; import java.time.ZonedDateTime; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; package eu.hlavki.identity.services.push.model; @Getter @Setter @NoArgsConstructor @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class AuditRecord { private String kind; private Id id; private String etag; private String ipAddress; private List<Event> events; @Getter @Setter @NoArgsConstructor @XmlAccessorType(XmlAccessType.FIELD) public static class Id {
@XmlJavaTypeAdapter(ZonedDateTimeAdapter.class)
hlavki/g-suite-identity-sync
services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import org.apache.cxf.rs.security.oidc.common.UserInfo;
package eu.hlavki.identity.services.sync; public interface AccountSyncService { void synchronizeUserGroups(UserInfo userInfo);
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import org.apache.cxf.rs.security.oidc.common.UserInfo; package eu.hlavki.identity.services.sync; public interface AccountSyncService { void synchronizeUserGroups(UserInfo userInfo);
void synchronizeGroup(String groupEmail) throws ResourceNotFoundException;
hlavki/g-suite-identity-sync
services/synchronize/client/src/main/java/eu/hlavki/identity/services/sync/client/SyncUserAttributesCommand.java
// Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.sync.client; @Service @Command(scope = "identity", name = "synchronize-users-attr", description = "Synchronize G Suite user attributes") public class SyncUserAttributesCommand implements Action { @Reference
// Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/synchronize/client/src/main/java/eu/hlavki/identity/services/sync/client/SyncUserAttributesCommand.java import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.sync.client; @Service @Command(scope = "identity", name = "synchronize-users-attr", description = "Synchronize G Suite user attributes") public class SyncUserAttributesCommand implements Action { @Reference
AccountSyncService syncService;
hlavki/g-suite-identity-sync
services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapAccountService.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // public enum Role { // EXTERNAL, INTERNAL // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapGroup.java // public class LdapGroup { // // private String name; // private String dn; // private String description; // private Set<String> membersDn; // // // public LdapGroup() { // } // // // public LdapGroup(String name, String dn, String description, Set<String> members) { // this.name = name; // this.dn = dn; // this.membersDn = members; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getDn() { // return dn; // } // // // public void setDn(String dn) { // this.dn = dn; // } // // // /** // * Return set of membersDn DN. // * // * @return set of membersDn DN. // */ // public Set<String> getMembersDn() { // return membersDn; // } // // // public void setMembersDn(Set<String> membersDn) { // this.membersDn = membersDn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("name=").append(name).append(", dn=").append(dn). // append(", membersDN=").append(membersDn).append(", desc=").append(description).append("]"); // return sb.toString(); // } // // // public String getDescription() { // return description; // } // // // public void setDescription(String description) { // this.description = description; // } // }
import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapAccount.Role; import eu.hlavki.identity.services.ldap.model.LdapGroup; import java.util.List; import java.util.Optional; import java.util.Set;
package eu.hlavki.identity.services.ldap; public interface LdapAccountService { boolean accountExists(String subject);
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // public enum Role { // EXTERNAL, INTERNAL // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapGroup.java // public class LdapGroup { // // private String name; // private String dn; // private String description; // private Set<String> membersDn; // // // public LdapGroup() { // } // // // public LdapGroup(String name, String dn, String description, Set<String> members) { // this.name = name; // this.dn = dn; // this.membersDn = members; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getDn() { // return dn; // } // // // public void setDn(String dn) { // this.dn = dn; // } // // // /** // * Return set of membersDn DN. // * // * @return set of membersDn DN. // */ // public Set<String> getMembersDn() { // return membersDn; // } // // // public void setMembersDn(Set<String> membersDn) { // this.membersDn = membersDn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("name=").append(name).append(", dn=").append(dn). // append(", membersDN=").append(membersDn).append(", desc=").append(description).append("]"); // return sb.toString(); // } // // // public String getDescription() { // return description; // } // // // public void setDescription(String description) { // this.description = description; // } // } // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapAccountService.java import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapAccount.Role; import eu.hlavki.identity.services.ldap.model.LdapGroup; import java.util.List; import java.util.Optional; import java.util.Set; package eu.hlavki.identity.services.ldap; public interface LdapAccountService { boolean accountExists(String subject);
Optional<LdapAccount> getAccountBySubject(String subject);
hlavki/g-suite-identity-sync
services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapAccountService.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // public enum Role { // EXTERNAL, INTERNAL // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapGroup.java // public class LdapGroup { // // private String name; // private String dn; // private String description; // private Set<String> membersDn; // // // public LdapGroup() { // } // // // public LdapGroup(String name, String dn, String description, Set<String> members) { // this.name = name; // this.dn = dn; // this.membersDn = members; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getDn() { // return dn; // } // // // public void setDn(String dn) { // this.dn = dn; // } // // // /** // * Return set of membersDn DN. // * // * @return set of membersDn DN. // */ // public Set<String> getMembersDn() { // return membersDn; // } // // // public void setMembersDn(Set<String> membersDn) { // this.membersDn = membersDn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("name=").append(name).append(", dn=").append(dn). // append(", membersDN=").append(membersDn).append(", desc=").append(description).append("]"); // return sb.toString(); // } // // // public String getDescription() { // return description; // } // // // public void setDescription(String description) { // this.description = description; // } // }
import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapAccount.Role; import eu.hlavki.identity.services.ldap.model.LdapGroup; import java.util.List; import java.util.Optional; import java.util.Set;
package eu.hlavki.identity.services.ldap; public interface LdapAccountService { boolean accountExists(String subject); Optional<LdapAccount> getAccountBySubject(String subject); Optional<LdapAccount> getAccountByEmail(String email);
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // public enum Role { // EXTERNAL, INTERNAL // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapGroup.java // public class LdapGroup { // // private String name; // private String dn; // private String description; // private Set<String> membersDn; // // // public LdapGroup() { // } // // // public LdapGroup(String name, String dn, String description, Set<String> members) { // this.name = name; // this.dn = dn; // this.membersDn = members; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getDn() { // return dn; // } // // // public void setDn(String dn) { // this.dn = dn; // } // // // /** // * Return set of membersDn DN. // * // * @return set of membersDn DN. // */ // public Set<String> getMembersDn() { // return membersDn; // } // // // public void setMembersDn(Set<String> membersDn) { // this.membersDn = membersDn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("name=").append(name).append(", dn=").append(dn). // append(", membersDN=").append(membersDn).append(", desc=").append(description).append("]"); // return sb.toString(); // } // // // public String getDescription() { // return description; // } // // // public void setDescription(String description) { // this.description = description; // } // } // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapAccountService.java import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapAccount.Role; import eu.hlavki.identity.services.ldap.model.LdapGroup; import java.util.List; import java.util.Optional; import java.util.Set; package eu.hlavki.identity.services.ldap; public interface LdapAccountService { boolean accountExists(String subject); Optional<LdapAccount> getAccountBySubject(String subject); Optional<LdapAccount> getAccountByEmail(String email);
List<LdapAccount> searchAccounts(Role role);
hlavki/g-suite-identity-sync
services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapAccountService.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // public enum Role { // EXTERNAL, INTERNAL // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapGroup.java // public class LdapGroup { // // private String name; // private String dn; // private String description; // private Set<String> membersDn; // // // public LdapGroup() { // } // // // public LdapGroup(String name, String dn, String description, Set<String> members) { // this.name = name; // this.dn = dn; // this.membersDn = members; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getDn() { // return dn; // } // // // public void setDn(String dn) { // this.dn = dn; // } // // // /** // * Return set of membersDn DN. // * // * @return set of membersDn DN. // */ // public Set<String> getMembersDn() { // return membersDn; // } // // // public void setMembersDn(Set<String> membersDn) { // this.membersDn = membersDn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("name=").append(name).append(", dn=").append(dn). // append(", membersDN=").append(membersDn).append(", desc=").append(description).append("]"); // return sb.toString(); // } // // // public String getDescription() { // return description; // } // // // public void setDescription(String description) { // this.description = description; // } // }
import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapAccount.Role; import eu.hlavki.identity.services.ldap.model.LdapGroup; import java.util.List; import java.util.Optional; import java.util.Set;
package eu.hlavki.identity.services.ldap; public interface LdapAccountService { boolean accountExists(String subject); Optional<LdapAccount> getAccountBySubject(String subject); Optional<LdapAccount> getAccountByEmail(String email); List<LdapAccount> searchAccounts(Role role); List<LdapAccount> getAllAccounts(); void createAccount(LdapAccount account); void updateAccount(LdapAccount account);
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // @Getter // @Setter // @NoArgsConstructor // public class LdapAccount { // // public enum Role { // EXTERNAL, INTERNAL // } // // private String dn; // private String name; // private String givenName; // private String familyName; // private String username; // private String subject; // private Set<String> emails; // private String password; // private Role role; // // // public LdapAccount(String dn) { // this.dn = dn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("givenName=").append(givenName). // append(", familyName=").append(familyName). // append(", name=").append(name). // append(", username=").append(username). // append(", subject=").append(subject). // append(", emails=").append(emails). // append(", role=").append(role).append("]"); // return sb.toString(); // } // // public String getValueByAttr(String attr) { // switch (attr) { // case "cn": return getName(); // case "uid": return getUsername(); // default: return null; // } // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapAccount.java // public enum Role { // EXTERNAL, INTERNAL // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/model/LdapGroup.java // public class LdapGroup { // // private String name; // private String dn; // private String description; // private Set<String> membersDn; // // // public LdapGroup() { // } // // // public LdapGroup(String name, String dn, String description, Set<String> members) { // this.name = name; // this.dn = dn; // this.membersDn = members; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getDn() { // return dn; // } // // // public void setDn(String dn) { // this.dn = dn; // } // // // /** // * Return set of membersDn DN. // * // * @return set of membersDn DN. // */ // public Set<String> getMembersDn() { // return membersDn; // } // // // public void setMembersDn(Set<String> membersDn) { // this.membersDn = membersDn; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("["); // sb.append("name=").append(name).append(", dn=").append(dn). // append(", membersDN=").append(membersDn).append(", desc=").append(description).append("]"); // return sb.toString(); // } // // // public String getDescription() { // return description; // } // // // public void setDescription(String description) { // this.description = description; // } // } // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapAccountService.java import eu.hlavki.identity.services.ldap.model.LdapAccount; import eu.hlavki.identity.services.ldap.model.LdapAccount.Role; import eu.hlavki.identity.services.ldap.model.LdapGroup; import java.util.List; import java.util.Optional; import java.util.Set; package eu.hlavki.identity.services.ldap; public interface LdapAccountService { boolean accountExists(String subject); Optional<LdapAccount> getAccountBySubject(String subject); Optional<LdapAccount> getAccountByEmail(String email); List<LdapAccount> searchAccounts(Role role); List<LdapAccount> getAllAccounts(); void createAccount(LdapAccount account); void updateAccount(LdapAccount account);
LdapGroup getGroup(String groupName);
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/TokenCache.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // }
import com.google.common.base.Supplier; import static com.google.common.base.Suppliers.memoizeWithExpiration; import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import java.util.Arrays; import static java.util.concurrent.TimeUnit.SECONDS; import javax.ws.rs.core.MediaType; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.jose.common.JoseType; import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; import org.apache.cxf.rs.security.jose.jws.JwsHeaders; import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.apache.cxf.rs.security.jose.jwt.JwtToken; import org.apache.cxf.rs.security.oauth2.client.AccessTokenGrantWriter; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant; import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider; import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.google.impl; public class TokenCache { private static final Logger log = LoggerFactory.getLogger(TokenCache.class);
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/TokenCache.java import com.google.common.base.Supplier; import static com.google.common.base.Suppliers.memoizeWithExpiration; import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import java.util.Arrays; import static java.util.concurrent.TimeUnit.SECONDS; import javax.ws.rs.core.MediaType; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.jose.common.JoseType; import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; import org.apache.cxf.rs.security.jose.jws.JwsHeaders; import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.apache.cxf.rs.security.jose.jwt.JwtToken; import org.apache.cxf.rs.security.oauth2.client.AccessTokenGrantWriter; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant; import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider; import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.google.impl; public class TokenCache { private static final Logger log = LoggerFactory.getLogger(TokenCache.class);
private final Configuration config;
hlavki/g-suite-identity-sync
services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/TokenCache.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // }
import com.google.common.base.Supplier; import static com.google.common.base.Suppliers.memoizeWithExpiration; import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import java.util.Arrays; import static java.util.concurrent.TimeUnit.SECONDS; import javax.ws.rs.core.MediaType; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.jose.common.JoseType; import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; import org.apache.cxf.rs.security.jose.jws.JwsHeaders; import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.apache.cxf.rs.security.jose.jwt.JwtToken; import org.apache.cxf.rs.security.oauth2.client.AccessTokenGrantWriter; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant; import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider; import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.google.impl; public class TokenCache { private static final Logger log = LoggerFactory.getLogger(TokenCache.class); private final Configuration config; private final Supplier<ClientAccessToken> tokenCache; public TokenCache(Configuration config) { this.config = config; long tokenLifetime = config.getServiceAccountTokenLifetime(); log.info("Token lifetime set to {}", tokenLifetime); this.tokenCache = memoizeWithExpiration(() -> getAccessToken(), tokenLifetime - 3, SECONDS); } ClientAccessToken getToken() { return tokenCache.get(); }
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/NoPrivateKeyException.java // public class NoPrivateKeyException extends RuntimeException { // // private static final long serialVersionUID = 2712920621905135028L; // // public NoPrivateKeyException() { // super(); // } // // // public NoPrivateKeyException(String message) { // super(message); // } // // // public NoPrivateKeyException(String message, Throwable cause) { // super(message, cause); // } // // // public NoPrivateKeyException(Throwable cause) { // super(cause); // } // } // // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/config/Configuration.java // public interface Configuration { // // String getGSuiteDomain(); // // // String getGSuiteImplicitGroup(); // // // boolean isSetGSuiteImplicitGroup(); // // // String getServiceAccountEmail(); // // // String getServiceAccountSubject(); // // // Set<String> getServiceAccountScopes(); // // // PrivateKey readServiceAccountKey() throws NoPrivateKeyException; // // // void setServiceAccount(String clientEmail, String privateKey, String subject, String tokenUri); // // // void resetServiceAccount(); // // // String getServiceAccountTokenUri(); // // // long getServiceAccountTokenLifetime(); // // // String getPushServiceHostname(); // // // void setPushServiceHostname(String hostname); // // // File getPushChannelFile(); // // // boolean isPushEnabled(); // // // void setPushEnabled(boolean value); // // // Duration getPushRefreshInterval(); // } // Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/impl/TokenCache.java import com.google.common.base.Supplier; import static com.google.common.base.Suppliers.memoizeWithExpiration; import eu.hlavki.identity.services.google.NoPrivateKeyException; import eu.hlavki.identity.services.google.config.Configuration; import java.util.Arrays; import static java.util.concurrent.TimeUnit.SECONDS; import javax.ws.rs.core.MediaType; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.jose.common.JoseType; import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; import org.apache.cxf.rs.security.jose.jws.JwsHeaders; import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.apache.cxf.rs.security.jose.jwt.JwtToken; import org.apache.cxf.rs.security.oauth2.client.AccessTokenGrantWriter; import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken; import org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant; import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider; import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.google.impl; public class TokenCache { private static final Logger log = LoggerFactory.getLogger(TokenCache.class); private final Configuration config; private final Supplier<ClientAccessToken> tokenCache; public TokenCache(Configuration config) { this.config = config; long tokenLifetime = config.getServiceAccountTokenLifetime(); log.info("Token lifetime set to {}", tokenLifetime); this.tokenCache = memoizeWithExpiration(() -> getAccessToken(), tokenLifetime - 3, SECONDS); } ClientAccessToken getToken() { return tokenCache.get(); }
private ClientAccessToken getAccessToken() throws NoPrivateKeyException {
hlavki/g-suite-identity-sync
services/google/client/src/main/java/eu/hlavki/identity/services/google/client/StopPushChannel.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // }
import eu.hlavki.identity.services.google.PushNotificationService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "stop-channel", description = "Stop channel") public class StopPushChannel implements Action { @Argument(index = 0, name = "id", description = "Channel id", required = true, multiValued = false) String id; @Argument(index = 1, name = "resourceId", description = "Resource id", required = true, multiValued = false) String resourceId; @Reference
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // Path: services/google/client/src/main/java/eu/hlavki/identity/services/google/client/StopPushChannel.java import eu.hlavki.identity.services.google.PushNotificationService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "stop-channel", description = "Stop channel") public class StopPushChannel implements Action { @Argument(index = 0, name = "id", description = "Channel id", required = true, multiValued = false) String id; @Argument(index = 1, name = "resourceId", description = "Resource id", required = true, multiValued = false) String resourceId; @Reference
PushNotificationService pushService;
hlavki/g-suite-identity-sync
services/synchronize/client/src/main/java/eu/hlavki/identity/services/sync/client/SyncGroupsCommand.java
// Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.sync.client; @Service @Command(scope = "identity", name = "synchronize-groups", description = "Synchronize G Suite groups to LDAP") public class SyncGroupsCommand implements Action { @Reference
// Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/synchronize/client/src/main/java/eu/hlavki/identity/services/sync/client/SyncGroupsCommand.java import eu.hlavki.identity.services.sync.AccountSyncService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.sync.client; @Service @Command(scope = "identity", name = "synchronize-groups", description = "Synchronize G Suite groups to LDAP") public class SyncGroupsCommand implements Action { @Reference
AccountSyncService syncService;
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/exception/GenericExceptionMapper.java
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AppError.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class AppError { // // String code; // String message; // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new AppError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message) { // return Response.ok(new AppError(code, message)).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message, Response.Status status) { // return Response.ok(new AppError(code, message)).status(status); // } // }
import eu.hlavki.identity.services.rest.model.AppError; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.exception; @Provider public class GenericExceptionMapper implements ExceptionMapper<Exception> { private static final Logger log = LoggerFactory.getLogger(GenericExceptionMapper.class); @Override public Response toResponse(Exception exception) { log.error(null, exception);
// Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AppError.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class AppError { // // String code; // String message; // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new AppError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message) { // return Response.ok(new AppError(code, message)).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message, Response.Status status) { // return Response.ok(new AppError(code, message)).status(status); // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/exception/GenericExceptionMapper.java import eu.hlavki.identity.services.rest.model.AppError; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.rest.exception; @Provider public class GenericExceptionMapper implements ExceptionMapper<Exception> { private static final Logger log = LoggerFactory.getLogger(GenericExceptionMapper.class); @Override public Response toResponse(Exception exception) { log.error(null, exception);
return AppError.toResponse("SERVER_ERR", exception).build();
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class);
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class);
private final Configuration config;
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class); private final Configuration config;
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class); private final Configuration config;
private final AccountSyncService syncService;
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class); private final Configuration config; private final AccountSyncService syncService; public PushNotificationRest(Configuration config, AccountSyncService syncService) { this.config = config; this.syncService = syncService; } @POST @Path("notify") @Consumes(MediaType.APPLICATION_OCTET_STREAM) public void notifyChanges() { log.info("Init request from Google push notifications!"); } @POST @Path("notify") @Consumes(MediaType.APPLICATION_JSON)
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class); private final Configuration config; private final AccountSyncService syncService; public PushNotificationRest(Configuration config, AccountSyncService syncService) { this.config = config; this.syncService = syncService; } @POST @Path("notify") @Consumes(MediaType.APPLICATION_OCTET_STREAM) public void notifyChanges() { log.info("Init request from Google push notifications!"); } @POST @Path("notify") @Consumes(MediaType.APPLICATION_JSON)
public void notifyChanges(AuditRecord record) {
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class); private final Configuration config; private final AccountSyncService syncService; public PushNotificationRest(Configuration config, AccountSyncService syncService) { this.config = config; this.syncService = syncService; } @POST @Path("notify") @Consumes(MediaType.APPLICATION_OCTET_STREAM) public void notifyChanges() { log.info("Init request from Google push notifications!"); } @POST @Path("notify") @Consumes(MediaType.APPLICATION_JSON) public void notifyChanges(AuditRecord record) {
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package eu.hlavki.identity.services.push.rest; @Path("/") public class PushNotificationRest { private static final Logger log = LoggerFactory.getLogger(PushNotificationRest.class); private final Configuration config; private final AccountSyncService syncService; public PushNotificationRest(Configuration config, AccountSyncService syncService) { this.config = config; this.syncService = syncService; } @POST @Path("notify") @Consumes(MediaType.APPLICATION_OCTET_STREAM) public void notifyChanges() { log.info("Init request from Google push notifications!"); } @POST @Path("notify") @Consumes(MediaType.APPLICATION_JSON) public void notifyChanges(AuditRecord record) {
for (Event evt : record.getEvents()) {
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
break; default: syncGroup(evt); break; } break; case USER_SETTINGS: switch (evt.getName()) { case "DELETE_USER": deleteUser(evt); break; case "CHANGE_FIRST_NAME": case "CHANGE_LAST_NAME": syncUser(evt); break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); break; } break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); } } } private void syncGroup(Event evt) { try { syncService.synchronizeGroup(getGroupEmail(evt)); syncService.cleanExternalUsers();
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; break; default: syncGroup(evt); break; } break; case USER_SETTINGS: switch (evt.getName()) { case "DELETE_USER": deleteUser(evt); break; case "CHANGE_FIRST_NAME": case "CHANGE_LAST_NAME": syncUser(evt); break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); break; } break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); } } } private void syncGroup(Event evt) { try { syncService.synchronizeGroup(getGroupEmail(evt)); syncService.cleanExternalUsers();
} catch (LdapSystemException | ResourceNotFoundException e) {
hlavki/g-suite-identity-sync
services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // }
import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
break; default: syncGroup(evt); break; } break; case USER_SETTINGS: switch (evt.getName()) { case "DELETE_USER": deleteUser(evt); break; case "CHANGE_FIRST_NAME": case "CHANGE_LAST_NAME": syncUser(evt); break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); break; } break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); } } } private void syncGroup(Event evt) { try { syncService.synchronizeGroup(getGroupEmail(evt)); syncService.cleanExternalUsers();
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public ResourceNotFoundException() { // } // // // public ResourceNotFoundException(String message) { // super(message); // } // // // public ResourceNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // // public ResourceNotFoundException(Throwable cause) { // super(cause); // } // // // public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/config/Configuration.java // public interface Configuration { // // public static final String TOPIC_CHANGE = "eu/hlavki/identity/push/Configuration/CHANGED"; // // boolean isEnabled(); // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class AuditRecord { // // private String kind; // private Id id; // private String etag; // private String ipAddress; // private List<Event> events; // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Id { // // @XmlJavaTypeAdapter(ZonedDateTimeAdapter.class) // private ZonedDateTime time; // private Long uniqueQualifier; // private String applicationName; // private String customerId; // } // // @Getter // @Setter // @NoArgsConstructor // @XmlAccessorType(XmlAccessType.FIELD) // public static class Actor { // // private String callerType; // private String email; // private String profileId; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Parameter { // // private String name; // private String value; // private Integer intValue; // private Boolean boolValue; // } // } // // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/model/AuditRecord.java // @Getter // @Setter // @NoArgsConstructor // @ToString // @XmlAccessorType(XmlAccessType.FIELD) // public static class Event { // // private EventType type; // private String name; // private Long profileId; // private List<Parameter> parameters; // } // // Path: services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/AccountSyncService.java // public interface AccountSyncService { // // void synchronizeUserGroups(UserInfo userInfo); // // // void synchronizeGroup(String groupEmail) throws ResourceNotFoundException; // // // void removeGroup(String groupEmail); // // // void synchronizeAllGroups(); // // // void synchronizeGSuiteUser(String email); // // // void synchronizeGSuiteUsers(); // // // void removeUserByEmail(String email); // // // void cleanExternalUsers(); // } // Path: services/google/push/src/main/java/eu/hlavki/identity/services/push/rest/PushNotificationRest.java import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.push.config.Configuration; import eu.hlavki.identity.services.push.model.AuditRecord; import eu.hlavki.identity.services.push.model.AuditRecord.Event; import eu.hlavki.identity.services.sync.AccountSyncService; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; break; default: syncGroup(evt); break; } break; case USER_SETTINGS: switch (evt.getName()) { case "DELETE_USER": deleteUser(evt); break; case "CHANGE_FIRST_NAME": case "CHANGE_LAST_NAME": syncUser(evt); break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); break; } break; default: log.info("Event {} of type {} is not relevant for me!", evt.getName(), evt.getType()); } } } private void syncGroup(Event evt) { try { syncService.synchronizeGroup(getGroupEmail(evt)); syncService.cleanExternalUsers();
} catch (LdapSystemException | ResourceNotFoundException e) {
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/exception/LdapExceptionMapper.java
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AppError.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class AppError { // // String code; // String message; // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new AppError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message) { // return Response.ok(new AppError(code, message)).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message, Response.Status status) { // return Response.ok(new AppError(code, message)).status(status); // } // }
import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.rest.model.AppError; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider;
package eu.hlavki.identity.services.rest.exception; @Provider public class LdapExceptionMapper implements ExceptionMapper<LdapSystemException> { @Override public Response toResponse(LdapSystemException exception) {
// Path: services/ldap/api/src/main/java/eu/hlavki/identity/services/ldap/LdapSystemException.java // public class LdapSystemException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // // public LdapSystemException(String message) { // super(message); // } // // // public LdapSystemException(String message, Throwable cause) { // super(message, cause); // } // // // public LdapSystemException(Throwable cause) { // super(cause); // } // // // public LdapSystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/model/AppError.java // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @XmlRootElement // public class AppError { // // String code; // String message; // // // public final static ResponseBuilder toResponse(String code, Throwable t) { // return Response.ok(new AppError(code, t.getMessage())).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message) { // return Response.ok(new AppError(code, message)).status(Response.Status.INTERNAL_SERVER_ERROR); // } // // // public final static ResponseBuilder toResponse(String code, String message, Response.Status status) { // return Response.ok(new AppError(code, message)).status(status); // } // } // Path: services/facade/src/main/java/eu/hlavki/identity/services/rest/exception/LdapExceptionMapper.java import eu.hlavki.identity.services.ldap.LdapSystemException; import eu.hlavki.identity.services.rest.model.AppError; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; package eu.hlavki.identity.services.rest.exception; @Provider public class LdapExceptionMapper implements ExceptionMapper<LdapSystemException> { @Override public Response toResponse(LdapSystemException exception) {
return AppError.toResponse("LDAP_ERR", exception).build();
hlavki/g-suite-identity-sync
services/google/client/src/main/java/eu/hlavki/identity/services/google/client/StopWatchingDomainCommand.java
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // }
import eu.hlavki.identity.services.google.PushNotificationService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service;
package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "stop-watching-domain", description = "Stop watching domain") public class StopWatchingDomainCommand implements Action { @Reference
// Path: services/google/api/src/main/java/eu/hlavki/identity/services/google/PushNotificationService.java // public interface PushNotificationService { // // /** // * Enable push notification. Set hostname for push service // * // * @param hostname // */ // void enablePushNotifications(String hostname); // // // void disablePushNotifications(); // // // void refreshPushNotifications(); // // // void stopPushChannel(String id, String resourceId); // // // boolean isEnabled(); // } // Path: services/google/client/src/main/java/eu/hlavki/identity/services/google/client/StopWatchingDomainCommand.java import eu.hlavki.identity.services.google.PushNotificationService; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; package eu.hlavki.identity.services.google.client; @Service @Command(scope = "google", name = "stop-watching-domain", description = "Stop watching domain") public class StopWatchingDomainCommand implements Action { @Reference
PushNotificationService pushService;
nyatla/NyARToolkit-for-Processing
src/jp/nyatla/nyar4psg/SingleCameraView.java
// Path: src/jp/nyatla/nyar4psg/utils/PatchCollection.java // public interface PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far); // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg2x.java // final public class PatchCollection_Psg2x implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(0,i_width,0,i_height,i_near,i_far+1); // } // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg302.java // final public class PatchCollection_Psg302 implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(-i_width/2,i_width/2,-i_height/2,i_height/2,i_near,i_far+1);//3/x // } // }
import processing.core.PApplet; import processing.core.PImage; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; import jp.nyatla.nyar4psg.utils.PatchCollection; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg2x; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg302; import jp.nyatla.nyartoolkit.core.param.NyARParam; import jp.nyatla.nyartoolkit.core.types.matrix.NyARDoubleMatrix44; import jp.nyatla.nyartoolkit.markersystem.NyARSingleCameraView;
package jp.nyatla.nyar4psg; /** * カメラ1台の視点を管理するクラスです。 * オブジェクト検出クラスに視点情報に関連した機能を提供します。 */ public class SingleCameraView {
// Path: src/jp/nyatla/nyar4psg/utils/PatchCollection.java // public interface PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far); // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg2x.java // final public class PatchCollection_Psg2x implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(0,i_width,0,i_height,i_near,i_far+1); // } // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg302.java // final public class PatchCollection_Psg302 implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(-i_width/2,i_width/2,-i_height/2,i_height/2,i_near,i_far+1);//3/x // } // } // Path: src/jp/nyatla/nyar4psg/SingleCameraView.java import processing.core.PApplet; import processing.core.PImage; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; import jp.nyatla.nyar4psg.utils.PatchCollection; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg2x; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg302; import jp.nyatla.nyartoolkit.core.param.NyARParam; import jp.nyatla.nyartoolkit.core.types.matrix.NyARDoubleMatrix44; import jp.nyatla.nyartoolkit.markersystem.NyARSingleCameraView; package jp.nyatla.nyar4psg; /** * カメラ1台の視点を管理するクラスです。 * オブジェクト検出クラスに視点情報に関連した機能を提供します。 */ public class SingleCameraView {
final PatchCollection _patch_collection;
nyatla/NyARToolkit-for-Processing
src/jp/nyatla/nyar4psg/SingleCameraView.java
// Path: src/jp/nyatla/nyar4psg/utils/PatchCollection.java // public interface PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far); // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg2x.java // final public class PatchCollection_Psg2x implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(0,i_width,0,i_height,i_near,i_far+1); // } // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg302.java // final public class PatchCollection_Psg302 implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(-i_width/2,i_width/2,-i_height/2,i_height/2,i_near,i_far+1);//3/x // } // }
import processing.core.PApplet; import processing.core.PImage; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; import jp.nyatla.nyar4psg.utils.PatchCollection; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg2x; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg302; import jp.nyatla.nyartoolkit.core.param.NyARParam; import jp.nyatla.nyartoolkit.core.types.matrix.NyARDoubleMatrix44; import jp.nyatla.nyartoolkit.markersystem.NyARSingleCameraView;
/** * この関数は、視錐台のクリップ面を設定します。この値のデフォルト値は、{@link #FRUSTUM_DEFAULT_NEAR_CLIP}と{@link #FRUSTUM_DEFAULT_FAR_CLIP}です。 * 設定値は、次回の{@link #setARPerspective()}から影響を及ぼします。現在の設定値にただちに影響を及ぼすものではありません。 * @param i_width * @param i_height * @param i_near * NearPlaneの値を設定します。単位は[mm]です。 * @param i_far * FarPlaneの値を設定します。単位は[mm]です。 */ public void setARClipping(int i_width,int i_height,float i_near,float i_far) { this._clip_far=i_far; this._clip_near=i_near; this._ps_background_mv.reset(); this._ps_background_mv.translate(0,0,-i_far); NyARDoubleMatrix44 tmp=new NyARDoubleMatrix44(); this._view.getARParam().getPerspectiveProjectionMatrix().makeCameraFrustumRH(i_width,i_height,i_near,i_far,tmp); NyPsUtils.nyarMat2PsMat(tmp,this._ps_projection); } /** * バージョンIDからパッチコレクションオブジェクトを返します。からコンストラクタから使います。 * @param i_version_id * ProcessingのバージョンIDです。 * @return */ private static PatchCollection createPatchCollection(int i_version_id) { switch(i_version_id){ case NyAR4PsgConfig.PV_221:
// Path: src/jp/nyatla/nyar4psg/utils/PatchCollection.java // public interface PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far); // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg2x.java // final public class PatchCollection_Psg2x implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(0,i_width,0,i_height,i_near,i_far+1); // } // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg302.java // final public class PatchCollection_Psg302 implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(-i_width/2,i_width/2,-i_height/2,i_height/2,i_near,i_far+1);//3/x // } // } // Path: src/jp/nyatla/nyar4psg/SingleCameraView.java import processing.core.PApplet; import processing.core.PImage; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; import jp.nyatla.nyar4psg.utils.PatchCollection; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg2x; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg302; import jp.nyatla.nyartoolkit.core.param.NyARParam; import jp.nyatla.nyartoolkit.core.types.matrix.NyARDoubleMatrix44; import jp.nyatla.nyartoolkit.markersystem.NyARSingleCameraView; /** * この関数は、視錐台のクリップ面を設定します。この値のデフォルト値は、{@link #FRUSTUM_DEFAULT_NEAR_CLIP}と{@link #FRUSTUM_DEFAULT_FAR_CLIP}です。 * 設定値は、次回の{@link #setARPerspective()}から影響を及ぼします。現在の設定値にただちに影響を及ぼすものではありません。 * @param i_width * @param i_height * @param i_near * NearPlaneの値を設定します。単位は[mm]です。 * @param i_far * FarPlaneの値を設定します。単位は[mm]です。 */ public void setARClipping(int i_width,int i_height,float i_near,float i_far) { this._clip_far=i_far; this._clip_near=i_near; this._ps_background_mv.reset(); this._ps_background_mv.translate(0,0,-i_far); NyARDoubleMatrix44 tmp=new NyARDoubleMatrix44(); this._view.getARParam().getPerspectiveProjectionMatrix().makeCameraFrustumRH(i_width,i_height,i_near,i_far,tmp); NyPsUtils.nyarMat2PsMat(tmp,this._ps_projection); } /** * バージョンIDからパッチコレクションオブジェクトを返します。からコンストラクタから使います。 * @param i_version_id * ProcessingのバージョンIDです。 * @return */ private static PatchCollection createPatchCollection(int i_version_id) { switch(i_version_id){ case NyAR4PsgConfig.PV_221:
return new PatchCollection_Psg2x();
nyatla/NyARToolkit-for-Processing
src/jp/nyatla/nyar4psg/SingleCameraView.java
// Path: src/jp/nyatla/nyar4psg/utils/PatchCollection.java // public interface PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far); // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg2x.java // final public class PatchCollection_Psg2x implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(0,i_width,0,i_height,i_near,i_far+1); // } // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg302.java // final public class PatchCollection_Psg302 implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(-i_width/2,i_width/2,-i_height/2,i_height/2,i_near,i_far+1);//3/x // } // }
import processing.core.PApplet; import processing.core.PImage; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; import jp.nyatla.nyar4psg.utils.PatchCollection; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg2x; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg302; import jp.nyatla.nyartoolkit.core.param.NyARParam; import jp.nyatla.nyartoolkit.core.types.matrix.NyARDoubleMatrix44; import jp.nyatla.nyartoolkit.markersystem.NyARSingleCameraView;
* @param i_width * @param i_height * @param i_near * NearPlaneの値を設定します。単位は[mm]です。 * @param i_far * FarPlaneの値を設定します。単位は[mm]です。 */ public void setARClipping(int i_width,int i_height,float i_near,float i_far) { this._clip_far=i_far; this._clip_near=i_near; this._ps_background_mv.reset(); this._ps_background_mv.translate(0,0,-i_far); NyARDoubleMatrix44 tmp=new NyARDoubleMatrix44(); this._view.getARParam().getPerspectiveProjectionMatrix().makeCameraFrustumRH(i_width,i_height,i_near,i_far,tmp); NyPsUtils.nyarMat2PsMat(tmp,this._ps_projection); } /** * バージョンIDからパッチコレクションオブジェクトを返します。からコンストラクタから使います。 * @param i_version_id * ProcessingのバージョンIDです。 * @return */ private static PatchCollection createPatchCollection(int i_version_id) { switch(i_version_id){ case NyAR4PsgConfig.PV_221: return new PatchCollection_Psg2x(); case NyAR4PsgConfig.PV_302: default:
// Path: src/jp/nyatla/nyar4psg/utils/PatchCollection.java // public interface PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far); // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg2x.java // final public class PatchCollection_Psg2x implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(0,i_width,0,i_height,i_near,i_far+1); // } // } // // Path: src/jp/nyatla/nyar4psg/utils/PatchCollection_Psg302.java // final public class PatchCollection_Psg302 implements PatchCollection // { // public void setBackgroundOrtho(PApplet i_applet,float i_width,float i_height,float i_near,float i_far) // { // i_applet.ortho(-i_width/2,i_width/2,-i_height/2,i_height/2,i_near,i_far+1);//3/x // } // } // Path: src/jp/nyatla/nyar4psg/SingleCameraView.java import processing.core.PApplet; import processing.core.PImage; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; import jp.nyatla.nyar4psg.utils.PatchCollection; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg2x; import jp.nyatla.nyar4psg.utils.PatchCollection_Psg302; import jp.nyatla.nyartoolkit.core.param.NyARParam; import jp.nyatla.nyartoolkit.core.types.matrix.NyARDoubleMatrix44; import jp.nyatla.nyartoolkit.markersystem.NyARSingleCameraView; * @param i_width * @param i_height * @param i_near * NearPlaneの値を設定します。単位は[mm]です。 * @param i_far * FarPlaneの値を設定します。単位は[mm]です。 */ public void setARClipping(int i_width,int i_height,float i_near,float i_far) { this._clip_far=i_far; this._clip_near=i_near; this._ps_background_mv.reset(); this._ps_background_mv.translate(0,0,-i_far); NyARDoubleMatrix44 tmp=new NyARDoubleMatrix44(); this._view.getARParam().getPerspectiveProjectionMatrix().makeCameraFrustumRH(i_width,i_height,i_near,i_far,tmp); NyPsUtils.nyarMat2PsMat(tmp,this._ps_projection); } /** * バージョンIDからパッチコレクションオブジェクトを返します。からコンストラクタから使います。 * @param i_version_id * ProcessingのバージョンIDです。 * @return */ private static PatchCollection createPatchCollection(int i_version_id) { switch(i_version_id){ case NyAR4PsgConfig.PV_221: return new PatchCollection_Psg2x(); case NyAR4PsgConfig.PV_302: default:
return new PatchCollection_Psg302();
wymarc/astrolabe-generator
src/main/java/com/wymarc/astrolabe/generator/config/Config.java
// Path: src/main/java/com/wymarc/astrolabe/generator/AstrolabeGenerator.java // public class AstrolabeGenerator{ // // public AstrolabeGenerator(){ // GeneratorGui gui = new GeneratorGui(); // } // // // public static void main(String[] args) { // javax.swing.SwingUtilities.invokeLater(new Runnable() { // public void run() { // new AstrolabeGenerator(); // } // }); // } // }
import com.wymarc.astrolabe.generator.AstrolabeGenerator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.util.ArrayList; import java.util.List;
/** * $Id: AstrolabeGenerator.java,v 3.1 * <p/> * The Astrolabe Generator is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 of * the License, or(at your option) any later version. * <p/> * The Astrolabe Generator 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. * <p/> * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * <p/> * Copyright (c) 2017 Timothy J. Mitchell */ package com.wymarc.astrolabe.generator.config; public class Config { public static String version = ""; private String defaultLocationName = ""; private String defaultLocation = ""; private List<ClimateSet> climateSets; private List<AstrolabeExample> astrolabeExamples; public Config() { try {
// Path: src/main/java/com/wymarc/astrolabe/generator/AstrolabeGenerator.java // public class AstrolabeGenerator{ // // public AstrolabeGenerator(){ // GeneratorGui gui = new GeneratorGui(); // } // // // public static void main(String[] args) { // javax.swing.SwingUtilities.invokeLater(new Runnable() { // public void run() { // new AstrolabeGenerator(); // } // }); // } // } // Path: src/main/java/com/wymarc/astrolabe/generator/config/Config.java import com.wymarc.astrolabe.generator.AstrolabeGenerator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * $Id: AstrolabeGenerator.java,v 3.1 * <p/> * The Astrolabe Generator is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 of * the License, or(at your option) any later version. * <p/> * The Astrolabe Generator 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. * <p/> * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * <p/> * Copyright (c) 2017 Timothy J. Mitchell */ package com.wymarc.astrolabe.generator.config; public class Config { public static String version = ""; private String defaultLocationName = ""; private String defaultLocation = ""; private List<ClimateSet> climateSets; private List<AstrolabeExample> astrolabeExamples; public Config() { try {
InputStream is = AstrolabeGenerator.class.getResourceAsStream("astrolabe_config.xml");
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/ViewModel/RunsUserLoginViewModel.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Callback/RequestCallback.java // public interface RequestCallback<T> { // void success(T response); // void error(Error err); // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Model/RunsUserInfo.java // public class RunsUserInfo { // // private String name; // private int age; // private int sex; // // public int getSex() { // return sex; // } // // public void setSex(int sex) { // this.sex = sex; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/ViewModel.java // public class ViewModel implements IViewModel { // protected String TAG = this.getClass().getName(); // private Object model = null; // private String name = null; // // @Override // public void initializeViewModel() { // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setModel(Object model) { // this.model = model; // } // // @Override // public Object getModel() { // return model; // } // // @Override // public void setViewModelName(String name) { // this.name = name; // } // // @Override // public String getViewModelName() { // return name; // } // }
import android.util.Log; import com.example.dev_wang.databindingdemo.Module.Login.Callback.RequestCallback; import com.example.dev_wang.databindingdemo.Module.Login.Model.RunsUserInfo; import com.example.puremvc_appfacade.Runs.ViewModel;
package com.example.dev_wang.databindingdemo.Module.Login.ViewModel; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserLoginViewModel extends ViewModel { @Override public void setModel(Object model) { super.setModel(model); } @Override public void initializeViewModel() { super.initializeViewModel(); }
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Callback/RequestCallback.java // public interface RequestCallback<T> { // void success(T response); // void error(Error err); // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Model/RunsUserInfo.java // public class RunsUserInfo { // // private String name; // private int age; // private int sex; // // public int getSex() { // return sex; // } // // public void setSex(int sex) { // this.sex = sex; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/ViewModel.java // public class ViewModel implements IViewModel { // protected String TAG = this.getClass().getName(); // private Object model = null; // private String name = null; // // @Override // public void initializeViewModel() { // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setModel(Object model) { // this.model = model; // } // // @Override // public Object getModel() { // return model; // } // // @Override // public void setViewModelName(String name) { // this.name = name; // } // // @Override // public String getViewModelName() { // return name; // } // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/ViewModel/RunsUserLoginViewModel.java import android.util.Log; import com.example.dev_wang.databindingdemo.Module.Login.Callback.RequestCallback; import com.example.dev_wang.databindingdemo.Module.Login.Model.RunsUserInfo; import com.example.puremvc_appfacade.Runs.ViewModel; package com.example.dev_wang.databindingdemo.Module.Login.ViewModel; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserLoginViewModel extends ViewModel { @Override public void setModel(Object model) { super.setModel(model); } @Override public void initializeViewModel() { super.initializeViewModel(); }
public void requestHttpInfo(String parameters, RequestCallback<RunsUserInfo> callback) {
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/ViewModel/RunsUserLoginViewModel.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Callback/RequestCallback.java // public interface RequestCallback<T> { // void success(T response); // void error(Error err); // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Model/RunsUserInfo.java // public class RunsUserInfo { // // private String name; // private int age; // private int sex; // // public int getSex() { // return sex; // } // // public void setSex(int sex) { // this.sex = sex; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/ViewModel.java // public class ViewModel implements IViewModel { // protected String TAG = this.getClass().getName(); // private Object model = null; // private String name = null; // // @Override // public void initializeViewModel() { // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setModel(Object model) { // this.model = model; // } // // @Override // public Object getModel() { // return model; // } // // @Override // public void setViewModelName(String name) { // this.name = name; // } // // @Override // public String getViewModelName() { // return name; // } // }
import android.util.Log; import com.example.dev_wang.databindingdemo.Module.Login.Callback.RequestCallback; import com.example.dev_wang.databindingdemo.Module.Login.Model.RunsUserInfo; import com.example.puremvc_appfacade.Runs.ViewModel;
package com.example.dev_wang.databindingdemo.Module.Login.ViewModel; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserLoginViewModel extends ViewModel { @Override public void setModel(Object model) { super.setModel(model); } @Override public void initializeViewModel() { super.initializeViewModel(); }
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Callback/RequestCallback.java // public interface RequestCallback<T> { // void success(T response); // void error(Error err); // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Model/RunsUserInfo.java // public class RunsUserInfo { // // private String name; // private int age; // private int sex; // // public int getSex() { // return sex; // } // // public void setSex(int sex) { // this.sex = sex; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/ViewModel.java // public class ViewModel implements IViewModel { // protected String TAG = this.getClass().getName(); // private Object model = null; // private String name = null; // // @Override // public void initializeViewModel() { // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setModel(Object model) { // this.model = model; // } // // @Override // public Object getModel() { // return model; // } // // @Override // public void setViewModelName(String name) { // this.name = name; // } // // @Override // public String getViewModelName() { // return name; // } // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/ViewModel/RunsUserLoginViewModel.java import android.util.Log; import com.example.dev_wang.databindingdemo.Module.Login.Callback.RequestCallback; import com.example.dev_wang.databindingdemo.Module.Login.Model.RunsUserInfo; import com.example.puremvc_appfacade.Runs.ViewModel; package com.example.dev_wang.databindingdemo.Module.Login.ViewModel; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserLoginViewModel extends ViewModel { @Override public void setModel(Object model) { super.setModel(model); } @Override public void initializeViewModel() { super.initializeViewModel(); }
public void requestHttpInfo(String parameters, RequestCallback<RunsUserInfo> callback) {
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // }
import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView;
package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/23. */ public class View implements IView{ protected String TAG = Controller.class.getName();
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView; package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/23. */ public class View implements IView{ protected String TAG = Controller.class.getName();
private HashMap<String, IMediator> iMediatorMap = new HashMap<>();
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // }
import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView;
package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/23. */ public class View implements IView{ protected String TAG = Controller.class.getName(); private HashMap<String, IMediator> iMediatorMap = new HashMap<>();
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView; package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/23. */ public class View implements IView{ protected String TAG = Controller.class.getName(); private HashMap<String, IMediator> iMediatorMap = new HashMap<>();
private HashMap<String, ArrayList<IObserver>> iObserverMap = new HashMap<>();
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // }
import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView;
package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/23. */ public class View implements IView{ protected String TAG = Controller.class.getName(); private HashMap<String, IMediator> iMediatorMap = new HashMap<>(); private HashMap<String, ArrayList<IObserver>> iObserverMap = new HashMap<>(); @Override
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView; package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/23. */ public class View implements IView{ protected String TAG = Controller.class.getName(); private HashMap<String, IMediator> iMediatorMap = new HashMap<>(); private HashMap<String, ArrayList<IObserver>> iObserverMap = new HashMap<>(); @Override
public void notifyObservers(INotification notification) {
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // }
import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView;
@Override public void registerMediator(String key, Class cls) { if (null == key || cls == null) { Log.e(TAG, "Register mediator with " + key +" failed" + " class: " + cls); return; } if (hasMediator(key)) { Log.e(TAG, "The mediator has already existed"); return; } IMediator mediator; try { mediator = (IMediator)cls.newInstance(); mediator.setMediatorName(key); iMediatorMap.put(key, mediator); } catch (Exception ex) { Log.e(TAG, "Exception : Register mediator with " + key + " failed"); return; } String notificationList[] = mediator.listNotificationInterests(); if (notificationList.length <= 0) { return; } try { Method method = cls.getMethod(mediator.Method_Name, INotification.class);
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java // public class Observer implements IObserver{ // private String Tag = this.getClass().getName(); // // private Method method = null; // private Object context = null; // // public static IObserver withNotifyMethod(Method method, Object context) { // return new Observer(method, context); // } // // public Observer(Method method, Object context) { // this.method = method; // this.context = context; // } // // @Override // public boolean comparedNotifyContext(Object context) { // return this.context.equals(context); // } // // @Override // public void setNotifyContext(Object context) { // this.context = context; // } // // @Override // public void setNotifyMethod(Method method) { // this.method = method; // } // // @Override // public void notifyObserver(INotification notification) { // if (null == context) { // Log.e(Tag, "Notify observer failed content is null"); // return; // } // // if (null == method) { // Log.e(Tag, "Notify observer failed method is null"); // return; // } // // if (null == notification) { // Log.e(Tag, "Notify observer failed notification is null"); // return; // } // try { // method.invoke(context, notification); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java // public interface IView { // void registerMediator(String key, Class cls); // void removeMediator(String key); // // IMediator getMediator(String key); // boolean hasMediator(String key); // // void notifyObservers(INotification notification); // void registerObserver(IObserver observer, String notificationName); // void removeObserver(Object context, String notificationName); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/View.java import android.util.Log; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.observer.Observer; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; import com.example.puremvc_appfacade.Runs.protocol.IView; @Override public void registerMediator(String key, Class cls) { if (null == key || cls == null) { Log.e(TAG, "Register mediator with " + key +" failed" + " class: " + cls); return; } if (hasMediator(key)) { Log.e(TAG, "The mediator has already existed"); return; } IMediator mediator; try { mediator = (IMediator)cls.newInstance(); mediator.setMediatorName(key); iMediatorMap.put(key, mediator); } catch (Exception ex) { Log.e(TAG, "Exception : Register mediator with " + key + " failed"); return; } String notificationList[] = mediator.listNotificationInterests(); if (notificationList.length <= 0) { return; } try { Method method = cls.getMethod(mediator.Method_Name, INotification.class);
IObserver observer = Observer.withNotifyMethod(method, mediator);
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Controller.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IController.java // public interface IController { // void registerAllModules(); // void unRegisterAllModules(); // // void addOnceModuleClass(Class moduleClass); // void removeModule(String moduleName); // IModule getModule(String moduleName); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IModule.java // public interface IModule { // void onRegister(); // void onRemove(); // // void setModuleName(String name); // String getModuleName(); // }
import android.util.Log; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.protocol.IController; import com.example.puremvc_appfacade.Runs.protocol.IModule;
package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/24. */ public class Controller implements IController { protected String TAG = Controller.class.getName();
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IController.java // public interface IController { // void registerAllModules(); // void unRegisterAllModules(); // // void addOnceModuleClass(Class moduleClass); // void removeModule(String moduleName); // IModule getModule(String moduleName); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IModule.java // public interface IModule { // void onRegister(); // void onRemove(); // // void setModuleName(String name); // String getModuleName(); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Controller.java import android.util.Log; import java.util.HashMap; import com.example.puremvc_appfacade.Runs.protocol.IController; import com.example.puremvc_appfacade.Runs.protocol.IModule; package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/24. */ public class Controller implements IController { protected String TAG = Controller.class.getName();
public HashMap<String, IModule> moduleHashMap = new HashMap<>();
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Activity/RunsUserRegisterActivity.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Facade.java // public enum Facade implements IFacade { // INSTANCE; // private IView iView = new View(); // private IModel iModel = new Model(); // private IController iController = null; // // @Override // public void init(IController controller) { // this.iController = controller; // this.registerAllModules(); // } // // @Override // public void notifyObservers(INotification notification) { // iView.notifyObservers(notification); // } // // @Override // public void sendNotification(String name) { // sendNotification(name, null, null); // } // // @Override // public void sendNotification(String name, Object body) { // sendNotification(name, body, null); // } // // @Override // public void sendNotification(String name, String type) { // sendNotification(name, null, type); // } // // @Override // public void sendNotification(String name, Object body, String type) { // this.notifyObservers(Notification.init(name, body, type)); // } // // @Override // public void registerMediatorWithName(String name, Class cls) { // iView.registerMediator(name, cls); // } // // @Override // public void removeMediatorWithName(String name) { // iView.removeMediator(name); // } // // @Override // public void registerViewModelWithName(String name, Class cls) { // iModel.registerViewModel(name, cls); // } // // @Override // public void removeViewModelWithName(String name) { // iModel.removeViewModel(name); // } // // @Override // public IMediator getMediatorWithName(String name) { // return iView.getMediator(name); // } // // @Override // public IViewModel getViewModelWithName(String name) { // return iModel.getViewModel(name); // } // // @Override // public boolean hasMediator(String name) { // return iView.hasMediator(name); // } // // @Override // public boolean hasViewModel(String name) { // return iModel.hasViewModel(name); // } // // @Override // public void registerAllModules() { // iController.registerAllModules(); // } // // @Override // public void unRegisterAllModules() { // iController.unRegisterAllModules(); // } // // @Override // public IModule getModule(String moduleName) { // return iController.getModule(moduleName); // } // // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.example.dev_wang.databindingdemo.R; import com.example.dev_wang.databindingdemo.databinding.ActivityRegisterBinding; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Facade;
package com.example.dev_wang.databindingdemo.Module.Login.Activity; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterActivity extends AppCompatActivity { private ActivityRegisterBinding activityRegisterBinding = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.activityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register);
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Facade.java // public enum Facade implements IFacade { // INSTANCE; // private IView iView = new View(); // private IModel iModel = new Model(); // private IController iController = null; // // @Override // public void init(IController controller) { // this.iController = controller; // this.registerAllModules(); // } // // @Override // public void notifyObservers(INotification notification) { // iView.notifyObservers(notification); // } // // @Override // public void sendNotification(String name) { // sendNotification(name, null, null); // } // // @Override // public void sendNotification(String name, Object body) { // sendNotification(name, body, null); // } // // @Override // public void sendNotification(String name, String type) { // sendNotification(name, null, type); // } // // @Override // public void sendNotification(String name, Object body, String type) { // this.notifyObservers(Notification.init(name, body, type)); // } // // @Override // public void registerMediatorWithName(String name, Class cls) { // iView.registerMediator(name, cls); // } // // @Override // public void removeMediatorWithName(String name) { // iView.removeMediator(name); // } // // @Override // public void registerViewModelWithName(String name, Class cls) { // iModel.registerViewModel(name, cls); // } // // @Override // public void removeViewModelWithName(String name) { // iModel.removeViewModel(name); // } // // @Override // public IMediator getMediatorWithName(String name) { // return iView.getMediator(name); // } // // @Override // public IViewModel getViewModelWithName(String name) { // return iModel.getViewModel(name); // } // // @Override // public boolean hasMediator(String name) { // return iView.hasMediator(name); // } // // @Override // public boolean hasViewModel(String name) { // return iModel.hasViewModel(name); // } // // @Override // public void registerAllModules() { // iController.registerAllModules(); // } // // @Override // public void unRegisterAllModules() { // iController.unRegisterAllModules(); // } // // @Override // public IModule getModule(String moduleName) { // return iController.getModule(moduleName); // } // // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Activity/RunsUserRegisterActivity.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.example.dev_wang.databindingdemo.R; import com.example.dev_wang.databindingdemo.databinding.ActivityRegisterBinding; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Facade; package com.example.dev_wang.databindingdemo.Module.Login.Activity; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterActivity extends AppCompatActivity { private ActivityRegisterBinding activityRegisterBinding = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.activityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register);
Facade.INSTANCE.sendNotification(Runs.BIND_REGISTER_COMPONENT, this);
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Activity/RunsUserRegisterActivity.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Facade.java // public enum Facade implements IFacade { // INSTANCE; // private IView iView = new View(); // private IModel iModel = new Model(); // private IController iController = null; // // @Override // public void init(IController controller) { // this.iController = controller; // this.registerAllModules(); // } // // @Override // public void notifyObservers(INotification notification) { // iView.notifyObservers(notification); // } // // @Override // public void sendNotification(String name) { // sendNotification(name, null, null); // } // // @Override // public void sendNotification(String name, Object body) { // sendNotification(name, body, null); // } // // @Override // public void sendNotification(String name, String type) { // sendNotification(name, null, type); // } // // @Override // public void sendNotification(String name, Object body, String type) { // this.notifyObservers(Notification.init(name, body, type)); // } // // @Override // public void registerMediatorWithName(String name, Class cls) { // iView.registerMediator(name, cls); // } // // @Override // public void removeMediatorWithName(String name) { // iView.removeMediator(name); // } // // @Override // public void registerViewModelWithName(String name, Class cls) { // iModel.registerViewModel(name, cls); // } // // @Override // public void removeViewModelWithName(String name) { // iModel.removeViewModel(name); // } // // @Override // public IMediator getMediatorWithName(String name) { // return iView.getMediator(name); // } // // @Override // public IViewModel getViewModelWithName(String name) { // return iModel.getViewModel(name); // } // // @Override // public boolean hasMediator(String name) { // return iView.hasMediator(name); // } // // @Override // public boolean hasViewModel(String name) { // return iModel.hasViewModel(name); // } // // @Override // public void registerAllModules() { // iController.registerAllModules(); // } // // @Override // public void unRegisterAllModules() { // iController.unRegisterAllModules(); // } // // @Override // public IModule getModule(String moduleName) { // return iController.getModule(moduleName); // } // // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.example.dev_wang.databindingdemo.R; import com.example.dev_wang.databindingdemo.databinding.ActivityRegisterBinding; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Facade;
package com.example.dev_wang.databindingdemo.Module.Login.Activity; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterActivity extends AppCompatActivity { private ActivityRegisterBinding activityRegisterBinding = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.activityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register);
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Facade.java // public enum Facade implements IFacade { // INSTANCE; // private IView iView = new View(); // private IModel iModel = new Model(); // private IController iController = null; // // @Override // public void init(IController controller) { // this.iController = controller; // this.registerAllModules(); // } // // @Override // public void notifyObservers(INotification notification) { // iView.notifyObservers(notification); // } // // @Override // public void sendNotification(String name) { // sendNotification(name, null, null); // } // // @Override // public void sendNotification(String name, Object body) { // sendNotification(name, body, null); // } // // @Override // public void sendNotification(String name, String type) { // sendNotification(name, null, type); // } // // @Override // public void sendNotification(String name, Object body, String type) { // this.notifyObservers(Notification.init(name, body, type)); // } // // @Override // public void registerMediatorWithName(String name, Class cls) { // iView.registerMediator(name, cls); // } // // @Override // public void removeMediatorWithName(String name) { // iView.removeMediator(name); // } // // @Override // public void registerViewModelWithName(String name, Class cls) { // iModel.registerViewModel(name, cls); // } // // @Override // public void removeViewModelWithName(String name) { // iModel.removeViewModel(name); // } // // @Override // public IMediator getMediatorWithName(String name) { // return iView.getMediator(name); // } // // @Override // public IViewModel getViewModelWithName(String name) { // return iModel.getViewModel(name); // } // // @Override // public boolean hasMediator(String name) { // return iView.hasMediator(name); // } // // @Override // public boolean hasViewModel(String name) { // return iModel.hasViewModel(name); // } // // @Override // public void registerAllModules() { // iController.registerAllModules(); // } // // @Override // public void unRegisterAllModules() { // iController.unRegisterAllModules(); // } // // @Override // public IModule getModule(String moduleName) { // return iController.getModule(moduleName); // } // // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Activity/RunsUserRegisterActivity.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.example.dev_wang.databindingdemo.R; import com.example.dev_wang.databindingdemo.databinding.ActivityRegisterBinding; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Facade; package com.example.dev_wang.databindingdemo.Module.Login.Activity; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterActivity extends AppCompatActivity { private ActivityRegisterBinding activityRegisterBinding = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.activityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register);
Facade.INSTANCE.sendNotification(Runs.BIND_REGISTER_COMPONENT, this);
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/AppModuleController.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Home/RunsHomePageModule.java // public class RunsHomePageModule extends Module { // @Override // public void onRegister() { // // } // // @Override // public void onRemove() { // // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/RunsUserLoginModule.java // public class RunsUserLoginModule extends Module { // // @Override // public void onRegister() { // // this.registerMediatorClass(RunsUserLoginMediator.class); // this.registerMediatorClass(RunsUserRegisterMediator.class); // // // this.registerViewModelClass(RunsUserLoginViewModel.class); // } // // @Override // public void onRemove() { // this.removeAllMediator(); // this.removeAllViewModel(); // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Controller.java // public class Controller implements IController { // protected String TAG = Controller.class.getName(); // // public HashMap<String, IModule> moduleHashMap = new HashMap<>(); // // @Override // public void registerAllModules() { // // will override by sub class // } // // @Override // public void unRegisterAllModules() { // // will override by sub class // } // // @Override // public void addOnceModuleClass(Class moduleClass) { // String name = moduleClass.getName(); // if (moduleHashMap.containsKey(name)){ // return; // } // // IModule module; // try { // module = (IModule)moduleClass.newInstance(); // module.setModuleName(name); // moduleHashMap.put(name, module); // module.onRegister(); // }catch (Exception ex) { // ex.printStackTrace(); // } // Log.i(TAG, "注册 module :" + name ); // } // // @Override // public void removeModule(String moduleName) { // moduleHashMap.remove(moduleName); // } // // @Override // public IModule getModule(String moduleName) { // return moduleHashMap.get(moduleName); // } // // }
import com.example.dev_wang.databindingdemo.Module.Home.RunsHomePageModule; import com.example.dev_wang.databindingdemo.Module.Login.RunsUserLoginModule; import com.example.puremvc_appfacade.Runs.core.Controller;
package com.example.dev_wang.databindingdemo.Module.AppFacade; /** * Created by dev_wang on 2017/1/24. */ public class AppModuleController extends Controller { @Override public void registerAllModules() { super.registerAllModules();
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Home/RunsHomePageModule.java // public class RunsHomePageModule extends Module { // @Override // public void onRegister() { // // } // // @Override // public void onRemove() { // // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/RunsUserLoginModule.java // public class RunsUserLoginModule extends Module { // // @Override // public void onRegister() { // // this.registerMediatorClass(RunsUserLoginMediator.class); // this.registerMediatorClass(RunsUserRegisterMediator.class); // // // this.registerViewModelClass(RunsUserLoginViewModel.class); // } // // @Override // public void onRemove() { // this.removeAllMediator(); // this.removeAllViewModel(); // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Controller.java // public class Controller implements IController { // protected String TAG = Controller.class.getName(); // // public HashMap<String, IModule> moduleHashMap = new HashMap<>(); // // @Override // public void registerAllModules() { // // will override by sub class // } // // @Override // public void unRegisterAllModules() { // // will override by sub class // } // // @Override // public void addOnceModuleClass(Class moduleClass) { // String name = moduleClass.getName(); // if (moduleHashMap.containsKey(name)){ // return; // } // // IModule module; // try { // module = (IModule)moduleClass.newInstance(); // module.setModuleName(name); // moduleHashMap.put(name, module); // module.onRegister(); // }catch (Exception ex) { // ex.printStackTrace(); // } // Log.i(TAG, "注册 module :" + name ); // } // // @Override // public void removeModule(String moduleName) { // moduleHashMap.remove(moduleName); // } // // @Override // public IModule getModule(String moduleName) { // return moduleHashMap.get(moduleName); // } // // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/AppModuleController.java import com.example.dev_wang.databindingdemo.Module.Home.RunsHomePageModule; import com.example.dev_wang.databindingdemo.Module.Login.RunsUserLoginModule; import com.example.puremvc_appfacade.Runs.core.Controller; package com.example.dev_wang.databindingdemo.Module.AppFacade; /** * Created by dev_wang on 2017/1/24. */ public class AppModuleController extends Controller { @Override public void registerAllModules() { super.registerAllModules();
this.addOnceModuleClass(RunsUserLoginModule.class);
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/AppModuleController.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Home/RunsHomePageModule.java // public class RunsHomePageModule extends Module { // @Override // public void onRegister() { // // } // // @Override // public void onRemove() { // // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/RunsUserLoginModule.java // public class RunsUserLoginModule extends Module { // // @Override // public void onRegister() { // // this.registerMediatorClass(RunsUserLoginMediator.class); // this.registerMediatorClass(RunsUserRegisterMediator.class); // // // this.registerViewModelClass(RunsUserLoginViewModel.class); // } // // @Override // public void onRemove() { // this.removeAllMediator(); // this.removeAllViewModel(); // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Controller.java // public class Controller implements IController { // protected String TAG = Controller.class.getName(); // // public HashMap<String, IModule> moduleHashMap = new HashMap<>(); // // @Override // public void registerAllModules() { // // will override by sub class // } // // @Override // public void unRegisterAllModules() { // // will override by sub class // } // // @Override // public void addOnceModuleClass(Class moduleClass) { // String name = moduleClass.getName(); // if (moduleHashMap.containsKey(name)){ // return; // } // // IModule module; // try { // module = (IModule)moduleClass.newInstance(); // module.setModuleName(name); // moduleHashMap.put(name, module); // module.onRegister(); // }catch (Exception ex) { // ex.printStackTrace(); // } // Log.i(TAG, "注册 module :" + name ); // } // // @Override // public void removeModule(String moduleName) { // moduleHashMap.remove(moduleName); // } // // @Override // public IModule getModule(String moduleName) { // return moduleHashMap.get(moduleName); // } // // }
import com.example.dev_wang.databindingdemo.Module.Home.RunsHomePageModule; import com.example.dev_wang.databindingdemo.Module.Login.RunsUserLoginModule; import com.example.puremvc_appfacade.Runs.core.Controller;
package com.example.dev_wang.databindingdemo.Module.AppFacade; /** * Created by dev_wang on 2017/1/24. */ public class AppModuleController extends Controller { @Override public void registerAllModules() { super.registerAllModules(); this.addOnceModuleClass(RunsUserLoginModule.class);
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Home/RunsHomePageModule.java // public class RunsHomePageModule extends Module { // @Override // public void onRegister() { // // } // // @Override // public void onRemove() { // // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/RunsUserLoginModule.java // public class RunsUserLoginModule extends Module { // // @Override // public void onRegister() { // // this.registerMediatorClass(RunsUserLoginMediator.class); // this.registerMediatorClass(RunsUserRegisterMediator.class); // // // this.registerViewModelClass(RunsUserLoginViewModel.class); // } // // @Override // public void onRemove() { // this.removeAllMediator(); // this.removeAllViewModel(); // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Controller.java // public class Controller implements IController { // protected String TAG = Controller.class.getName(); // // public HashMap<String, IModule> moduleHashMap = new HashMap<>(); // // @Override // public void registerAllModules() { // // will override by sub class // } // // @Override // public void unRegisterAllModules() { // // will override by sub class // } // // @Override // public void addOnceModuleClass(Class moduleClass) { // String name = moduleClass.getName(); // if (moduleHashMap.containsKey(name)){ // return; // } // // IModule module; // try { // module = (IModule)moduleClass.newInstance(); // module.setModuleName(name); // moduleHashMap.put(name, module); // module.onRegister(); // }catch (Exception ex) { // ex.printStackTrace(); // } // Log.i(TAG, "注册 module :" + name ); // } // // @Override // public void removeModule(String moduleName) { // moduleHashMap.remove(moduleName); // } // // @Override // public IModule getModule(String moduleName) { // return moduleHashMap.get(moduleName); // } // // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/AppModuleController.java import com.example.dev_wang.databindingdemo.Module.Home.RunsHomePageModule; import com.example.dev_wang.databindingdemo.Module.Login.RunsUserLoginModule; import com.example.puremvc_appfacade.Runs.core.Controller; package com.example.dev_wang.databindingdemo.Module.AppFacade; /** * Created by dev_wang on 2017/1/24. */ public class AppModuleController extends Controller { @Override public void registerAllModules() { super.registerAllModules(); this.addOnceModuleClass(RunsUserLoginModule.class);
this.addOnceModuleClass(RunsHomePageModule.class);
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // }
import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver;
package com.example.puremvc_appfacade.Runs.observer; /** * Created by dev_wang on 2017/1/23. */ public class Observer implements IObserver{ private String Tag = this.getClass().getName(); private Method method = null; private Object context = null; public static IObserver withNotifyMethod(Method method, Object context) { return new Observer(method, context); } public Observer(Method method, Object context) { this.method = method; this.context = context; } @Override public boolean comparedNotifyContext(Object context) { return this.context.equals(context); } @Override public void setNotifyContext(Object context) { this.context = context; } @Override public void setNotifyMethod(Method method) { this.method = method; } @Override
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IObserver.java // public interface IObserver { // // boolean comparedNotifyContext(Object context); // void setNotifyContext(Object context); // void notifyObserver(INotification notification); // void setNotifyMethod(Method method); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Observer.java import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.example.puremvc_appfacade.Runs.protocol.INotification; import com.example.puremvc_appfacade.Runs.protocol.IObserver; package com.example.puremvc_appfacade.Runs.observer; /** * Created by dev_wang on 2017/1/23. */ public class Observer implements IObserver{ private String Tag = this.getClass().getName(); private Method method = null; private Object context = null; public static IObserver withNotifyMethod(Method method, Object context) { return new Observer(method, context); } public Observer(Method method, Object context) { this.method = method; this.context = context; } @Override public boolean comparedNotifyContext(Object context) { return this.context.equals(context); } @Override public void setNotifyContext(Object context) { this.context = context; } @Override public void setNotifyMethod(Method method) { this.method = method; } @Override
public void notifyObserver(INotification notification) {
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // }
import android.util.Log; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification;
public void onRegister() { // will override by sub class } @Override public void onRemove() { // will override by sub class } @Override public void setViewComponent(Object viewComponent) { this.viewComponent = viewComponent; } @Override public Object getViewComponent() { return this.viewComponent; } @Override public void setMediatorName(String name) { this.mediatorName = name; } @Override public String getMediatorName() { return this.mediatorName; } @Override
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IMediator.java // public interface IMediator { // String Method_Name = "handleNotification"; // // void onRegister(); // void onRemove(); // // void setViewComponent(Object viewComponent); // Object getViewComponent(); // // void setMediatorName(String name); // String getMediatorName(); // // void initializeMediator(); // void handleNotification(INotification notification); // String[] listNotificationInterests(); // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java import android.util.Log; import com.example.puremvc_appfacade.Runs.protocol.IMediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; public void onRegister() { // will override by sub class } @Override public void onRemove() { // will override by sub class } @Override public void setViewComponent(Object viewComponent) { this.viewComponent = viewComponent; } @Override public Object getViewComponent() { return this.viewComponent; } @Override public void setMediatorName(String name) { this.mediatorName = name; } @Override public String getMediatorName() { return this.mediatorName; } @Override
public void handleNotification(INotification notification) {
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Model.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IModel.java // public interface IModel { // void registerViewModel(String key, Class cls); // void removeViewModel(String key); // // IViewModel getViewModel(String key); // boolean hasViewModel(String key); // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IViewModel.java // public interface IViewModel { // void setModel(Object model); // Object getModel(); // // void setViewModelName(String name); // String getViewModelName(); // // void onRegister(); // void onRemove(); // void initializeViewModel(); // }
import com.example.puremvc_appfacade.Runs.protocol.IViewModel; import android.util.Log; import com.example.puremvc_appfacade.Runs.protocol.IModel; import java.util.HashMap;
package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/24. */ public class Model implements IModel { protected String TAG = Controller.class.getName();
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IModel.java // public interface IModel { // void registerViewModel(String key, Class cls); // void removeViewModel(String key); // // IViewModel getViewModel(String key); // boolean hasViewModel(String key); // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IViewModel.java // public interface IViewModel { // void setModel(Object model); // Object getModel(); // // void setViewModelName(String name); // String getViewModelName(); // // void onRegister(); // void onRemove(); // void initializeViewModel(); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/core/Model.java import com.example.puremvc_appfacade.Runs.protocol.IViewModel; import android.util.Log; import com.example.puremvc_appfacade.Runs.protocol.IModel; import java.util.HashMap; package com.example.puremvc_appfacade.Runs.core; /** * Created by dev_wang on 2017/1/24. */ public class Model implements IModel { protected String TAG = Controller.class.getName();
private HashMap<String, IViewModel> iViewModelMap = new HashMap<>();
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Meditaor/RunsUserRegisterMediator.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/MainActivity.java // public class MainActivity extends AppCompatActivity { // private ActivityMainBinding activityMainBinding = null; // // public MainActivity() { // super(); // Facade.INSTANCE.init(new AppModuleController()); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // // final MainActivity that = this; // activityMainBinding.login.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGIN_NOTIFICATION,that); // //上面一句代码等同于下面两行 // // Intent intent = new Intent(MainActivity.this, RunsUserLoginActivity.class); // // startActivity(intent); // } // }); // activityMainBinding.register.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_REGISTER_NOTIFICATION); // } // }); // // activityMainBinding.logout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGOUT_NOTIFICATION); // } // }); // // } // // // // @Override // protected void onDestroy() { // super.onDestroy(); // Facade.INSTANCE.unRegisterAllModules(); // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java // public class Mediator implements IMediator { // protected String TAG = this.getClass().getName(); // private Object viewComponent = null; // private String mediatorName = null; // // @Override // public void initializeMediator() { // Log.i(TAG,"initializeMediator " + this.getClass().getName()); // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setViewComponent(Object viewComponent) { // this.viewComponent = viewComponent; // } // // @Override // public Object getViewComponent() { // return this.viewComponent; // } // // @Override // public void setMediatorName(String name) { // this.mediatorName = name; // } // // @Override // public String getMediatorName() { // return this.mediatorName; // } // // @Override // public void handleNotification(INotification notification) { // // will override by sub class // Log.i(TAG,"handleNotification " + this.getClass().getName()); // } // // @Override // public String[] listNotificationInterests() { // return null; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.dev_wang.databindingdemo.MainActivity; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Mediator; import com.example.puremvc_appfacade.Runs.protocol.INotification;
package com.example.dev_wang.databindingdemo.Module.Login.Meditaor; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterMediator extends Mediator { @Override public void initializeMediator() { super.initializeMediator(); } @Override
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/MainActivity.java // public class MainActivity extends AppCompatActivity { // private ActivityMainBinding activityMainBinding = null; // // public MainActivity() { // super(); // Facade.INSTANCE.init(new AppModuleController()); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // // final MainActivity that = this; // activityMainBinding.login.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGIN_NOTIFICATION,that); // //上面一句代码等同于下面两行 // // Intent intent = new Intent(MainActivity.this, RunsUserLoginActivity.class); // // startActivity(intent); // } // }); // activityMainBinding.register.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_REGISTER_NOTIFICATION); // } // }); // // activityMainBinding.logout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGOUT_NOTIFICATION); // } // }); // // } // // // // @Override // protected void onDestroy() { // super.onDestroy(); // Facade.INSTANCE.unRegisterAllModules(); // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java // public class Mediator implements IMediator { // protected String TAG = this.getClass().getName(); // private Object viewComponent = null; // private String mediatorName = null; // // @Override // public void initializeMediator() { // Log.i(TAG,"initializeMediator " + this.getClass().getName()); // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setViewComponent(Object viewComponent) { // this.viewComponent = viewComponent; // } // // @Override // public Object getViewComponent() { // return this.viewComponent; // } // // @Override // public void setMediatorName(String name) { // this.mediatorName = name; // } // // @Override // public String getMediatorName() { // return this.mediatorName; // } // // @Override // public void handleNotification(INotification notification) { // // will override by sub class // Log.i(TAG,"handleNotification " + this.getClass().getName()); // } // // @Override // public String[] listNotificationInterests() { // return null; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Meditaor/RunsUserRegisterMediator.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.dev_wang.databindingdemo.MainActivity; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Mediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; package com.example.dev_wang.databindingdemo.Module.Login.Meditaor; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterMediator extends Mediator { @Override public void initializeMediator() { super.initializeMediator(); } @Override
public void handleNotification(INotification notification) {
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Meditaor/RunsUserRegisterMediator.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/MainActivity.java // public class MainActivity extends AppCompatActivity { // private ActivityMainBinding activityMainBinding = null; // // public MainActivity() { // super(); // Facade.INSTANCE.init(new AppModuleController()); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // // final MainActivity that = this; // activityMainBinding.login.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGIN_NOTIFICATION,that); // //上面一句代码等同于下面两行 // // Intent intent = new Intent(MainActivity.this, RunsUserLoginActivity.class); // // startActivity(intent); // } // }); // activityMainBinding.register.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_REGISTER_NOTIFICATION); // } // }); // // activityMainBinding.logout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGOUT_NOTIFICATION); // } // }); // // } // // // // @Override // protected void onDestroy() { // super.onDestroy(); // Facade.INSTANCE.unRegisterAllModules(); // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java // public class Mediator implements IMediator { // protected String TAG = this.getClass().getName(); // private Object viewComponent = null; // private String mediatorName = null; // // @Override // public void initializeMediator() { // Log.i(TAG,"initializeMediator " + this.getClass().getName()); // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setViewComponent(Object viewComponent) { // this.viewComponent = viewComponent; // } // // @Override // public Object getViewComponent() { // return this.viewComponent; // } // // @Override // public void setMediatorName(String name) { // this.mediatorName = name; // } // // @Override // public String getMediatorName() { // return this.mediatorName; // } // // @Override // public void handleNotification(INotification notification) { // // will override by sub class // Log.i(TAG,"handleNotification " + this.getClass().getName()); // } // // @Override // public String[] listNotificationInterests() { // return null; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.dev_wang.databindingdemo.MainActivity; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Mediator; import com.example.puremvc_appfacade.Runs.protocol.INotification;
package com.example.dev_wang.databindingdemo.Module.Login.Meditaor; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterMediator extends Mediator { @Override public void initializeMediator() { super.initializeMediator(); } @Override public void handleNotification(INotification notification) { super.handleNotification(notification); String notificationName = notification.getName();
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/MainActivity.java // public class MainActivity extends AppCompatActivity { // private ActivityMainBinding activityMainBinding = null; // // public MainActivity() { // super(); // Facade.INSTANCE.init(new AppModuleController()); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // // final MainActivity that = this; // activityMainBinding.login.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGIN_NOTIFICATION,that); // //上面一句代码等同于下面两行 // // Intent intent = new Intent(MainActivity.this, RunsUserLoginActivity.class); // // startActivity(intent); // } // }); // activityMainBinding.register.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_REGISTER_NOTIFICATION); // } // }); // // activityMainBinding.logout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGOUT_NOTIFICATION); // } // }); // // } // // // // @Override // protected void onDestroy() { // super.onDestroy(); // Facade.INSTANCE.unRegisterAllModules(); // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java // public class Mediator implements IMediator { // protected String TAG = this.getClass().getName(); // private Object viewComponent = null; // private String mediatorName = null; // // @Override // public void initializeMediator() { // Log.i(TAG,"initializeMediator " + this.getClass().getName()); // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setViewComponent(Object viewComponent) { // this.viewComponent = viewComponent; // } // // @Override // public Object getViewComponent() { // return this.viewComponent; // } // // @Override // public void setMediatorName(String name) { // this.mediatorName = name; // } // // @Override // public String getMediatorName() { // return this.mediatorName; // } // // @Override // public void handleNotification(INotification notification) { // // will override by sub class // Log.i(TAG,"handleNotification " + this.getClass().getName()); // } // // @Override // public String[] listNotificationInterests() { // return null; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Meditaor/RunsUserRegisterMediator.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.dev_wang.databindingdemo.MainActivity; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Mediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; package com.example.dev_wang.databindingdemo.Module.Login.Meditaor; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterMediator extends Mediator { @Override public void initializeMediator() { super.initializeMediator(); } @Override public void handleNotification(INotification notification) { super.handleNotification(notification); String notificationName = notification.getName();
if (notificationName.equals(Runs.BIND_REGISTER_COMPONENT)) {
RunsCode/AppFacadeMVC
app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Meditaor/RunsUserRegisterMediator.java
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/MainActivity.java // public class MainActivity extends AppCompatActivity { // private ActivityMainBinding activityMainBinding = null; // // public MainActivity() { // super(); // Facade.INSTANCE.init(new AppModuleController()); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // // final MainActivity that = this; // activityMainBinding.login.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGIN_NOTIFICATION,that); // //上面一句代码等同于下面两行 // // Intent intent = new Intent(MainActivity.this, RunsUserLoginActivity.class); // // startActivity(intent); // } // }); // activityMainBinding.register.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_REGISTER_NOTIFICATION); // } // }); // // activityMainBinding.logout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGOUT_NOTIFICATION); // } // }); // // } // // // // @Override // protected void onDestroy() { // super.onDestroy(); // Facade.INSTANCE.unRegisterAllModules(); // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java // public class Mediator implements IMediator { // protected String TAG = this.getClass().getName(); // private Object viewComponent = null; // private String mediatorName = null; // // @Override // public void initializeMediator() { // Log.i(TAG,"initializeMediator " + this.getClass().getName()); // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setViewComponent(Object viewComponent) { // this.viewComponent = viewComponent; // } // // @Override // public Object getViewComponent() { // return this.viewComponent; // } // // @Override // public void setMediatorName(String name) { // this.mediatorName = name; // } // // @Override // public String getMediatorName() { // return this.mediatorName; // } // // @Override // public void handleNotification(INotification notification) { // // will override by sub class // Log.i(TAG,"handleNotification " + this.getClass().getName()); // } // // @Override // public String[] listNotificationInterests() { // return null; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.dev_wang.databindingdemo.MainActivity; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Mediator; import com.example.puremvc_appfacade.Runs.protocol.INotification;
package com.example.dev_wang.databindingdemo.Module.Login.Meditaor; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterMediator extends Mediator { @Override public void initializeMediator() { super.initializeMediator(); } @Override public void handleNotification(INotification notification) { super.handleNotification(notification); String notificationName = notification.getName(); if (notificationName.equals(Runs.BIND_REGISTER_COMPONENT)) { Object object = notification.getObject(); if (null != object) { this.setViewComponent(object); Toast.makeText((Context)object, Runs.BIND_REGISTER_COMPONENT, Toast.LENGTH_SHORT).show(); } return; } if (notificationName.equals(Runs.USER_REGISTER_DONE_NOTIFICATION)) { Activity activity = (Activity)(this.getViewComponent());
// Path: app/src/main/java/com/example/dev_wang/databindingdemo/MainActivity.java // public class MainActivity extends AppCompatActivity { // private ActivityMainBinding activityMainBinding = null; // // public MainActivity() { // super(); // Facade.INSTANCE.init(new AppModuleController()); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // // final MainActivity that = this; // activityMainBinding.login.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGIN_NOTIFICATION,that); // //上面一句代码等同于下面两行 // // Intent intent = new Intent(MainActivity.this, RunsUserLoginActivity.class); // // startActivity(intent); // } // }); // activityMainBinding.register.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_REGISTER_NOTIFICATION); // } // }); // // activityMainBinding.logout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facade.INSTANCE.sendNotification(Runs.USER_LOGOUT_NOTIFICATION); // } // }); // // } // // // // @Override // protected void onDestroy() { // super.onDestroy(); // Facade.INSTANCE.unRegisterAllModules(); // } // } // // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/AppFacade/Runs.java // public abstract class Runs { // // //RunsUserLoginMediator // public static final String BIND_VIEW_COMPONENT = "BIND_VIEW_COMPONENT"; // public static final String UNBUNDLED_VIEW_COMPONENT = "UNBUNDLED_VIEW_COMPONENT"; // public static final String USER_LOGIN_NOTIFICATION = "USER_LOGIN_NOTIFICATION"; // public static final String USER_LOGOUT_NOTIFICATION = "USER_LOGOUT_NOTIFICATION"; // public static final String USER_REGISTER_NOTIFICATION = "USER_REGISTER_NOTIFICATION"; // // //RunsUserRegisterMediatorUNLOCK // public static final String BIND_REGISTER_COMPONENT = "BIND_REGISTER_COMPONENT"; // public static final String USER_BIND_PHONE_NOTIFICATION = "USER_BIND_PHONE_NOTIFICATION"; // public static final String USER_REGISTER_DONE_NOTIFICATION = "USER_REGISTER_DONE_NOTIFICATION"; // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Mediator.java // public class Mediator implements IMediator { // protected String TAG = this.getClass().getName(); // private Object viewComponent = null; // private String mediatorName = null; // // @Override // public void initializeMediator() { // Log.i(TAG,"initializeMediator " + this.getClass().getName()); // // will override by sub class // } // // @Override // public void onRegister() { // // will override by sub class // } // // @Override // public void onRemove() { // // will override by sub class // } // // @Override // public void setViewComponent(Object viewComponent) { // this.viewComponent = viewComponent; // } // // @Override // public Object getViewComponent() { // return this.viewComponent; // } // // @Override // public void setMediatorName(String name) { // this.mediatorName = name; // } // // @Override // public String getMediatorName() { // return this.mediatorName; // } // // @Override // public void handleNotification(INotification notification) { // // will override by sub class // Log.i(TAG,"handleNotification " + this.getClass().getName()); // } // // @Override // public String[] listNotificationInterests() { // return null; // } // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotification.java // public interface INotification { // // void setName(String name); // String getName(); // // void setObject(Object object); // Object getObject(); // // void setType(String type); // String getType(); // } // Path: app/src/main/java/com/example/dev_wang/databindingdemo/Module/Login/Meditaor/RunsUserRegisterMediator.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.example.dev_wang.databindingdemo.MainActivity; import com.example.dev_wang.databindingdemo.Module.AppFacade.Runs; import com.example.puremvc_appfacade.Runs.Mediator; import com.example.puremvc_appfacade.Runs.protocol.INotification; package com.example.dev_wang.databindingdemo.Module.Login.Meditaor; /** * Created by dev_wang on 2017/1/24. */ public class RunsUserRegisterMediator extends Mediator { @Override public void initializeMediator() { super.initializeMediator(); } @Override public void handleNotification(INotification notification) { super.handleNotification(notification); String notificationName = notification.getName(); if (notificationName.equals(Runs.BIND_REGISTER_COMPONENT)) { Object object = notification.getObject(); if (null != object) { this.setViewComponent(object); Toast.makeText((Context)object, Runs.BIND_REGISTER_COMPONENT, Toast.LENGTH_SHORT).show(); } return; } if (notificationName.equals(Runs.USER_REGISTER_DONE_NOTIFICATION)) { Activity activity = (Activity)(this.getViewComponent());
Intent intent = new Intent(activity, MainActivity.class);
RunsCode/AppFacadeMVC
puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Notifier.java
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Facade.java // public enum Facade implements IFacade { // INSTANCE; // private IView iView = new View(); // private IModel iModel = new Model(); // private IController iController = null; // // @Override // public void init(IController controller) { // this.iController = controller; // this.registerAllModules(); // } // // @Override // public void notifyObservers(INotification notification) { // iView.notifyObservers(notification); // } // // @Override // public void sendNotification(String name) { // sendNotification(name, null, null); // } // // @Override // public void sendNotification(String name, Object body) { // sendNotification(name, body, null); // } // // @Override // public void sendNotification(String name, String type) { // sendNotification(name, null, type); // } // // @Override // public void sendNotification(String name, Object body, String type) { // this.notifyObservers(Notification.init(name, body, type)); // } // // @Override // public void registerMediatorWithName(String name, Class cls) { // iView.registerMediator(name, cls); // } // // @Override // public void removeMediatorWithName(String name) { // iView.removeMediator(name); // } // // @Override // public void registerViewModelWithName(String name, Class cls) { // iModel.registerViewModel(name, cls); // } // // @Override // public void removeViewModelWithName(String name) { // iModel.removeViewModel(name); // } // // @Override // public IMediator getMediatorWithName(String name) { // return iView.getMediator(name); // } // // @Override // public IViewModel getViewModelWithName(String name) { // return iModel.getViewModel(name); // } // // @Override // public boolean hasMediator(String name) { // return iView.hasMediator(name); // } // // @Override // public boolean hasViewModel(String name) { // return iModel.hasViewModel(name); // } // // @Override // public void registerAllModules() { // iController.registerAllModules(); // } // // @Override // public void unRegisterAllModules() { // iController.unRegisterAllModules(); // } // // @Override // public IModule getModule(String moduleName) { // return iController.getModule(moduleName); // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotifier.java // public interface INotifier { // void sendNotification(String name); // void sendNotification(String name, Object body); // void sendNotification(String name, String type); // void sendNotification(String name, Object body, String type); // }
import com.example.puremvc_appfacade.Runs.Facade; import com.example.puremvc_appfacade.Runs.protocol.INotifier;
package com.example.puremvc_appfacade.Runs.observer; /** * Created by dev_wang on 2017/1/23. */ public class Notifier implements INotifier { @Override public void sendNotification(String name) { this.sendNotification(name, null, null); } @Override public void sendNotification(String name, Object body) { this.sendNotification(name, body, null); } @Override public void sendNotification(String name, String type) { this.sendNotification(name, null, type); } @Override public void sendNotification(String name, Object body, String type) {
// Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/Facade.java // public enum Facade implements IFacade { // INSTANCE; // private IView iView = new View(); // private IModel iModel = new Model(); // private IController iController = null; // // @Override // public void init(IController controller) { // this.iController = controller; // this.registerAllModules(); // } // // @Override // public void notifyObservers(INotification notification) { // iView.notifyObservers(notification); // } // // @Override // public void sendNotification(String name) { // sendNotification(name, null, null); // } // // @Override // public void sendNotification(String name, Object body) { // sendNotification(name, body, null); // } // // @Override // public void sendNotification(String name, String type) { // sendNotification(name, null, type); // } // // @Override // public void sendNotification(String name, Object body, String type) { // this.notifyObservers(Notification.init(name, body, type)); // } // // @Override // public void registerMediatorWithName(String name, Class cls) { // iView.registerMediator(name, cls); // } // // @Override // public void removeMediatorWithName(String name) { // iView.removeMediator(name); // } // // @Override // public void registerViewModelWithName(String name, Class cls) { // iModel.registerViewModel(name, cls); // } // // @Override // public void removeViewModelWithName(String name) { // iModel.removeViewModel(name); // } // // @Override // public IMediator getMediatorWithName(String name) { // return iView.getMediator(name); // } // // @Override // public IViewModel getViewModelWithName(String name) { // return iModel.getViewModel(name); // } // // @Override // public boolean hasMediator(String name) { // return iView.hasMediator(name); // } // // @Override // public boolean hasViewModel(String name) { // return iModel.hasViewModel(name); // } // // @Override // public void registerAllModules() { // iController.registerAllModules(); // } // // @Override // public void unRegisterAllModules() { // iController.unRegisterAllModules(); // } // // @Override // public IModule getModule(String moduleName) { // return iController.getModule(moduleName); // } // // } // // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/INotifier.java // public interface INotifier { // void sendNotification(String name); // void sendNotification(String name, Object body); // void sendNotification(String name, String type); // void sendNotification(String name, Object body, String type); // } // Path: puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/observer/Notifier.java import com.example.puremvc_appfacade.Runs.Facade; import com.example.puremvc_appfacade.Runs.protocol.INotifier; package com.example.puremvc_appfacade.Runs.observer; /** * Created by dev_wang on 2017/1/23. */ public class Notifier implements INotifier { @Override public void sendNotification(String name) { this.sendNotification(name, null, null); } @Override public void sendNotification(String name, Object body) { this.sendNotification(name, body, null); } @Override public void sendNotification(String name, String type) { this.sendNotification(name, null, type); } @Override public void sendNotification(String name, Object body, String type) {
Facade.INSTANCE.sendNotification(name, body, type);
mokies/ratelimitj
ratelimitj-inmemory/src/main/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentRequestRateLimiter.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentRequestLimiter.java // public interface ConcurrentRequestLimiter { // // Baton acquire(String key); // // Baton acquire(String key, int weight); // // }
import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentRequestLimiter; import net.jodah.expiringmap.ExpiringMap; import java.util.Optional; import java.util.concurrent.Semaphore; import java.util.function.Supplier; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static net.jodah.expiringmap.ExpirationPolicy.ACCESSED;
package es.moki.ratelimitj.inmemory.concurrent; public class InMemoryConcurrentRequestRateLimiter implements ConcurrentRequestLimiter { private final ExpiringMap<String, Semaphore> expiringKeyMap;
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentRequestLimiter.java // public interface ConcurrentRequestLimiter { // // Baton acquire(String key); // // Baton acquire(String key, int weight); // // } // Path: ratelimitj-inmemory/src/main/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentRequestRateLimiter.java import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentRequestLimiter; import net.jodah.expiringmap.ExpiringMap; import java.util.Optional; import java.util.concurrent.Semaphore; import java.util.function.Supplier; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static net.jodah.expiringmap.ExpirationPolicy.ACCESSED; package es.moki.ratelimitj.inmemory.concurrent; public class InMemoryConcurrentRequestRateLimiter implements ConcurrentRequestLimiter { private final ExpiringMap<String, Semaphore> expiringKeyMap;
private final ConcurrentLimitRule rule;
mokies/ratelimitj
ratelimitj-inmemory/src/main/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentRequestRateLimiter.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentRequestLimiter.java // public interface ConcurrentRequestLimiter { // // Baton acquire(String key); // // Baton acquire(String key, int weight); // // }
import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentRequestLimiter; import net.jodah.expiringmap.ExpiringMap; import java.util.Optional; import java.util.concurrent.Semaphore; import java.util.function.Supplier; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static net.jodah.expiringmap.ExpirationPolicy.ACCESSED;
package es.moki.ratelimitj.inmemory.concurrent; public class InMemoryConcurrentRequestRateLimiter implements ConcurrentRequestLimiter { private final ExpiringMap<String, Semaphore> expiringKeyMap; private final ConcurrentLimitRule rule; public InMemoryConcurrentRequestRateLimiter(ConcurrentLimitRule rule) { this.rule = rule; expiringKeyMap = ExpiringMap.builder().expiration(rule.getTimeoutMillis(), MILLISECONDS).expirationPolicy(ACCESSED).build(); } @Override
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentRequestLimiter.java // public interface ConcurrentRequestLimiter { // // Baton acquire(String key); // // Baton acquire(String key, int weight); // // } // Path: ratelimitj-inmemory/src/main/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentRequestRateLimiter.java import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentRequestLimiter; import net.jodah.expiringmap.ExpiringMap; import java.util.Optional; import java.util.concurrent.Semaphore; import java.util.function.Supplier; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static net.jodah.expiringmap.ExpirationPolicy.ACCESSED; package es.moki.ratelimitj.inmemory.concurrent; public class InMemoryConcurrentRequestRateLimiter implements ConcurrentRequestLimiter { private final ExpiringMap<String, Semaphore> expiringKeyMap; private final ConcurrentLimitRule rule; public InMemoryConcurrentRequestRateLimiter(ConcurrentLimitRule rule) { this.rule = rule; expiringKeyMap = ExpiringMap.builder().expiration(rule.getTimeoutMillis(), MILLISECONDS).expirationPolicy(ACCESSED).build(); } @Override
public Baton acquire(String key) {
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/filter/RateLimit429EnforcerFilterTest.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiter.java // public interface RequestRateLimiter { // // /** // * Determine if the given key, after incrementing by one, has exceeded the configured rate limit. // * @param key key. // * @return {@code true} if the key is over the limit, otherwise {@code false} // */ // boolean overLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, has exceeded the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key has exceeded the limit, otherwise {@code false} . // */ // boolean overLimitWhenIncremented(String key, int weight); // // /** // * Determine if the given key, after incrementing by one, is &gt;= the configured rate limit. // * @param key key. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, is &gt;= the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key, int weight); // // // /** // // * Determine if the given key has exceeded the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is over the limit, otherwise {@code false} // // */ // // boolean isOverLimit(String key); // // // // /** // // * Determine if the given key is &gt;= the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // // */ // // boolean isGeLimit(String key); // // /** // * Resets the accumulated rate for the given key. // * @param key key. // * @return {@code true} if the key existed, otherwise {@code false} . // */ // boolean resetLimit(String key); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiterFactory.java // public interface RequestRateLimiterFactory extends Closeable { // // RequestRateLimiter getInstance(Set<RequestLimitRule> rules); // // ReactiveRequestRateLimiter getInstanceReactive(Set<RequestLimitRule> rules); // }
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import io.dropwizard.testing.junit5.ResourceExtension; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when;
package es.moki.ratelimij.dropwizard.filter; @ExtendWith({ DropwizardExtensionsSupport.class, MockitoExtension.class }) public class RateLimit429EnforcerFilterTest {
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiter.java // public interface RequestRateLimiter { // // /** // * Determine if the given key, after incrementing by one, has exceeded the configured rate limit. // * @param key key. // * @return {@code true} if the key is over the limit, otherwise {@code false} // */ // boolean overLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, has exceeded the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key has exceeded the limit, otherwise {@code false} . // */ // boolean overLimitWhenIncremented(String key, int weight); // // /** // * Determine if the given key, after incrementing by one, is &gt;= the configured rate limit. // * @param key key. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, is &gt;= the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key, int weight); // // // /** // // * Determine if the given key has exceeded the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is over the limit, otherwise {@code false} // // */ // // boolean isOverLimit(String key); // // // // /** // // * Determine if the given key is &gt;= the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // // */ // // boolean isGeLimit(String key); // // /** // * Resets the accumulated rate for the given key. // * @param key key. // * @return {@code true} if the key existed, otherwise {@code false} . // */ // boolean resetLimit(String key); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiterFactory.java // public interface RequestRateLimiterFactory extends Closeable { // // RequestRateLimiter getInstance(Set<RequestLimitRule> rules); // // ReactiveRequestRateLimiter getInstanceReactive(Set<RequestLimitRule> rules); // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/filter/RateLimit429EnforcerFilterTest.java import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import io.dropwizard.testing.junit5.ResourceExtension; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; package es.moki.ratelimij.dropwizard.filter; @ExtendWith({ DropwizardExtensionsSupport.class, MockitoExtension.class }) public class RateLimit429EnforcerFilterTest {
@Mock private static RequestRateLimiterFactory requestRateLimiterFactory;
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/filter/RateLimit429EnforcerFilterTest.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiter.java // public interface RequestRateLimiter { // // /** // * Determine if the given key, after incrementing by one, has exceeded the configured rate limit. // * @param key key. // * @return {@code true} if the key is over the limit, otherwise {@code false} // */ // boolean overLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, has exceeded the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key has exceeded the limit, otherwise {@code false} . // */ // boolean overLimitWhenIncremented(String key, int weight); // // /** // * Determine if the given key, after incrementing by one, is &gt;= the configured rate limit. // * @param key key. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, is &gt;= the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key, int weight); // // // /** // // * Determine if the given key has exceeded the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is over the limit, otherwise {@code false} // // */ // // boolean isOverLimit(String key); // // // // /** // // * Determine if the given key is &gt;= the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // // */ // // boolean isGeLimit(String key); // // /** // * Resets the accumulated rate for the given key. // * @param key key. // * @return {@code true} if the key existed, otherwise {@code false} . // */ // boolean resetLimit(String key); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiterFactory.java // public interface RequestRateLimiterFactory extends Closeable { // // RequestRateLimiter getInstance(Set<RequestLimitRule> rules); // // ReactiveRequestRateLimiter getInstanceReactive(Set<RequestLimitRule> rules); // }
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import io.dropwizard.testing.junit5.ResourceExtension; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when;
package es.moki.ratelimij.dropwizard.filter; @ExtendWith({ DropwizardExtensionsSupport.class, MockitoExtension.class }) public class RateLimit429EnforcerFilterTest { @Mock private static RequestRateLimiterFactory requestRateLimiterFactory;
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiter.java // public interface RequestRateLimiter { // // /** // * Determine if the given key, after incrementing by one, has exceeded the configured rate limit. // * @param key key. // * @return {@code true} if the key is over the limit, otherwise {@code false} // */ // boolean overLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, has exceeded the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key has exceeded the limit, otherwise {@code false} . // */ // boolean overLimitWhenIncremented(String key, int weight); // // /** // * Determine if the given key, after incrementing by one, is &gt;= the configured rate limit. // * @param key key. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key); // // /** // * Determine if the given key, after incrementing by the given weight, is &gt;= the configured rate limit. // * @param key key. // * @param weight A variable weight. // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // */ // boolean geLimitWhenIncremented(String key, int weight); // // // /** // // * Determine if the given key has exceeded the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is over the limit, otherwise {@code false} // // */ // // boolean isOverLimit(String key); // // // // /** // // * Determine if the given key is &gt;= the configured rate limit. // // * @param key key. // // * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} . // // */ // // boolean isGeLimit(String key); // // /** // * Resets the accumulated rate for the given key. // * @param key key. // * @return {@code true} if the key existed, otherwise {@code false} . // */ // boolean resetLimit(String key); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiterFactory.java // public interface RequestRateLimiterFactory extends Closeable { // // RequestRateLimiter getInstance(Set<RequestLimitRule> rules); // // ReactiveRequestRateLimiter getInstanceReactive(Set<RequestLimitRule> rules); // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/filter/RateLimit429EnforcerFilterTest.java import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import io.dropwizard.testing.junit5.ResourceExtension; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; package es.moki.ratelimij.dropwizard.filter; @ExtendWith({ DropwizardExtensionsSupport.class, MockitoExtension.class }) public class RateLimit429EnforcerFilterTest { @Mock private static RequestRateLimiterFactory requestRateLimiterFactory;
@Mock private RequestRateLimiter requestRateLimiter;
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/LoginResource.java
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // }
import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit;
package es.moki.ratelimij.dropwizard.component.app.api; @Path("/login") @Consumes(MediaType.APPLICATION_JSON) public class LoginResource { @POST
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/LoginResource.java import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit; package es.moki.ratelimij.dropwizard.component.app.api; @Path("/login") @Consumes(MediaType.APPLICATION_JSON) public class LoginResource { @POST
@RateLimited(keys = { KeyPart.ANY }, rates = {
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/LoginResource.java
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // }
import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit;
package es.moki.ratelimij.dropwizard.component.app.api; @Path("/login") @Consumes(MediaType.APPLICATION_JSON) public class LoginResource { @POST @RateLimited(keys = { KeyPart.ANY }, rates = { @Rate(duration = 10, timeUnit = TimeUnit.HOURS, limit = 5)})
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/LoginResource.java import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit; package es.moki.ratelimij.dropwizard.component.app.api; @Path("/login") @Consumes(MediaType.APPLICATION_JSON) public class LoginResource { @POST @RateLimited(keys = { KeyPart.ANY }, rates = { @Rate(duration = 10, timeUnit = TimeUnit.HOURS, limit = 5)})
public Response login(final LoginRequest login) {
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/DropwizardRateLimitComponentTest.java
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/RateLimitApplication.java // public class RateLimitApplication extends Application<Configuration> { // // @Override // public void initialize(Bootstrap<Configuration> bootstrap) { // RedisClient redisClient = RedisClient.create("redis://localhost:7006"); // RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient); // bootstrap.addBundle(new RateLimitBundle(factory)); // } // // @Override // public void run(Configuration configuration, Environment environment) { // environment.jersey().register(new LoginResource()); // environment.jersey().register(new UserResource()); // environment.jersey().register(new TrekResource()); // environment.jersey().register(new AuthDynamicFeature( // new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() // .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") // .buildAuthFilter())); // environment.jersey().register(RolesAllowedDynamicFeature.class); // environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/extension/RedisStandaloneFlushExtension.java // public class RedisStandaloneFlushExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // } // // }
import es.moki.ratelimij.dropwizard.component.app.RateLimitApplication; import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimitj.redis.extensions.RedisStandaloneFlushExtension; import io.dropwizard.Configuration; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat;
package es.moki.ratelimij.dropwizard.component; @ExtendWith({ DropwizardExtensionsSupport.class,
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/RateLimitApplication.java // public class RateLimitApplication extends Application<Configuration> { // // @Override // public void initialize(Bootstrap<Configuration> bootstrap) { // RedisClient redisClient = RedisClient.create("redis://localhost:7006"); // RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient); // bootstrap.addBundle(new RateLimitBundle(factory)); // } // // @Override // public void run(Configuration configuration, Environment environment) { // environment.jersey().register(new LoginResource()); // environment.jersey().register(new UserResource()); // environment.jersey().register(new TrekResource()); // environment.jersey().register(new AuthDynamicFeature( // new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() // .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") // .buildAuthFilter())); // environment.jersey().register(RolesAllowedDynamicFeature.class); // environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/extension/RedisStandaloneFlushExtension.java // public class RedisStandaloneFlushExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/DropwizardRateLimitComponentTest.java import es.moki.ratelimij.dropwizard.component.app.RateLimitApplication; import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimitj.redis.extensions.RedisStandaloneFlushExtension; import io.dropwizard.Configuration; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; package es.moki.ratelimij.dropwizard.component; @ExtendWith({ DropwizardExtensionsSupport.class,
RedisStandaloneFlushExtension.class
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/DropwizardRateLimitComponentTest.java
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/RateLimitApplication.java // public class RateLimitApplication extends Application<Configuration> { // // @Override // public void initialize(Bootstrap<Configuration> bootstrap) { // RedisClient redisClient = RedisClient.create("redis://localhost:7006"); // RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient); // bootstrap.addBundle(new RateLimitBundle(factory)); // } // // @Override // public void run(Configuration configuration, Environment environment) { // environment.jersey().register(new LoginResource()); // environment.jersey().register(new UserResource()); // environment.jersey().register(new TrekResource()); // environment.jersey().register(new AuthDynamicFeature( // new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() // .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") // .buildAuthFilter())); // environment.jersey().register(RolesAllowedDynamicFeature.class); // environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/extension/RedisStandaloneFlushExtension.java // public class RedisStandaloneFlushExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // } // // }
import es.moki.ratelimij.dropwizard.component.app.RateLimitApplication; import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimitj.redis.extensions.RedisStandaloneFlushExtension; import io.dropwizard.Configuration; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat;
package es.moki.ratelimij.dropwizard.component; @ExtendWith({ DropwizardExtensionsSupport.class, RedisStandaloneFlushExtension.class }) public class DropwizardRateLimitComponentTest { private final DropwizardAppExtension<Configuration> app = new DropwizardAppExtension<>(
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/RateLimitApplication.java // public class RateLimitApplication extends Application<Configuration> { // // @Override // public void initialize(Bootstrap<Configuration> bootstrap) { // RedisClient redisClient = RedisClient.create("redis://localhost:7006"); // RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient); // bootstrap.addBundle(new RateLimitBundle(factory)); // } // // @Override // public void run(Configuration configuration, Environment environment) { // environment.jersey().register(new LoginResource()); // environment.jersey().register(new UserResource()); // environment.jersey().register(new TrekResource()); // environment.jersey().register(new AuthDynamicFeature( // new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() // .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") // .buildAuthFilter())); // environment.jersey().register(RolesAllowedDynamicFeature.class); // environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/extension/RedisStandaloneFlushExtension.java // public class RedisStandaloneFlushExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/DropwizardRateLimitComponentTest.java import es.moki.ratelimij.dropwizard.component.app.RateLimitApplication; import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimitj.redis.extensions.RedisStandaloneFlushExtension; import io.dropwizard.Configuration; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; package es.moki.ratelimij.dropwizard.component; @ExtendWith({ DropwizardExtensionsSupport.class, RedisStandaloneFlushExtension.class }) public class DropwizardRateLimitComponentTest { private final DropwizardAppExtension<Configuration> app = new DropwizardAppExtension<>(
RateLimitApplication.class,
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/DropwizardRateLimitComponentTest.java
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/RateLimitApplication.java // public class RateLimitApplication extends Application<Configuration> { // // @Override // public void initialize(Bootstrap<Configuration> bootstrap) { // RedisClient redisClient = RedisClient.create("redis://localhost:7006"); // RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient); // bootstrap.addBundle(new RateLimitBundle(factory)); // } // // @Override // public void run(Configuration configuration, Environment environment) { // environment.jersey().register(new LoginResource()); // environment.jersey().register(new UserResource()); // environment.jersey().register(new TrekResource()); // environment.jersey().register(new AuthDynamicFeature( // new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() // .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") // .buildAuthFilter())); // environment.jersey().register(RolesAllowedDynamicFeature.class); // environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/extension/RedisStandaloneFlushExtension.java // public class RedisStandaloneFlushExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // } // // }
import es.moki.ratelimij.dropwizard.component.app.RateLimitApplication; import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimitj.redis.extensions.RedisStandaloneFlushExtension; import io.dropwizard.Configuration; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat;
Response getLimitedByDefault() { return client.target(String.format("http://localhost:%d/application/user/{id}/default", localPort)) .resolveTemplate("id", 1) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); } Response getLimitedByAuthenticatedUser() { return client.target(String.format("http://localhost:%d/application/user/{id}/authenticated", localPort)) .resolveTemplate("id", 1) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); } Response getKlingons() { return client.target(String.format("http://localhost:%d/application/klingons", localPort)) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); } Response getVulcans() { return client.target(String.format("http://localhost:%d/application/vulcans", localPort)) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); }
// Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/RateLimitApplication.java // public class RateLimitApplication extends Application<Configuration> { // // @Override // public void initialize(Bootstrap<Configuration> bootstrap) { // RedisClient redisClient = RedisClient.create("redis://localhost:7006"); // RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient); // bootstrap.addBundle(new RateLimitBundle(factory)); // } // // @Override // public void run(Configuration configuration, Environment environment) { // environment.jersey().register(new LoginResource()); // environment.jersey().register(new UserResource()); // environment.jersey().register(new TrekResource()); // environment.jersey().register(new AuthDynamicFeature( // new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() // .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") // .buildAuthFilter())); // environment.jersey().register(RolesAllowedDynamicFeature.class); // environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/model/LoginRequest.java // public class LoginRequest { // // public final String username; // // public final String password; // // @JsonCreator // public LoginRequest(@JsonProperty("username") String username, // @JsonProperty("password") String password) { // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // } // // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/extension/RedisStandaloneFlushExtension.java // public class RedisStandaloneFlushExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/DropwizardRateLimitComponentTest.java import es.moki.ratelimij.dropwizard.component.app.RateLimitApplication; import es.moki.ratelimij.dropwizard.component.app.model.LoginRequest; import es.moki.ratelimitj.redis.extensions.RedisStandaloneFlushExtension; import io.dropwizard.Configuration; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; Response getLimitedByDefault() { return client.target(String.format("http://localhost:%d/application/user/{id}/default", localPort)) .resolveTemplate("id", 1) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); } Response getLimitedByAuthenticatedUser() { return client.target(String.format("http://localhost:%d/application/user/{id}/authenticated", localPort)) .resolveTemplate("id", 1) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); } Response getKlingons() { return client.target(String.format("http://localhost:%d/application/klingons", localPort)) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); } Response getVulcans() { return client.target(String.format("http://localhost:%d/application/vulcans", localPort)) .request() .header(HttpHeaders.AUTHORIZATION, "Bearer secret") .get(); }
private LoginRequest loginForm() {
mokies/ratelimitj
ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/RateLimitBundle.java
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/RateLimited429EnforcerFeature.java // @Provider // public class RateLimited429EnforcerFeature implements DynamicFeature { // // @Override // public void configure(final ResourceInfo resourceInfo, // final FeatureContext context) { // // final AnnotatedMethod method = new AnnotatedMethod(resourceInfo.getResourceMethod()); // final RateLimited rateLimited = method.getAnnotation(RateLimited.class); // // if (null != rateLimited) { // context.register(RateLimit429EnforcerFilter.class); // } // } // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiterFactory.java // public interface RequestRateLimiterFactory extends Closeable { // // RequestRateLimiter getInstance(Set<RequestLimitRule> rules); // // ReactiveRequestRateLimiter getInstanceReactive(Set<RequestLimitRule> rules); // }
import es.moki.ratelimij.dropwizard.filter.RateLimited429EnforcerFeature; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.lifecycle.Managed; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.glassfish.hk2.utilities.binding.AbstractBinder; import static java.util.Objects.requireNonNull;
package es.moki.ratelimij.dropwizard; public class RateLimitBundle implements ConfiguredBundle<Configuration> { private final RequestRateLimiterFactory requestRateLimiterFactory; public RateLimitBundle(RequestRateLimiterFactory requestRateLimiterFactory) { this.requestRateLimiterFactory = requireNonNull(requestRateLimiterFactory); } @Override public void initialize(Bootstrap<?> bootstrap) { } @Override public void run(final Configuration configuration, final Environment environment) { environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(requestRateLimiterFactory).to(RequestRateLimiterFactory.class); } });
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/RateLimited429EnforcerFeature.java // @Provider // public class RateLimited429EnforcerFeature implements DynamicFeature { // // @Override // public void configure(final ResourceInfo resourceInfo, // final FeatureContext context) { // // final AnnotatedMethod method = new AnnotatedMethod(resourceInfo.getResourceMethod()); // final RateLimited rateLimited = method.getAnnotation(RateLimited.class); // // if (null != rateLimited) { // context.register(RateLimit429EnforcerFilter.class); // } // } // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestRateLimiterFactory.java // public interface RequestRateLimiterFactory extends Closeable { // // RequestRateLimiter getInstance(Set<RequestLimitRule> rules); // // ReactiveRequestRateLimiter getInstanceReactive(Set<RequestLimitRule> rules); // } // Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/RateLimitBundle.java import es.moki.ratelimij.dropwizard.filter.RateLimited429EnforcerFeature; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.lifecycle.Managed; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.glassfish.hk2.utilities.binding.AbstractBinder; import static java.util.Objects.requireNonNull; package es.moki.ratelimij.dropwizard; public class RateLimitBundle implements ConfiguredBundle<Configuration> { private final RequestRateLimiterFactory requestRateLimiterFactory; public RateLimitBundle(RequestRateLimiterFactory requestRateLimiterFactory) { this.requestRateLimiterFactory = requireNonNull(requestRateLimiterFactory); } @Override public void initialize(Bootstrap<?> bootstrap) { } @Override public void run(final Configuration configuration, final Environment environment) { environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(requestRateLimiterFactory).to(RequestRateLimiterFactory.class); } });
environment.jersey().register(new RateLimited429EnforcerFeature());
mokies/ratelimitj
ratelimitj-inmemory/src/test/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentSyncRequestRateLimiterTest.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-test/src/main/java/es/moki/ratelimitj/test/limiter/concurrent/AbstractSyncConcurrentRateLimiterTest.java // public class AbstractSyncConcurrentRateLimiterTest { // }
import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.test.limiter.concurrent.AbstractSyncConcurrentRateLimiterTest; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat;
package es.moki.ratelimitj.inmemory.concurrent; class InMemoryConcurrentSyncRequestRateLimiterTest extends AbstractSyncConcurrentRateLimiterTest { @Test void shouldPreventConcurrentRequests() { InMemoryConcurrentRequestRateLimiter limiter = new InMemoryConcurrentRequestRateLimiter(
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-test/src/main/java/es/moki/ratelimitj/test/limiter/concurrent/AbstractSyncConcurrentRateLimiterTest.java // public class AbstractSyncConcurrentRateLimiterTest { // } // Path: ratelimitj-inmemory/src/test/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentSyncRequestRateLimiterTest.java import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.test.limiter.concurrent.AbstractSyncConcurrentRateLimiterTest; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; package es.moki.ratelimitj.inmemory.concurrent; class InMemoryConcurrentSyncRequestRateLimiterTest extends AbstractSyncConcurrentRateLimiterTest { @Test void shouldPreventConcurrentRequests() { InMemoryConcurrentRequestRateLimiter limiter = new InMemoryConcurrentRequestRateLimiter(
ConcurrentLimitRule.of(2, TimeUnit.MINUTES, 1));
mokies/ratelimitj
ratelimitj-inmemory/src/test/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentSyncRequestRateLimiterTest.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-test/src/main/java/es/moki/ratelimitj/test/limiter/concurrent/AbstractSyncConcurrentRateLimiterTest.java // public class AbstractSyncConcurrentRateLimiterTest { // }
import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.test.limiter.concurrent.AbstractSyncConcurrentRateLimiterTest; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat;
package es.moki.ratelimitj.inmemory.concurrent; class InMemoryConcurrentSyncRequestRateLimiterTest extends AbstractSyncConcurrentRateLimiterTest { @Test void shouldPreventConcurrentRequests() { InMemoryConcurrentRequestRateLimiter limiter = new InMemoryConcurrentRequestRateLimiter( ConcurrentLimitRule.of(2, TimeUnit.MINUTES, 1)); assertThat(limiter.acquire("key").hasAcquired()).isTrue();
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/Baton.java // public interface Baton { // // void release(); // // <T> Optional<T> get(Supplier<T> action); // // void doAction(Runnable action); // // boolean hasAcquired(); // } // // Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java // @ParametersAreNonnullByDefault // public class ConcurrentLimitRule { // // private final int concurrentLimit; // private final long timeoutMillis; // private final String name; // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis) { // this(concurrentLimit, timeoutMillis, null); // } // // private ConcurrentLimitRule(int concurrentLimit, long timeoutMillis, String name) { // this.concurrentLimit = concurrentLimit; // this.timeoutMillis = timeoutMillis; // this.name = name; // } // // /** // * Initialise a concurrent rate limit. // * // * @param concurrentLimit The concurrent limit. // * @param timeOutUnit The time unit. // * @param timeOut A timeOut for the checkout baton. // * @return A concurrent limit rule. // */ // public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) { // requireNonNull(timeOutUnit, "time out unit can not be null"); // return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut)); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public ConcurrentLimitRule withName(String name) { // return new ConcurrentLimitRule(this.concurrentLimit, this.timeoutMillis, name); // } // // public int getConcurrentLimit() { // return concurrentLimit; // } // // public long getTimeoutMillis() { // return timeoutMillis; // } // // public String getName() { // return name; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof ConcurrentLimitRule)) { // return false; // } // ConcurrentLimitRule that = (ConcurrentLimitRule) o; // return concurrentLimit == that.concurrentLimit && // timeoutMillis == that.timeoutMillis && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(concurrentLimit, timeoutMillis, name); // } // } // // Path: ratelimitj-test/src/main/java/es/moki/ratelimitj/test/limiter/concurrent/AbstractSyncConcurrentRateLimiterTest.java // public class AbstractSyncConcurrentRateLimiterTest { // } // Path: ratelimitj-inmemory/src/test/java/es/moki/ratelimitj/inmemory/concurrent/InMemoryConcurrentSyncRequestRateLimiterTest.java import es.moki.ratelimitj.core.limiter.concurrent.Baton; import es.moki.ratelimitj.core.limiter.concurrent.ConcurrentLimitRule; import es.moki.ratelimitj.test.limiter.concurrent.AbstractSyncConcurrentRateLimiterTest; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; package es.moki.ratelimitj.inmemory.concurrent; class InMemoryConcurrentSyncRequestRateLimiterTest extends AbstractSyncConcurrentRateLimiterTest { @Test void shouldPreventConcurrentRequests() { InMemoryConcurrentRequestRateLimiter limiter = new InMemoryConcurrentRequestRateLimiter( ConcurrentLimitRule.of(2, TimeUnit.MINUTES, 1)); assertThat(limiter.acquire("key").hasAcquired()).isTrue();
Baton baton1 = limiter.acquire("key");
mokies/ratelimitj
ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/annotation/RateLimited.java
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // }
import es.moki.ratelimij.dropwizard.filter.KeyPart; import javax.ws.rs.NameBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package es.moki.ratelimij.dropwizard.annotation; @NameBinding @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD}) public @interface RateLimited {
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // } // Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/annotation/RateLimited.java import es.moki.ratelimij.dropwizard.filter.KeyPart; import javax.ws.rs.NameBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package es.moki.ratelimij.dropwizard.annotation; @NameBinding @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD}) public @interface RateLimited {
KeyPart[] keys() default {};
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/TrekResource.java
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // }
import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import io.dropwizard.auth.Auth; import io.dropwizard.auth.PrincipalImpl; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit;
package es.moki.ratelimij.dropwizard.component.app.api; @Path("/") @Consumes(MediaType.APPLICATION_JSON) public class TrekResource { @GET @Path("vulcans")
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/TrekResource.java import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import io.dropwizard.auth.Auth; import io.dropwizard.auth.PrincipalImpl; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit; package es.moki.ratelimij.dropwizard.component.app.api; @Path("/") @Consumes(MediaType.APPLICATION_JSON) public class TrekResource { @GET @Path("vulcans")
@RateLimited(groupKeyPrefix = "trek-races", keys = KeyPart.AUTHENTICATED, rates = {@Rate(duration = 10, timeUnit = TimeUnit.HOURS, limit = 10)})
mokies/ratelimitj
ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/RedisScriptLoaderTest.java
// Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/extensions/RedisStandaloneConnectionSetupExtension.java // public class RedisStandaloneConnectionSetupExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // private static RedisReactiveCommands<String, String> reactiveCommands; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // reactiveCommands = connect.reactive(); // } // // public RedisClient getClient() { // return client; // } // // public RedisScriptingReactiveCommands<String, String> getScriptingReactiveCommands() { // return reactiveCommands; // } // // public RedisKeyReactiveCommands<String, String> getKeyReactiveCommands() { // return reactiveCommands; // } // // }
import es.moki.ratelimitj.redis.extensions.RedisStandaloneConnectionSetupExtension; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import java.time.Duration; import java.time.temporal.ChronoUnit; import static io.lettuce.core.ScriptOutputType.VALUE; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
package es.moki.ratelimitj.redis.request; class RedisScriptLoaderTest { @RegisterExtension
// Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/extensions/RedisStandaloneConnectionSetupExtension.java // public class RedisStandaloneConnectionSetupExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // private static RedisReactiveCommands<String, String> reactiveCommands; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // reactiveCommands = connect.reactive(); // } // // public RedisClient getClient() { // return client; // } // // public RedisScriptingReactiveCommands<String, String> getScriptingReactiveCommands() { // return reactiveCommands; // } // // public RedisKeyReactiveCommands<String, String> getKeyReactiveCommands() { // return reactiveCommands; // } // // } // Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/RedisScriptLoaderTest.java import es.moki.ratelimitj.redis.extensions.RedisStandaloneConnectionSetupExtension; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import java.time.Duration; import java.time.temporal.ChronoUnit; import static io.lettuce.core.ScriptOutputType.VALUE; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; package es.moki.ratelimitj.redis.request; class RedisScriptLoaderTest { @RegisterExtension
static RedisStandaloneConnectionSetupExtension extension = new RedisStandaloneConnectionSetupExtension();
mokies/ratelimitj
ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/RequestLimitRuleJsonSerialiserTest.java
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java // @ParametersAreNonnullByDefault // public class RequestLimitRule { // // private final int durationSeconds; // private final long limit; // private final int precision; // private final String name; // private final Set<String> keys; // // private RequestLimitRule(int durationSeconds, long limit, int precision) { // this(durationSeconds, limit, precision, null); // } // // private RequestLimitRule(int durationSeconds, long limit, int precision, String name) { // this(durationSeconds, limit, precision, name, null); // } // // private RequestLimitRule(int durationSeconds, long limit, int precision, String name, Set<String> keys) { // this.durationSeconds = durationSeconds; // this.limit = limit; // this.precision = precision; // this.name = name; // this.keys = keys; // } // // private static void checkDuration(Duration duration) { // requireNonNull(duration, "duration can not be null"); // if (Duration.ofSeconds(1).compareTo(duration) > 0) { // throw new IllegalArgumentException("duration must be great than 1 second"); // } // } // // /** // * Initialise a request rate limit. Imagine the whole duration window as being one large bucket with a single count. // * // * @param duration The time the limit will be applied over. The duration must be greater than 1 second. // * @param limit A number representing the maximum operations that can be performed in the given duration. // * @return A limit rule. // */ // public static RequestLimitRule of(Duration duration, long limit) { // checkDuration(duration); // if (limit < 0) { // throw new IllegalArgumentException("limit must be greater than zero."); // } // int durationSeconds = (int) duration.getSeconds(); // return new RequestLimitRule(durationSeconds, limit, durationSeconds); // } // // /** // * Controls (approximate) sliding window precision. A lower duration increases precision and minimises the Thundering herd problem - https://en.wikipedia.org/wiki/Thundering_herd_problem // * // * @param precision Defines the time precision that will be used to approximate the sliding window. The precision must be greater than 1 second. // * @return a limit rule // */ // public RequestLimitRule withPrecision(Duration precision) { // checkDuration(precision); // return new RequestLimitRule(this.durationSeconds, this.limit, (int) precision.getSeconds(), this.name, this.keys); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public RequestLimitRule withName(String name) { // return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, name, this.keys); // } // // /** // * Applies a key to the rate limit that defines to which keys, the rule applies, empty for any unmatched key. // * // * @param keys Defines a set of keys to which the rule applies. // * @return a limit rule // */ // public RequestLimitRule matchingKeys(String... keys) { // Set<String> keySet = keys.length > 0 ? new HashSet<>(Arrays.asList(keys)) : null; // return matchingKeys(keySet); // } // // /** // * Applies a key to the rate limit that defines to which keys, the rule applies, null for any unmatched key. // * // * @param keys Defines a set of keys to which the rule applies. // * @return a limit rule // */ // public RequestLimitRule matchingKeys(Set<String> keys) { // return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, this.name, keys); // } // // /** // * @return The limits duration in seconds. // */ // public int getDurationSeconds() { // return durationSeconds; // } // // /** // * @return The limits precision in seconds. // */ // public int getPrecisionSeconds() { // return precision; // } // // /** // * @return The name. // */ // public String getName() { // return name; // } // // /** // * @return The limit. // */ // public long getLimit() { // return limit; // } // // /** // * @return The keys. // */ // @Nullable // public Set<String> getKeys() { // return keys; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof RequestLimitRule)) { // return false; // } // RequestLimitRule that = (RequestLimitRule) o; // return durationSeconds == that.durationSeconds // && limit == that.limit // && Objects.equals(precision, that.precision) // && Objects.equals(name, that.name) // && Objects.equals(keys, that.keys); // } // // @Override // public int hashCode() { // return Objects.hash(durationSeconds, limit, precision, name, keys); // } // }
import com.google.common.collect.ImmutableList; import es.moki.ratelimitj.core.limiter.request.RequestLimitRule; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat;
package es.moki.ratelimitj.redis.request; class RequestLimitRuleJsonSerialiserTest { private final LimitRuleJsonSerialiser serialiser = new LimitRuleJsonSerialiser(); @Test @DisplayName("should encode limit rule in JSON array") void shouldEncode() {
// Path: ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/request/RequestLimitRule.java // @ParametersAreNonnullByDefault // public class RequestLimitRule { // // private final int durationSeconds; // private final long limit; // private final int precision; // private final String name; // private final Set<String> keys; // // private RequestLimitRule(int durationSeconds, long limit, int precision) { // this(durationSeconds, limit, precision, null); // } // // private RequestLimitRule(int durationSeconds, long limit, int precision, String name) { // this(durationSeconds, limit, precision, name, null); // } // // private RequestLimitRule(int durationSeconds, long limit, int precision, String name, Set<String> keys) { // this.durationSeconds = durationSeconds; // this.limit = limit; // this.precision = precision; // this.name = name; // this.keys = keys; // } // // private static void checkDuration(Duration duration) { // requireNonNull(duration, "duration can not be null"); // if (Duration.ofSeconds(1).compareTo(duration) > 0) { // throw new IllegalArgumentException("duration must be great than 1 second"); // } // } // // /** // * Initialise a request rate limit. Imagine the whole duration window as being one large bucket with a single count. // * // * @param duration The time the limit will be applied over. The duration must be greater than 1 second. // * @param limit A number representing the maximum operations that can be performed in the given duration. // * @return A limit rule. // */ // public static RequestLimitRule of(Duration duration, long limit) { // checkDuration(duration); // if (limit < 0) { // throw new IllegalArgumentException("limit must be greater than zero."); // } // int durationSeconds = (int) duration.getSeconds(); // return new RequestLimitRule(durationSeconds, limit, durationSeconds); // } // // /** // * Controls (approximate) sliding window precision. A lower duration increases precision and minimises the Thundering herd problem - https://en.wikipedia.org/wiki/Thundering_herd_problem // * // * @param precision Defines the time precision that will be used to approximate the sliding window. The precision must be greater than 1 second. // * @return a limit rule // */ // public RequestLimitRule withPrecision(Duration precision) { // checkDuration(precision); // return new RequestLimitRule(this.durationSeconds, this.limit, (int) precision.getSeconds(), this.name, this.keys); // } // // /** // * Applies a name to the rate limit that is useful for metrics. // * // * @param name Defines a descriptive name for the rule limit. // * @return a limit rule // */ // public RequestLimitRule withName(String name) { // return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, name, this.keys); // } // // /** // * Applies a key to the rate limit that defines to which keys, the rule applies, empty for any unmatched key. // * // * @param keys Defines a set of keys to which the rule applies. // * @return a limit rule // */ // public RequestLimitRule matchingKeys(String... keys) { // Set<String> keySet = keys.length > 0 ? new HashSet<>(Arrays.asList(keys)) : null; // return matchingKeys(keySet); // } // // /** // * Applies a key to the rate limit that defines to which keys, the rule applies, null for any unmatched key. // * // * @param keys Defines a set of keys to which the rule applies. // * @return a limit rule // */ // public RequestLimitRule matchingKeys(Set<String> keys) { // return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, this.name, keys); // } // // /** // * @return The limits duration in seconds. // */ // public int getDurationSeconds() { // return durationSeconds; // } // // /** // * @return The limits precision in seconds. // */ // public int getPrecisionSeconds() { // return precision; // } // // /** // * @return The name. // */ // public String getName() { // return name; // } // // /** // * @return The limit. // */ // public long getLimit() { // return limit; // } // // /** // * @return The keys. // */ // @Nullable // public Set<String> getKeys() { // return keys; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || !(o instanceof RequestLimitRule)) { // return false; // } // RequestLimitRule that = (RequestLimitRule) o; // return durationSeconds == that.durationSeconds // && limit == that.limit // && Objects.equals(precision, that.precision) // && Objects.equals(name, that.name) // && Objects.equals(keys, that.keys); // } // // @Override // public int hashCode() { // return Objects.hash(durationSeconds, limit, precision, name, keys); // } // } // Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/RequestLimitRuleJsonSerialiserTest.java import com.google.common.collect.ImmutableList; import es.moki.ratelimitj.core.limiter.request.RequestLimitRule; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; package es.moki.ratelimitj.redis.request; class RequestLimitRuleJsonSerialiserTest { private final LimitRuleJsonSerialiser serialiser = new LimitRuleJsonSerialiser(); @Test @DisplayName("should encode limit rule in JSON array") void shouldEncode() {
ImmutableList<RequestLimitRule> rules = ImmutableList.of(RequestLimitRule.of(Duration.ofSeconds(10), 10L),
mokies/ratelimitj
ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/UserResource.java
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // }
import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import io.dropwizard.auth.Auth; import io.dropwizard.auth.PrincipalImpl; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit;
package es.moki.ratelimij.dropwizard.component.app.api; @Path("/user") @Consumes(MediaType.APPLICATION_JSON) public class UserResource { @GET @Path("/{id}/default")
// Path: ratelimitj-dropwizard/src/main/java/es/moki/ratelimij/dropwizard/filter/KeyPart.java // @ParametersAreNonnullByDefault // public enum KeyPart implements KeyProvider { // // /** // * The 'any' key will be the first of: // * <ul> // * <li>authenticated principle (Dropwizard auth)</li> // * <li>X-Forwarded-For Header IP address</li> // * <li>servlet remote address IP</li> // * </ul> // */ // ANY { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> userRequestKey(securityContext), // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // }, // // /** // * The 'authenticated' key will be the authenticated principle (Dropwizard auth). // */ // AUTHENTICATED { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return userRequestKey(securityContext); // } // }, // // /** // * The 'ip' key will be the IP (X-Forwarded-For Header or servlet remote address). // */ // IP { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return selectOptional( // () -> xForwardedForRequestKey(request), // () -> ipRequestKey(request)); // } // // }, // // /** // * The 'resource' key will be the of the resource name. // */ // RESOURCE_NAME { // @Override // public Optional<CharSequence> create(final HttpServletRequest request, // final ResourceInfo resource, // final SecurityContext securityContext) { // return Optional.of(resource.getResourceClass().getTypeName() // + "#" + resource.getResourceMethod().getName()); // } // }; // // static Optional<CharSequence> userRequestKey(SecurityContext securityContext) { // Principal userPrincipal = securityContext.getUserPrincipal(); // if (isNull(userPrincipal)) { // return Optional.empty(); // } // return Optional.of("usr#" + userPrincipal.getName()); // } // // private static final String X_FORWARDED_FOR = "X-Forwarded-For"; // // static Optional<CharSequence> xForwardedForRequestKey(HttpServletRequest request) { // // String header = request.getHeader(X_FORWARDED_FOR); // if (isNull(header)) { // return Optional.empty(); // } // // Optional<String> originatingClientIp = Stream.of(header.split(",")).findFirst(); // return originatingClientIp.map(ip -> "xfwd4#" + ip); // } // // static Optional<CharSequence> ipRequestKey(HttpServletRequest request) { // String remoteAddress = request.getRemoteAddr(); // if (isNull(remoteAddress)) { // return Optional.empty(); // } // return Optional.of("ip#" + remoteAddress); // } // // @SafeVarargs // static <T> Optional<T> selectOptional(Supplier<Optional<T>>... optionals) { // return Arrays.stream(optionals) // .reduce((s1, s2) -> () -> s1.get().map(Optional::of).orElseGet(s2)) // .orElse(Optional::empty).get(); // } // // public static Optional<CharSequence> combineKeysParts(CharSequence groupKeyPrefix, List<KeyProvider> keyParts, HttpServletRequest request, ResourceInfo resource, SecurityContext securityContext) { // // List<CharSequence> keys = Stream.concat( // Stream.of(groupKeyPrefix), // keyParts.stream() // .map(keyPart -> keyPart.create(request, resource, securityContext)) // .filter(Optional::isPresent) // .map(Optional::get) // ).collect(Collectors.toList()); // // if (keys.isEmpty()) { // return Optional.empty(); // } // return Optional.of(keys.stream().collect(Collectors.joining(":", "rlj", ""))); // } // // } // Path: ratelimitj-dropwizard/src/test/java/es/moki/ratelimij/dropwizard/component/app/api/UserResource.java import es.moki.ratelimij.dropwizard.annotation.Rate; import es.moki.ratelimij.dropwizard.annotation.RateLimited; import es.moki.ratelimij.dropwizard.filter.KeyPart; import io.dropwizard.auth.Auth; import io.dropwizard.auth.PrincipalImpl; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.concurrent.TimeUnit; package es.moki.ratelimij.dropwizard.component.app.api; @Path("/user") @Consumes(MediaType.APPLICATION_JSON) public class UserResource { @GET @Path("/{id}/default")
@RateLimited(keys = { KeyPart.ANY }, rates = {@Rate(duration = 10, timeUnit = TimeUnit.HOURS, limit = 5)})
mokies/ratelimitj
ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/reactive/RedisStandaloneSlidingWindowReactiveRequestRateLimiterTest.java
// Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/extensions/RedisStandaloneConnectionSetupExtension.java // public class RedisStandaloneConnectionSetupExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // private static RedisReactiveCommands<String, String> reactiveCommands; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // reactiveCommands = connect.reactive(); // } // // public RedisClient getClient() { // return client; // } // // public RedisScriptingReactiveCommands<String, String> getScriptingReactiveCommands() { // return reactiveCommands; // } // // public RedisKeyReactiveCommands<String, String> getKeyReactiveCommands() { // return reactiveCommands; // } // // }
import es.moki.ratelimitj.redis.extensions.RedisStandaloneConnectionSetupExtension; import io.lettuce.core.api.reactive.RedisKeyReactiveCommands; import io.lettuce.core.api.reactive.RedisScriptingReactiveCommands; import org.junit.jupiter.api.extension.RegisterExtension;
package es.moki.ratelimitj.redis.request.reactive; public class RedisStandaloneSlidingWindowReactiveRequestRateLimiterTest extends RedisSlidingWindowReactiveRequestRateLimiterTest { @RegisterExtension
// Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/extensions/RedisStandaloneConnectionSetupExtension.java // public class RedisStandaloneConnectionSetupExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClient client; // private static StatefulRedisConnection<String, String> connect; // private static RedisReactiveCommands<String, String> reactiveCommands; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClient.create("redis://localhost:7006"); // connect = client.connect(); // reactiveCommands = connect.reactive(); // } // // public RedisClient getClient() { // return client; // } // // public RedisScriptingReactiveCommands<String, String> getScriptingReactiveCommands() { // return reactiveCommands; // } // // public RedisKeyReactiveCommands<String, String> getKeyReactiveCommands() { // return reactiveCommands; // } // // } // Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/reactive/RedisStandaloneSlidingWindowReactiveRequestRateLimiterTest.java import es.moki.ratelimitj.redis.extensions.RedisStandaloneConnectionSetupExtension; import io.lettuce.core.api.reactive.RedisKeyReactiveCommands; import io.lettuce.core.api.reactive.RedisScriptingReactiveCommands; import org.junit.jupiter.api.extension.RegisterExtension; package es.moki.ratelimitj.redis.request.reactive; public class RedisStandaloneSlidingWindowReactiveRequestRateLimiterTest extends RedisSlidingWindowReactiveRequestRateLimiterTest { @RegisterExtension
static RedisStandaloneConnectionSetupExtension extension = new RedisStandaloneConnectionSetupExtension();
mokies/ratelimitj
ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/reactive/RedisClusterSlidingWindowReactiveRequestRateLimiterTest.java
// Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/extensions/RedisClusterConnectionSetupExtension.java // public class RedisClusterConnectionSetupExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClusterClient client; // private static StatefulRedisClusterConnection<String, String> connect; // private static RedisAdvancedClusterReactiveCommands<String, String> reactiveCommands; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClusterClient.create("redis://localhost:7000"); // connect = client.connect(); // reactiveCommands = connect.reactive(); // } // // public RedisClusterClient getClient() { // return client; // } // // public RedisScriptingReactiveCommands<String, String> getRedisScriptingReactiveCommands() { // return reactiveCommands; // } // // public RedisKeyReactiveCommands<String, String> getRedisKeyReactiveCommands() { // return reactiveCommands; // } // // }
import es.moki.ratelimitj.redis.extensions.RedisClusterConnectionSetupExtension; import io.lettuce.core.api.reactive.RedisKeyReactiveCommands; import io.lettuce.core.api.reactive.RedisScriptingReactiveCommands; import org.junit.jupiter.api.extension.RegisterExtension;
package es.moki.ratelimitj.redis.request.reactive; public class RedisClusterSlidingWindowReactiveRequestRateLimiterTest extends RedisSlidingWindowReactiveRequestRateLimiterTest { @RegisterExtension
// Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/extensions/RedisClusterConnectionSetupExtension.java // public class RedisClusterConnectionSetupExtension implements // BeforeAllCallback, AfterAllCallback, AfterEachCallback { // // private static RedisClusterClient client; // private static StatefulRedisClusterConnection<String, String> connect; // private static RedisAdvancedClusterReactiveCommands<String, String> reactiveCommands; // // @Override // @SuppressWarnings("FutureReturnValueIgnored") // public void afterAll(ExtensionContext context) { // client.shutdownAsync(); // } // // @Override // public void afterEach(ExtensionContext context) { // connect.sync().flushdb(); // } // // @Override // public void beforeAll(ExtensionContext context) { // client = RedisClusterClient.create("redis://localhost:7000"); // connect = client.connect(); // reactiveCommands = connect.reactive(); // } // // public RedisClusterClient getClient() { // return client; // } // // public RedisScriptingReactiveCommands<String, String> getRedisScriptingReactiveCommands() { // return reactiveCommands; // } // // public RedisKeyReactiveCommands<String, String> getRedisKeyReactiveCommands() { // return reactiveCommands; // } // // } // Path: ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/reactive/RedisClusterSlidingWindowReactiveRequestRateLimiterTest.java import es.moki.ratelimitj.redis.extensions.RedisClusterConnectionSetupExtension; import io.lettuce.core.api.reactive.RedisKeyReactiveCommands; import io.lettuce.core.api.reactive.RedisScriptingReactiveCommands; import org.junit.jupiter.api.extension.RegisterExtension; package es.moki.ratelimitj.redis.request.reactive; public class RedisClusterSlidingWindowReactiveRequestRateLimiterTest extends RedisSlidingWindowReactiveRequestRateLimiterTest { @RegisterExtension
static RedisClusterConnectionSetupExtension extension = new RedisClusterConnectionSetupExtension();
xspec/xspec-maven-plugin-1
src/test/java/io/xspec/maven/xspecMavenPlugin/resources/impl/DefaultSchematronImplResourcesTest.java
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/SchematronImplResources.java // public interface SchematronImplResources { // // /** // * Usually iso_dsdl_include.xsl // * @return Schematron ISO dsdl include URI // */ // public String getSchIsoDsdlIncludeUri(); // // /** // * Usually iso_abstract_expand.xsl // * @return Schematron ISO abstract expand URI // */ // public String getSchIsoAbstractExpandUri(); // // /** // * Usuall iso_svrl_for_xslt2.xsl // * @return Schematron ISO Svrl for XSLT includes URI // */ // public String getSchIsoSvrlForXslt2Uri(); // // }
import io.xspec.maven.xspecMavenPlugin.resources.SchematronImplResources; import static org.junit.Assert.*; import org.junit.Test;
/** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.resources.impl; /** * Tests {@link DefaultSchematronImplResources} * @author cmarchand */ public class DefaultSchematronImplResourcesTest { @Test public void testClassImplementsInterface() { DefaultSchematronImplResources impl = new DefaultSchematronImplResources();
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/SchematronImplResources.java // public interface SchematronImplResources { // // /** // * Usually iso_dsdl_include.xsl // * @return Schematron ISO dsdl include URI // */ // public String getSchIsoDsdlIncludeUri(); // // /** // * Usually iso_abstract_expand.xsl // * @return Schematron ISO abstract expand URI // */ // public String getSchIsoAbstractExpandUri(); // // /** // * Usuall iso_svrl_for_xslt2.xsl // * @return Schematron ISO Svrl for XSLT includes URI // */ // public String getSchIsoSvrlForXslt2Uri(); // // } // Path: src/test/java/io/xspec/maven/xspecMavenPlugin/resources/impl/DefaultSchematronImplResourcesTest.java import io.xspec.maven.xspecMavenPlugin.resources.SchematronImplResources; import static org.junit.Assert.*; import org.junit.Test; /** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.resources.impl; /** * Tests {@link DefaultSchematronImplResources} * @author cmarchand */ public class DefaultSchematronImplResourcesTest { @Test public void testClassImplementsInterface() { DefaultSchematronImplResources impl = new DefaultSchematronImplResources();
assertTrue("Class does not implement interface", (impl instanceof SchematronImplResources));
xspec/xspec-maven-plugin-1
src/test/java/io/xspec/maven/xspecMavenPlugin/resources/impl/DefaultXSpecPluginResourcesTest.java
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/XSpecPluginResources.java // public interface XSpecPluginResources { // public static final String XML_UTILITIES_PREFIX = "cp:/"; // public static final String LOCAL_PREFIX = "cp:/"; // public static final String CATALOG_NS = "urn:oasis:names:tc:entity:xmlns:xml:catalog"; // // /** // * Returns URI for dependency scanner utility // * @return Dependency scanner URI // */ // public String getDependencyScannerUri(); // /** // * Image Down for folding report // * @return // */ // public String getImageDown(); // // /** // * Image Up for folding report // * @return // */ // public String getImageUp(); // // /** // * XSL that changes external images to inline images in folding report // * @return // */ // public String getXsltImageChanger(); // }
import io.xspec.maven.xspecMavenPlugin.resources.XSpecPluginResources; import static org.junit.Assert.*; import org.junit.Test;
/** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.resources.impl; /** * Tests {@link DefaultXSpecPluginResources} * @author cmarchand */ public class DefaultXSpecPluginResourcesTest { @Test public void testClassImplementsInterface() { DefaultXSpecPluginResources impl = new DefaultXSpecPluginResources();
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/XSpecPluginResources.java // public interface XSpecPluginResources { // public static final String XML_UTILITIES_PREFIX = "cp:/"; // public static final String LOCAL_PREFIX = "cp:/"; // public static final String CATALOG_NS = "urn:oasis:names:tc:entity:xmlns:xml:catalog"; // // /** // * Returns URI for dependency scanner utility // * @return Dependency scanner URI // */ // public String getDependencyScannerUri(); // /** // * Image Down for folding report // * @return // */ // public String getImageDown(); // // /** // * Image Up for folding report // * @return // */ // public String getImageUp(); // // /** // * XSL that changes external images to inline images in folding report // * @return // */ // public String getXsltImageChanger(); // } // Path: src/test/java/io/xspec/maven/xspecMavenPlugin/resources/impl/DefaultXSpecPluginResourcesTest.java import io.xspec.maven.xspecMavenPlugin.resources.XSpecPluginResources; import static org.junit.Assert.*; import org.junit.Test; /** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.resources.impl; /** * Tests {@link DefaultXSpecPluginResources} * @author cmarchand */ public class DefaultXSpecPluginResourcesTest { @Test public void testClassImplementsInterface() { DefaultXSpecPluginResources impl = new DefaultXSpecPluginResources();
assertTrue("class does not implements interface", (impl instanceof XSpecPluginResources));
xspec/xspec-maven-plugin-1
src/main/java/io/xspec/maven/xspecMavenPlugin/resolver/Resolver.java
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/utils/QuietLogger.java // public class QuietLogger extends SystemStreamLog { // private static QuietLogger INSTANCE; // // public static QuietLogger getLogger() { // if(INSTANCE==null) { // INSTANCE = new QuietLogger(); // } // return INSTANCE; // } // // private QuietLogger() { // super(); // } // // @Override // public boolean isDebugEnabled() { // return false; // } // // @Override // public void debug(CharSequence cs) { } // // @Override // public void debug(CharSequence cs, Throwable thrwbl) { } // // @Override // public void debug(Throwable thrwbl) { } // // @Override // public boolean isInfoEnabled() { // return false; // } // // @Override // public void info(CharSequence cs) { } // // @Override // public void info(CharSequence cs, Throwable thrwbl) { } // // @Override // public void info(Throwable thrwbl) { } // // @Override // public boolean isWarnEnabled() { // return false; // } // // @Override // public void warn(CharSequence cs) { } // // @Override // public void warn(CharSequence cs, Throwable thrwbl) { } // // @Override // public void warn(Throwable thrwbl) { } // // @Override // public boolean isErrorEnabled() { // return true; // } // // }
import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Pattern; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.apache.maven.plugin.logging.Log; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xmlresolver.Catalog; import org.xmlresolver.CatalogSource; import com.google.common.base.CharMatcher; import io.xspec.maven.xspecMavenPlugin.utils.QuietLogger; import java.io.File; import java.io.IOException;
private boolean isCpProtocol(String href, String base) { return (href!=null && href.startsWith("cp:/")) || (base!=null && base.startsWith("cp:/")); } private Source resolveToClasspath(String href, String base) { String fullUrl = isAbsolute(href) ? href : base+href; String path = removeCpPrefix(fullUrl); InputStream is = getClass().getResourceAsStream(path); if(is==null) { return null; } StreamSource ret = new StreamSource(is); String systemId = getClass().getResource(path).toExternalForm(); log.warn(systemId); ret.setSystemId(normalizeUrl(systemId)); return ret; } private boolean isAbsolute(String href) { return protocolPattern.matcher(href).matches(); } private String removeCpPrefix(String fullUrl) { return fullUrl.substring(3); } private Log getLog() { if(LOG_ENABLE) return log;
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/utils/QuietLogger.java // public class QuietLogger extends SystemStreamLog { // private static QuietLogger INSTANCE; // // public static QuietLogger getLogger() { // if(INSTANCE==null) { // INSTANCE = new QuietLogger(); // } // return INSTANCE; // } // // private QuietLogger() { // super(); // } // // @Override // public boolean isDebugEnabled() { // return false; // } // // @Override // public void debug(CharSequence cs) { } // // @Override // public void debug(CharSequence cs, Throwable thrwbl) { } // // @Override // public void debug(Throwable thrwbl) { } // // @Override // public boolean isInfoEnabled() { // return false; // } // // @Override // public void info(CharSequence cs) { } // // @Override // public void info(CharSequence cs, Throwable thrwbl) { } // // @Override // public void info(Throwable thrwbl) { } // // @Override // public boolean isWarnEnabled() { // return false; // } // // @Override // public void warn(CharSequence cs) { } // // @Override // public void warn(CharSequence cs, Throwable thrwbl) { } // // @Override // public void warn(Throwable thrwbl) { } // // @Override // public boolean isErrorEnabled() { // return true; // } // // } // Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resolver/Resolver.java import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Pattern; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.apache.maven.plugin.logging.Log; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xmlresolver.Catalog; import org.xmlresolver.CatalogSource; import com.google.common.base.CharMatcher; import io.xspec.maven.xspecMavenPlugin.utils.QuietLogger; import java.io.File; import java.io.IOException; private boolean isCpProtocol(String href, String base) { return (href!=null && href.startsWith("cp:/")) || (base!=null && base.startsWith("cp:/")); } private Source resolveToClasspath(String href, String base) { String fullUrl = isAbsolute(href) ? href : base+href; String path = removeCpPrefix(fullUrl); InputStream is = getClass().getResourceAsStream(path); if(is==null) { return null; } StreamSource ret = new StreamSource(is); String systemId = getClass().getResource(path).toExternalForm(); log.warn(systemId); ret.setSystemId(normalizeUrl(systemId)); return ret; } private boolean isAbsolute(String href) { return protocolPattern.matcher(href).matches(); } private String removeCpPrefix(String fullUrl) { return fullUrl.substring(3); } private Log getLog() { if(LOG_ENABLE) return log;
return QuietLogger.getLogger();
xspec/xspec-maven-plugin-1
src/test/java/io/xspec/maven/xspecMavenPlugin/resources/impl/DefaultXSpecImplResourcesTest.java
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/XSpecImplResources.java // public interface XSpecImplResources { // public static final String XSPEC_PREFIX = "cp:/"; // // /** // * Usually, generate-xspec-tests.xsl // * @return XSpec compiler for XSL URI // */ // public String getXSpecXslCompilerUri(); // // /** // * Usually generate-query-tests.xsl // * @return XSpec compiler for XQuery URI // */ // public String getXSpecXQueryCompilerUri(); // // /** // * Usually schut-to-xspec.xsl // * @return XSpec-for-Schematron converter URI // */ // public String getSchematronSchutConverterUri(); // // /** // * Usually format-xspec-report.xsl // * @param useFolding // * @return XSpec reporter URI // */ // public String getXSpecReporterUri(boolean useFolding); // // /** // * Usually coverage-report.xsl // * @return XSpec Code Coverage reporter URI // */ // public String getXSpecCoverageReporterUri(); // // /** // * Usually test-report.css // * @return // */ // public String getXSpecCssReportUri(); // // }
import io.xspec.maven.xspecMavenPlugin.resources.XSpecImplResources; import static org.junit.Assert.*; import org.junit.Test;
/** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.resources.impl; /** * Tests {@link DefaultXSpecImplResources} * @author cmarchand */ public class DefaultXSpecImplResourcesTest { @Test public void testClassImplementsInterface() { DefaultXSpecImplResources impl = new DefaultXSpecImplResources();
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/XSpecImplResources.java // public interface XSpecImplResources { // public static final String XSPEC_PREFIX = "cp:/"; // // /** // * Usually, generate-xspec-tests.xsl // * @return XSpec compiler for XSL URI // */ // public String getXSpecXslCompilerUri(); // // /** // * Usually generate-query-tests.xsl // * @return XSpec compiler for XQuery URI // */ // public String getXSpecXQueryCompilerUri(); // // /** // * Usually schut-to-xspec.xsl // * @return XSpec-for-Schematron converter URI // */ // public String getSchematronSchutConverterUri(); // // /** // * Usually format-xspec-report.xsl // * @param useFolding // * @return XSpec reporter URI // */ // public String getXSpecReporterUri(boolean useFolding); // // /** // * Usually coverage-report.xsl // * @return XSpec Code Coverage reporter URI // */ // public String getXSpecCoverageReporterUri(); // // /** // * Usually test-report.css // * @return // */ // public String getXSpecCssReportUri(); // // } // Path: src/test/java/io/xspec/maven/xspecMavenPlugin/resources/impl/DefaultXSpecImplResourcesTest.java import io.xspec.maven.xspecMavenPlugin.resources.XSpecImplResources; import static org.junit.Assert.*; import org.junit.Test; /** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.resources.impl; /** * Tests {@link DefaultXSpecImplResources} * @author cmarchand */ public class DefaultXSpecImplResourcesTest { @Test public void testClassImplementsInterface() { DefaultXSpecImplResources impl = new DefaultXSpecImplResources();
assertTrue("Class does not implements interface", impl instanceof XSpecImplResources);
xspec/xspec-maven-plugin-1
src/main/java/io/xspec/maven/xspecMavenPlugin/utils/CatalogWriter.java
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/XSpecPluginResources.java // public interface XSpecPluginResources { // public static final String XML_UTILITIES_PREFIX = "cp:/"; // public static final String LOCAL_PREFIX = "cp:/"; // public static final String CATALOG_NS = "urn:oasis:names:tc:entity:xmlns:xml:catalog"; // // /** // * Returns URI for dependency scanner utility // * @return Dependency scanner URI // */ // public String getDependencyScannerUri(); // /** // * Image Down for folding report // * @return // */ // public String getImageDown(); // // /** // * Image Up for folding report // * @return // */ // public String getImageUp(); // // /** // * XSL that changes external images to inline images in folding report // * @return // */ // public String getXsltImageChanger(); // }
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.Properties; import io.xspec.maven.xspecMavenPlugin.resources.XSpecPluginResources; import javanet.staxutils.IndentingXMLStreamWriter; import javax.xml.stream.XMLOutputFactory;
/** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.utils; /** * This class writes a catalog * @author cmarchand */ public class CatalogWriter { public CatalogWriter(ClassLoader cl) throws XSpecPluginException { super(); } /** * Generates and write a catalog that resolves all resources for XSpec, * schematron and plugin implementation. If XSpec execution requires a user * defined catalog, it may be specified in <tt>userCatalogFileName</tt>.<br/> * <tt>userCatalogFileName</tt> may be null ; no <tt>&lt;nextCatalog&gt;</tt> * entry will be added to generated catalog.<br/> * If a non null value is provided for <tt>userCatalogFileName</tt>, then * a non null value <strong>must</strong> be provided for <tt>environment</tt> ; * else, a IllegalArgumentException will be thrown. * @param userCatalogFilename The nextCatalog URI to add to generated catalog. * @param environment Environment properties, used to resolve all placeholders * in <tt>userCatalogFileName</tt>. * @param keepGeneratedCatalog Indicates if generated catalog must be kept after * plugin execution. If <tt>false</tt>, generated catalog will be deleted at * JVM exit. * @return Generated file * @throws XSpecPluginException * @throws IOException */ public File writeCatalog(String userCatalogFilename, Properties environment, boolean keepGeneratedCatalog) throws XSpecPluginException, IOException, IllegalArgumentException { if(userCatalogFilename!=null && environment==null) { throw new IllegalArgumentException("If you specify a userCatalogFilename, you must provide a non null environment."); } File tmpCatalog = File.createTempFile("tmp", "-catalog.xml"); try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(tmpCatalog), Charset.forName("UTF-8"))) { XMLStreamWriter xmlWriter = XMLOutputFactory.newFactory().createXMLStreamWriter(osw); xmlWriter = new IndentingXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("UTF-8", "1.0"); xmlWriter.writeStartElement("catalog");
// Path: src/main/java/io/xspec/maven/xspecMavenPlugin/resources/XSpecPluginResources.java // public interface XSpecPluginResources { // public static final String XML_UTILITIES_PREFIX = "cp:/"; // public static final String LOCAL_PREFIX = "cp:/"; // public static final String CATALOG_NS = "urn:oasis:names:tc:entity:xmlns:xml:catalog"; // // /** // * Returns URI for dependency scanner utility // * @return Dependency scanner URI // */ // public String getDependencyScannerUri(); // /** // * Image Down for folding report // * @return // */ // public String getImageDown(); // // /** // * Image Up for folding report // * @return // */ // public String getImageUp(); // // /** // * XSL that changes external images to inline images in folding report // * @return // */ // public String getXsltImageChanger(); // } // Path: src/main/java/io/xspec/maven/xspecMavenPlugin/utils/CatalogWriter.java import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.Properties; import io.xspec.maven.xspecMavenPlugin.resources.XSpecPluginResources; import javanet.staxutils.IndentingXMLStreamWriter; import javax.xml.stream.XMLOutputFactory; /** * Copyright © 2018, Christophe Marchand, XSpec organization * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.xspec.maven.xspecMavenPlugin.utils; /** * This class writes a catalog * @author cmarchand */ public class CatalogWriter { public CatalogWriter(ClassLoader cl) throws XSpecPluginException { super(); } /** * Generates and write a catalog that resolves all resources for XSpec, * schematron and plugin implementation. If XSpec execution requires a user * defined catalog, it may be specified in <tt>userCatalogFileName</tt>.<br/> * <tt>userCatalogFileName</tt> may be null ; no <tt>&lt;nextCatalog&gt;</tt> * entry will be added to generated catalog.<br/> * If a non null value is provided for <tt>userCatalogFileName</tt>, then * a non null value <strong>must</strong> be provided for <tt>environment</tt> ; * else, a IllegalArgumentException will be thrown. * @param userCatalogFilename The nextCatalog URI to add to generated catalog. * @param environment Environment properties, used to resolve all placeholders * in <tt>userCatalogFileName</tt>. * @param keepGeneratedCatalog Indicates if generated catalog must be kept after * plugin execution. If <tt>false</tt>, generated catalog will be deleted at * JVM exit. * @return Generated file * @throws XSpecPluginException * @throws IOException */ public File writeCatalog(String userCatalogFilename, Properties environment, boolean keepGeneratedCatalog) throws XSpecPluginException, IOException, IllegalArgumentException { if(userCatalogFilename!=null && environment==null) { throw new IllegalArgumentException("If you specify a userCatalogFilename, you must provide a non null environment."); } File tmpCatalog = File.createTempFile("tmp", "-catalog.xml"); try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(tmpCatalog), Charset.forName("UTF-8"))) { XMLStreamWriter xmlWriter = XMLOutputFactory.newFactory().createXMLStreamWriter(osw); xmlWriter = new IndentingXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("UTF-8", "1.0"); xmlWriter.writeStartElement("catalog");
xmlWriter.setDefaultNamespace(XSpecPluginResources.CATALOG_NS);