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
|
---|---|---|---|---|---|---|
Talon876/RSIRCBot | src/org/nolat/rsircbot/settings/Settings.java | // Path: src/org/nolat/rsircbot/settings/json/BotSettings.java
// public class BotSettings {
// private String name;
// private String server;
// private int port;
// private boolean debug;
// private String broadcast_tag;
// private String wit_token;
// private int message_count;
// private int command_count;
// private List<Channel> channels;
// private List<User> users;
// private List<String> feedback;
//
// public String getName() {
// return name;
// }
//
// public String getServer() {
// return server;
// }
//
// public int getPort() {
// return port;
// }
//
// public boolean isDebug() {
// return debug;
// }
//
// public String getBroadcastTag() {
// return broadcast_tag;
// }
//
// public String getWitToken() {
// return wit_token;
// }
//
// public List<Channel> getChannels() {
// return channels;
// }
//
// public List<User> getUsers() {
// return users;
// }
//
// public String getQotd(String channel) {
// Channel c = getChannel(channel);
// if (c != null) {
// return c.getQotdMessage();
// } else {
// return "";
// }
// }
//
// public Channel getChannel(String name) {
// for (Channel c : channels) {
// if (c.getName().equalsIgnoreCase(name)) {
// return c;
// }
// }
// return null;
// }
//
// public User getUser(String name) {
// for (User u : users) {
// if (u.getName().equalsIgnoreCase(name)) {
// return u;
// }
// }
// return null;
// }
//
// public void addChannel(Channel c) {
// channels.add(c);
// }
//
// public void addUser(User u) {
// users.add(u);
// }
//
// public void removeChannel(String channel) {
// channels.remove(getChannel(channel));
// }
//
// public int getMessageCount() {
// return message_count;
// }
//
// public int getCommandCount() {
// return command_count;
// }
//
// public void increaseMessageCount() {
// message_count++;
// }
//
// public void increaseCommandCount() {
// command_count++;
// }
//
// public void addFeedback(String fb) {
// if (feedback != null) {
// feedback.add(fb);
// } else {
// feedback = new ArrayList<String>();
// feedback.add(fb);
// }
//
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/Channel.java
// public class Channel {
// String name;
// boolean greeting;
// HashMap<String, String> qotd;
//
// public Channel(String name, boolean showGreeting, boolean showQotd, String qotdMsg) {
// this.name = name;
// greeting = showGreeting;
// qotd = new HashMap<String, String>();
// qotd.put("message", qotdMsg);
// qotd.put("display", Boolean.toString(greeting));
// }
//
// public String getQotdMessage() {
// return qotd.get("message");
// }
//
// public boolean shouldDisplayQotd() {
// return Boolean.parseBoolean(qotd.get("display"));
// }
//
// public String getName() {
// return name;
// }
//
// public boolean shouldDisplayGreeting() {
// return greeting;
// }
//
// public void setQotd(String message) {
// qotd.put("message", message);
// }
//
// public void toggleQotd() {
// boolean showQotd = !Boolean.parseBoolean(qotd.get("display"));
// qotd.put("display", Boolean.toString(showQotd));
// }
//
// public void toggleGreeting() {
// greeting = !greeting;
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/User.java
// public class User {
// String name;
// String rsn;
//
// public User(String name, String rsn) {
// this.name = name;
// this.rsn = rsn;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRSN() {
// return rsn;
// }
//
// public void setRSN(String rsn) {
// this.rsn = rsn;
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/FileReader.java
// public class FileReader {
// public static String readFile(String pathname) throws IOException {
//
// File file = new File(pathname);
// StringBuilder fileContents = new StringBuilder((int) file.length());
// Scanner scanner = new Scanner(file);
// String lineSeparator = System.getProperty("line.separator");
//
// try {
// while (scanner.hasNextLine()) {
// fileContents.append(scanner.nextLine() + lineSeparator);
// }
// return fileContents.toString();
// } finally {
// scanner.close();
// }
// }
//
// public static void writeFile(String path, String contents) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(path);
// out.println(contents);
// out.flush();
// out.close();
// }
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.nolat.rsircbot.settings.json.BotSettings;
import org.nolat.rsircbot.settings.json.Channel;
import org.nolat.rsircbot.settings.json.User;
import org.nolat.rsircbot.tools.FileReader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder; | package org.nolat.rsircbot.settings;
public class Settings {
File settingsFile;
String jsonData; | // Path: src/org/nolat/rsircbot/settings/json/BotSettings.java
// public class BotSettings {
// private String name;
// private String server;
// private int port;
// private boolean debug;
// private String broadcast_tag;
// private String wit_token;
// private int message_count;
// private int command_count;
// private List<Channel> channels;
// private List<User> users;
// private List<String> feedback;
//
// public String getName() {
// return name;
// }
//
// public String getServer() {
// return server;
// }
//
// public int getPort() {
// return port;
// }
//
// public boolean isDebug() {
// return debug;
// }
//
// public String getBroadcastTag() {
// return broadcast_tag;
// }
//
// public String getWitToken() {
// return wit_token;
// }
//
// public List<Channel> getChannels() {
// return channels;
// }
//
// public List<User> getUsers() {
// return users;
// }
//
// public String getQotd(String channel) {
// Channel c = getChannel(channel);
// if (c != null) {
// return c.getQotdMessage();
// } else {
// return "";
// }
// }
//
// public Channel getChannel(String name) {
// for (Channel c : channels) {
// if (c.getName().equalsIgnoreCase(name)) {
// return c;
// }
// }
// return null;
// }
//
// public User getUser(String name) {
// for (User u : users) {
// if (u.getName().equalsIgnoreCase(name)) {
// return u;
// }
// }
// return null;
// }
//
// public void addChannel(Channel c) {
// channels.add(c);
// }
//
// public void addUser(User u) {
// users.add(u);
// }
//
// public void removeChannel(String channel) {
// channels.remove(getChannel(channel));
// }
//
// public int getMessageCount() {
// return message_count;
// }
//
// public int getCommandCount() {
// return command_count;
// }
//
// public void increaseMessageCount() {
// message_count++;
// }
//
// public void increaseCommandCount() {
// command_count++;
// }
//
// public void addFeedback(String fb) {
// if (feedback != null) {
// feedback.add(fb);
// } else {
// feedback = new ArrayList<String>();
// feedback.add(fb);
// }
//
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/Channel.java
// public class Channel {
// String name;
// boolean greeting;
// HashMap<String, String> qotd;
//
// public Channel(String name, boolean showGreeting, boolean showQotd, String qotdMsg) {
// this.name = name;
// greeting = showGreeting;
// qotd = new HashMap<String, String>();
// qotd.put("message", qotdMsg);
// qotd.put("display", Boolean.toString(greeting));
// }
//
// public String getQotdMessage() {
// return qotd.get("message");
// }
//
// public boolean shouldDisplayQotd() {
// return Boolean.parseBoolean(qotd.get("display"));
// }
//
// public String getName() {
// return name;
// }
//
// public boolean shouldDisplayGreeting() {
// return greeting;
// }
//
// public void setQotd(String message) {
// qotd.put("message", message);
// }
//
// public void toggleQotd() {
// boolean showQotd = !Boolean.parseBoolean(qotd.get("display"));
// qotd.put("display", Boolean.toString(showQotd));
// }
//
// public void toggleGreeting() {
// greeting = !greeting;
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/User.java
// public class User {
// String name;
// String rsn;
//
// public User(String name, String rsn) {
// this.name = name;
// this.rsn = rsn;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRSN() {
// return rsn;
// }
//
// public void setRSN(String rsn) {
// this.rsn = rsn;
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/FileReader.java
// public class FileReader {
// public static String readFile(String pathname) throws IOException {
//
// File file = new File(pathname);
// StringBuilder fileContents = new StringBuilder((int) file.length());
// Scanner scanner = new Scanner(file);
// String lineSeparator = System.getProperty("line.separator");
//
// try {
// while (scanner.hasNextLine()) {
// fileContents.append(scanner.nextLine() + lineSeparator);
// }
// return fileContents.toString();
// } finally {
// scanner.close();
// }
// }
//
// public static void writeFile(String path, String contents) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(path);
// out.println(contents);
// out.flush();
// out.close();
// }
// }
// Path: src/org/nolat/rsircbot/settings/Settings.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.nolat.rsircbot.settings.json.BotSettings;
import org.nolat.rsircbot.settings.json.Channel;
import org.nolat.rsircbot.settings.json.User;
import org.nolat.rsircbot.tools.FileReader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
package org.nolat.rsircbot.settings;
public class Settings {
File settingsFile;
String jsonData; | BotSettings settings; |
Talon876/RSIRCBot | src/org/nolat/rsircbot/settings/Settings.java | // Path: src/org/nolat/rsircbot/settings/json/BotSettings.java
// public class BotSettings {
// private String name;
// private String server;
// private int port;
// private boolean debug;
// private String broadcast_tag;
// private String wit_token;
// private int message_count;
// private int command_count;
// private List<Channel> channels;
// private List<User> users;
// private List<String> feedback;
//
// public String getName() {
// return name;
// }
//
// public String getServer() {
// return server;
// }
//
// public int getPort() {
// return port;
// }
//
// public boolean isDebug() {
// return debug;
// }
//
// public String getBroadcastTag() {
// return broadcast_tag;
// }
//
// public String getWitToken() {
// return wit_token;
// }
//
// public List<Channel> getChannels() {
// return channels;
// }
//
// public List<User> getUsers() {
// return users;
// }
//
// public String getQotd(String channel) {
// Channel c = getChannel(channel);
// if (c != null) {
// return c.getQotdMessage();
// } else {
// return "";
// }
// }
//
// public Channel getChannel(String name) {
// for (Channel c : channels) {
// if (c.getName().equalsIgnoreCase(name)) {
// return c;
// }
// }
// return null;
// }
//
// public User getUser(String name) {
// for (User u : users) {
// if (u.getName().equalsIgnoreCase(name)) {
// return u;
// }
// }
// return null;
// }
//
// public void addChannel(Channel c) {
// channels.add(c);
// }
//
// public void addUser(User u) {
// users.add(u);
// }
//
// public void removeChannel(String channel) {
// channels.remove(getChannel(channel));
// }
//
// public int getMessageCount() {
// return message_count;
// }
//
// public int getCommandCount() {
// return command_count;
// }
//
// public void increaseMessageCount() {
// message_count++;
// }
//
// public void increaseCommandCount() {
// command_count++;
// }
//
// public void addFeedback(String fb) {
// if (feedback != null) {
// feedback.add(fb);
// } else {
// feedback = new ArrayList<String>();
// feedback.add(fb);
// }
//
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/Channel.java
// public class Channel {
// String name;
// boolean greeting;
// HashMap<String, String> qotd;
//
// public Channel(String name, boolean showGreeting, boolean showQotd, String qotdMsg) {
// this.name = name;
// greeting = showGreeting;
// qotd = new HashMap<String, String>();
// qotd.put("message", qotdMsg);
// qotd.put("display", Boolean.toString(greeting));
// }
//
// public String getQotdMessage() {
// return qotd.get("message");
// }
//
// public boolean shouldDisplayQotd() {
// return Boolean.parseBoolean(qotd.get("display"));
// }
//
// public String getName() {
// return name;
// }
//
// public boolean shouldDisplayGreeting() {
// return greeting;
// }
//
// public void setQotd(String message) {
// qotd.put("message", message);
// }
//
// public void toggleQotd() {
// boolean showQotd = !Boolean.parseBoolean(qotd.get("display"));
// qotd.put("display", Boolean.toString(showQotd));
// }
//
// public void toggleGreeting() {
// greeting = !greeting;
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/User.java
// public class User {
// String name;
// String rsn;
//
// public User(String name, String rsn) {
// this.name = name;
// this.rsn = rsn;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRSN() {
// return rsn;
// }
//
// public void setRSN(String rsn) {
// this.rsn = rsn;
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/FileReader.java
// public class FileReader {
// public static String readFile(String pathname) throws IOException {
//
// File file = new File(pathname);
// StringBuilder fileContents = new StringBuilder((int) file.length());
// Scanner scanner = new Scanner(file);
// String lineSeparator = System.getProperty("line.separator");
//
// try {
// while (scanner.hasNextLine()) {
// fileContents.append(scanner.nextLine() + lineSeparator);
// }
// return fileContents.toString();
// } finally {
// scanner.close();
// }
// }
//
// public static void writeFile(String path, String contents) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(path);
// out.println(contents);
// out.flush();
// out.close();
// }
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.nolat.rsircbot.settings.json.BotSettings;
import org.nolat.rsircbot.settings.json.Channel;
import org.nolat.rsircbot.settings.json.User;
import org.nolat.rsircbot.tools.FileReader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder; | package org.nolat.rsircbot.settings;
public class Settings {
File settingsFile;
String jsonData;
BotSettings settings;
public Settings(String path) throws SettingsException {
File f = new File(path);
if (f.exists() && f.isFile()) {
settingsFile = f;
try { | // Path: src/org/nolat/rsircbot/settings/json/BotSettings.java
// public class BotSettings {
// private String name;
// private String server;
// private int port;
// private boolean debug;
// private String broadcast_tag;
// private String wit_token;
// private int message_count;
// private int command_count;
// private List<Channel> channels;
// private List<User> users;
// private List<String> feedback;
//
// public String getName() {
// return name;
// }
//
// public String getServer() {
// return server;
// }
//
// public int getPort() {
// return port;
// }
//
// public boolean isDebug() {
// return debug;
// }
//
// public String getBroadcastTag() {
// return broadcast_tag;
// }
//
// public String getWitToken() {
// return wit_token;
// }
//
// public List<Channel> getChannels() {
// return channels;
// }
//
// public List<User> getUsers() {
// return users;
// }
//
// public String getQotd(String channel) {
// Channel c = getChannel(channel);
// if (c != null) {
// return c.getQotdMessage();
// } else {
// return "";
// }
// }
//
// public Channel getChannel(String name) {
// for (Channel c : channels) {
// if (c.getName().equalsIgnoreCase(name)) {
// return c;
// }
// }
// return null;
// }
//
// public User getUser(String name) {
// for (User u : users) {
// if (u.getName().equalsIgnoreCase(name)) {
// return u;
// }
// }
// return null;
// }
//
// public void addChannel(Channel c) {
// channels.add(c);
// }
//
// public void addUser(User u) {
// users.add(u);
// }
//
// public void removeChannel(String channel) {
// channels.remove(getChannel(channel));
// }
//
// public int getMessageCount() {
// return message_count;
// }
//
// public int getCommandCount() {
// return command_count;
// }
//
// public void increaseMessageCount() {
// message_count++;
// }
//
// public void increaseCommandCount() {
// command_count++;
// }
//
// public void addFeedback(String fb) {
// if (feedback != null) {
// feedback.add(fb);
// } else {
// feedback = new ArrayList<String>();
// feedback.add(fb);
// }
//
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/Channel.java
// public class Channel {
// String name;
// boolean greeting;
// HashMap<String, String> qotd;
//
// public Channel(String name, boolean showGreeting, boolean showQotd, String qotdMsg) {
// this.name = name;
// greeting = showGreeting;
// qotd = new HashMap<String, String>();
// qotd.put("message", qotdMsg);
// qotd.put("display", Boolean.toString(greeting));
// }
//
// public String getQotdMessage() {
// return qotd.get("message");
// }
//
// public boolean shouldDisplayQotd() {
// return Boolean.parseBoolean(qotd.get("display"));
// }
//
// public String getName() {
// return name;
// }
//
// public boolean shouldDisplayGreeting() {
// return greeting;
// }
//
// public void setQotd(String message) {
// qotd.put("message", message);
// }
//
// public void toggleQotd() {
// boolean showQotd = !Boolean.parseBoolean(qotd.get("display"));
// qotd.put("display", Boolean.toString(showQotd));
// }
//
// public void toggleGreeting() {
// greeting = !greeting;
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/json/User.java
// public class User {
// String name;
// String rsn;
//
// public User(String name, String rsn) {
// this.name = name;
// this.rsn = rsn;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRSN() {
// return rsn;
// }
//
// public void setRSN(String rsn) {
// this.rsn = rsn;
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/FileReader.java
// public class FileReader {
// public static String readFile(String pathname) throws IOException {
//
// File file = new File(pathname);
// StringBuilder fileContents = new StringBuilder((int) file.length());
// Scanner scanner = new Scanner(file);
// String lineSeparator = System.getProperty("line.separator");
//
// try {
// while (scanner.hasNextLine()) {
// fileContents.append(scanner.nextLine() + lineSeparator);
// }
// return fileContents.toString();
// } finally {
// scanner.close();
// }
// }
//
// public static void writeFile(String path, String contents) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(path);
// out.println(contents);
// out.flush();
// out.close();
// }
// }
// Path: src/org/nolat/rsircbot/settings/Settings.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.nolat.rsircbot.settings.json.BotSettings;
import org.nolat.rsircbot.settings.json.Channel;
import org.nolat.rsircbot.settings.json.User;
import org.nolat.rsircbot.tools.FileReader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
package org.nolat.rsircbot.settings;
public class Settings {
File settingsFile;
String jsonData;
BotSettings settings;
public Settings(String path) throws SettingsException {
File f = new File(path);
if (f.exists() && f.isFile()) {
settingsFile = f;
try { | jsonData = FileReader.readFile(path); |
Talon876/RSIRCBot | src/org/nolat/rsircbot/data/json/OfferData.java | // Path: src/org/nolat/rsircbot/tools/RSFormatter.java
// public class RSFormatter {
// public static final DecimalFormat formatter = new DecimalFormat("#,###");
//
// public static String format(int num) {
// return formatter.format(num);
// }
//
// public static String format(double num) {
// return formatter.format(num);
// }
//
// public static String format(String string) {
// return format(Float.parseFloat(string));
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import org.nolat.rsircbot.tools.RSFormatter; | package org.nolat.rsircbot.data.json;
public class OfferData {
String date;
String price;
String quantity;
String rs_name;
String selling;
public boolean isSelling() {
return selling.equals("1");
}
public String getDateString() {
Date d = new Date(Long.parseLong(date) * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm a (Z)");
return sdf.format(d);
}
public Date getDate() {
Date d = new Date(Long.parseLong(date) * 1000);
return d;
}
public String getRSN() {
return rs_name;
}
public String getQuantityString() { | // Path: src/org/nolat/rsircbot/tools/RSFormatter.java
// public class RSFormatter {
// public static final DecimalFormat formatter = new DecimalFormat("#,###");
//
// public static String format(int num) {
// return formatter.format(num);
// }
//
// public static String format(double num) {
// return formatter.format(num);
// }
//
// public static String format(String string) {
// return format(Float.parseFloat(string));
// }
// }
// Path: src/org/nolat/rsircbot/data/json/OfferData.java
import java.text.SimpleDateFormat;
import java.util.Date;
import org.nolat.rsircbot.tools.RSFormatter;
package org.nolat.rsircbot.data.json;
public class OfferData {
String date;
String price;
String quantity;
String rs_name;
String selling;
public boolean isSelling() {
return selling.equals("1");
}
public String getDateString() {
Date d = new Date(Long.parseLong(date) * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm a (Z)");
return sdf.format(d);
}
public Date getDate() {
Date d = new Date(Long.parseLong(date) * 1000);
return d;
}
public String getRSN() {
return rs_name;
}
public String getQuantityString() { | return RSFormatter.format(quantity); |
Talon876/RSIRCBot | src/org/nolat/rsircbot/CommandExecutor.java | // Path: src/org/nolat/rsircbot/commands/Command.java
// public abstract class Command {
// public static ArrayList<Command> commands = new ArrayList<Command>();
// static {
// new HelpCommand();
// new HiscoreCommand();
// new CombatCommand();
// new XPForLevelCommand();
// new MapCommand();
// new QotdCommand();
// new BotStatsCommand();
// new ToggleCommand();
// new FeedbackCommand();
// new BroadcastCommand();
// new CompareCommand();
// new RSNCommand();
// new PriceCommand();
// new WTSCommand();
// new WTBCommand();
// new CalcCommand();
// new AlchCommand();
// new BitcoinCommand();
// new WoMCommand();
// }
//
// private boolean privateReply = true;
//
// String command;
//
// String argString;
//
// ArrayList<String> alternativeCommands;
//
// String helpMessage;
//
// public Command(String command) {
// this.command = command;
// Command.commands.add(this);
// System.out.println("Registered command: " + command);
// alternativeCommands = new ArrayList<String>();
// argString = "";
// }
//
// public void addAlternativeCommand(String altCommand) {
// alternativeCommands.add(altCommand);
// }
//
// public String getCommand() {
// return command;
// }
//
// public String getHelpMessage() {
// return helpMessage;
// }
//
// public void setHelpMessage(String helpMessage) {
// this.helpMessage = helpMessage;
// }
//
// public String getArgString() {
// return argString;
// }
//
// public String getUsageString() {
// return "Usage: " + command + " " + argString;
// }
//
// public boolean isPrivateReply() {
// return privateReply;
// }
//
// public void setPrivateReply(boolean privateReply) {
// this.privateReply = privateReply;
// }
//
// public void setArgString(String argString) {
// this.argString = argString;
// }
//
// /**
// * Check if a string matches this command's string or an alternative string.
// *
// * @param msg
// * The message to check
// * @return true if this string matches the command
// */
// public boolean matchesString(String msg) {
// boolean matches = false;
// matches = matches || msg.equalsIgnoreCase(command);
// for (String cmd : alternativeCommands) {
// matches = matches || msg.equalsIgnoreCase(cmd);
// }
// return matches;
// }
//
// /**
// * Executes the command with the given arguments
// *
// * @param bot
// * the bot used to send messages
// * @param channel
// * the channel the request came from
// * @param executor
// * The name of the person who executed the command
// * @param message
// * the unmodified message containing the command
// */
// public abstract void executeCommand(RSIRCBot bot, String channel, String executor, String message);
//
// /**
// * Finds the Command object
// *
// * @param message
// * @return
// */
// public static Command getCommand(String message) {
// Command cmd = null;
// if (message.length() > 1 && !message.startsWith(" ")) {
// String[] tokens = message.split(" ");
// String commandString = tokens[0];
// boolean privateReply = true;
// if (commandString.startsWith("!") || commandString.startsWith(".")) {
// privateReply = true;
// } else if (commandString.startsWith("@")) {
// privateReply = false;
// }
// commandString = tokens[0].substring(1, tokens[0].length());
// for (Command c : commands) {
// if (c.matchesString(commandString)) {
// cmd = c;
// cmd.setPrivateReply(privateReply);
// break;
// }
// }
// }
// return cmd;
// }
// }
| import org.nolat.rsircbot.commands.Command; | package org.nolat.rsircbot;
public class CommandExecutor implements Runnable {
private final RSIRCBot bot;
private final String target;
private final String sender;
private final String message; | // Path: src/org/nolat/rsircbot/commands/Command.java
// public abstract class Command {
// public static ArrayList<Command> commands = new ArrayList<Command>();
// static {
// new HelpCommand();
// new HiscoreCommand();
// new CombatCommand();
// new XPForLevelCommand();
// new MapCommand();
// new QotdCommand();
// new BotStatsCommand();
// new ToggleCommand();
// new FeedbackCommand();
// new BroadcastCommand();
// new CompareCommand();
// new RSNCommand();
// new PriceCommand();
// new WTSCommand();
// new WTBCommand();
// new CalcCommand();
// new AlchCommand();
// new BitcoinCommand();
// new WoMCommand();
// }
//
// private boolean privateReply = true;
//
// String command;
//
// String argString;
//
// ArrayList<String> alternativeCommands;
//
// String helpMessage;
//
// public Command(String command) {
// this.command = command;
// Command.commands.add(this);
// System.out.println("Registered command: " + command);
// alternativeCommands = new ArrayList<String>();
// argString = "";
// }
//
// public void addAlternativeCommand(String altCommand) {
// alternativeCommands.add(altCommand);
// }
//
// public String getCommand() {
// return command;
// }
//
// public String getHelpMessage() {
// return helpMessage;
// }
//
// public void setHelpMessage(String helpMessage) {
// this.helpMessage = helpMessage;
// }
//
// public String getArgString() {
// return argString;
// }
//
// public String getUsageString() {
// return "Usage: " + command + " " + argString;
// }
//
// public boolean isPrivateReply() {
// return privateReply;
// }
//
// public void setPrivateReply(boolean privateReply) {
// this.privateReply = privateReply;
// }
//
// public void setArgString(String argString) {
// this.argString = argString;
// }
//
// /**
// * Check if a string matches this command's string or an alternative string.
// *
// * @param msg
// * The message to check
// * @return true if this string matches the command
// */
// public boolean matchesString(String msg) {
// boolean matches = false;
// matches = matches || msg.equalsIgnoreCase(command);
// for (String cmd : alternativeCommands) {
// matches = matches || msg.equalsIgnoreCase(cmd);
// }
// return matches;
// }
//
// /**
// * Executes the command with the given arguments
// *
// * @param bot
// * the bot used to send messages
// * @param channel
// * the channel the request came from
// * @param executor
// * The name of the person who executed the command
// * @param message
// * the unmodified message containing the command
// */
// public abstract void executeCommand(RSIRCBot bot, String channel, String executor, String message);
//
// /**
// * Finds the Command object
// *
// * @param message
// * @return
// */
// public static Command getCommand(String message) {
// Command cmd = null;
// if (message.length() > 1 && !message.startsWith(" ")) {
// String[] tokens = message.split(" ");
// String commandString = tokens[0];
// boolean privateReply = true;
// if (commandString.startsWith("!") || commandString.startsWith(".")) {
// privateReply = true;
// } else if (commandString.startsWith("@")) {
// privateReply = false;
// }
// commandString = tokens[0].substring(1, tokens[0].length());
// for (Command c : commands) {
// if (c.matchesString(commandString)) {
// cmd = c;
// cmd.setPrivateReply(privateReply);
// break;
// }
// }
// }
// return cmd;
// }
// }
// Path: src/org/nolat/rsircbot/CommandExecutor.java
import org.nolat.rsircbot.commands.Command;
package org.nolat.rsircbot;
public class CommandExecutor implements Runnable {
private final RSIRCBot bot;
private final String target;
private final String sender;
private final String message; | private final Command command; |
Talon876/RSIRCBot | src/org/nolat/rsircbot/data/BitcoinData.java | // Path: src/org/nolat/rsircbot/tools/URLReader.java
// public class URLReader {
//
// public static String readUrl(String urlString) throws Exception {
// BufferedReader reader = null;
// StringBuffer buffer = new StringBuffer();
// try {
// URL url = new URL(urlString);
// URLConnection connection = url.openConnection();
// connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " +
// "AppleWebKit/537.11 (KHTML, like Gecko) " +
// "Chrome/23.0.1271.95 " +
// "Safari/537.11");
//
// reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// String line;
// while ((line = reader.readLine()) != null) {
// buffer.append(line);
// }
//
// } finally {
// if (reader != null) {
// reader.close();
// }
// }
//
// return buffer.toString();
// }
// }
| import org.nolat.rsircbot.tools.URLReader;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; | package org.nolat.rsircbot.data;
public class BitcoinData {
private static final String baseUrl = "http://data.mtgox.com/api/1/BTCUSD/ticker";
private String lowValue = "";
private String highValue = "";
private String avgValue = "";
public BitcoinData() throws LookupException {
String jsonData = null;
boolean failed = false;
try { | // Path: src/org/nolat/rsircbot/tools/URLReader.java
// public class URLReader {
//
// public static String readUrl(String urlString) throws Exception {
// BufferedReader reader = null;
// StringBuffer buffer = new StringBuffer();
// try {
// URL url = new URL(urlString);
// URLConnection connection = url.openConnection();
// connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " +
// "AppleWebKit/537.11 (KHTML, like Gecko) " +
// "Chrome/23.0.1271.95 " +
// "Safari/537.11");
//
// reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// String line;
// while ((line = reader.readLine()) != null) {
// buffer.append(line);
// }
//
// } finally {
// if (reader != null) {
// reader.close();
// }
// }
//
// return buffer.toString();
// }
// }
// Path: src/org/nolat/rsircbot/data/BitcoinData.java
import org.nolat.rsircbot.tools.URLReader;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
package org.nolat.rsircbot.data;
public class BitcoinData {
private static final String baseUrl = "http://data.mtgox.com/api/1/BTCUSD/ticker";
private String lowValue = "";
private String highValue = "";
private String avgValue = "";
public BitcoinData() throws LookupException {
String jsonData = null;
boolean failed = false;
try { | jsonData = URLReader.readUrl(baseUrl); |
Talon876/RSIRCBot | src/org/nolat/rsircbot/data/json/ItemData.java | // Path: src/org/nolat/rsircbot/tools/RSFormatter.java
// public class RSFormatter {
// public static final DecimalFormat formatter = new DecimalFormat("#,###");
//
// public static String format(int num) {
// return formatter.format(num);
// }
//
// public static String format(double num) {
// return formatter.format(num);
// }
//
// public static String format(String string) {
// return format(Float.parseFloat(string));
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/TimeUtils.java
// public class TimeUtils {
//
// public final static long ONE_SECOND = 1000;
// public final static long SECONDS = 60;
//
// public final static long ONE_MINUTE = ONE_SECOND * 60;
// public final static long MINUTES = 60;
//
// public final static long ONE_HOUR = ONE_MINUTE * 60;
// public final static long HOURS = 24;
//
// public final static long ONE_DAY = ONE_HOUR * 24;
//
// private TimeUtils() {
// }
//
// /**
// * converts time (in milliseconds) to human-readable format "<w> days, <x> hours, <y> minutes and (z) seconds"
// */
// public static String millisToLongDHMS(long duration) {
// StringBuffer res = new StringBuffer();
// long temp = 0;
// if (duration <= ONE_SECOND * 5) {
// res.append("a few seconds");
// return res.toString();
// } else if (duration <= ONE_MINUTE) {
// res.append("a moment");
// return res.toString();
// } else {
// temp = duration / ONE_DAY;
// if (temp > 0) {
// duration -= temp * ONE_DAY;
// res.append(temp).append(" day").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_HOUR;
// if (temp > 0) {
// duration -= temp * ONE_HOUR;
// res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_MINUTE;
// if (temp > 0) {
// duration -= temp * ONE_MINUTE;
// res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
// }
//
// // if (!res.toString().equals("") && duration >= ONE_SECOND) {
// // res.append(" and ");
// // }
// //
// // temp = duration / ONE_SECOND;
// // if (temp > 0) {
// // res.append(temp).append(" second").append(temp > 1 ? "s" : "");
// // }
// return res.toString();
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.nolat.rsircbot.tools.RSFormatter;
import org.nolat.rsircbot.tools.TimeUtils; | package org.nolat.rsircbot.data.json;
public class ItemData {
String average;
String high_alch;
List<HistoryData> history;
String id;
String image;
String name;
List<OfferData> offers;
String recent_high;
String recent_low;
public int getHighAlchValue() {
return Integer.parseInt(high_alch);
}
public String getHighAlchString() { | // Path: src/org/nolat/rsircbot/tools/RSFormatter.java
// public class RSFormatter {
// public static final DecimalFormat formatter = new DecimalFormat("#,###");
//
// public static String format(int num) {
// return formatter.format(num);
// }
//
// public static String format(double num) {
// return formatter.format(num);
// }
//
// public static String format(String string) {
// return format(Float.parseFloat(string));
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/TimeUtils.java
// public class TimeUtils {
//
// public final static long ONE_SECOND = 1000;
// public final static long SECONDS = 60;
//
// public final static long ONE_MINUTE = ONE_SECOND * 60;
// public final static long MINUTES = 60;
//
// public final static long ONE_HOUR = ONE_MINUTE * 60;
// public final static long HOURS = 24;
//
// public final static long ONE_DAY = ONE_HOUR * 24;
//
// private TimeUtils() {
// }
//
// /**
// * converts time (in milliseconds) to human-readable format "<w> days, <x> hours, <y> minutes and (z) seconds"
// */
// public static String millisToLongDHMS(long duration) {
// StringBuffer res = new StringBuffer();
// long temp = 0;
// if (duration <= ONE_SECOND * 5) {
// res.append("a few seconds");
// return res.toString();
// } else if (duration <= ONE_MINUTE) {
// res.append("a moment");
// return res.toString();
// } else {
// temp = duration / ONE_DAY;
// if (temp > 0) {
// duration -= temp * ONE_DAY;
// res.append(temp).append(" day").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_HOUR;
// if (temp > 0) {
// duration -= temp * ONE_HOUR;
// res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_MINUTE;
// if (temp > 0) {
// duration -= temp * ONE_MINUTE;
// res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
// }
//
// // if (!res.toString().equals("") && duration >= ONE_SECOND) {
// // res.append(" and ");
// // }
// //
// // temp = duration / ONE_SECOND;
// // if (temp > 0) {
// // res.append(temp).append(" second").append(temp > 1 ? "s" : "");
// // }
// return res.toString();
// }
// }
// }
// Path: src/org/nolat/rsircbot/data/json/ItemData.java
import java.util.ArrayList;
import java.util.List;
import org.nolat.rsircbot.tools.RSFormatter;
import org.nolat.rsircbot.tools.TimeUtils;
package org.nolat.rsircbot.data.json;
public class ItemData {
String average;
String high_alch;
List<HistoryData> history;
String id;
String image;
String name;
List<OfferData> offers;
String recent_high;
String recent_low;
public int getHighAlchValue() {
return Integer.parseInt(high_alch);
}
public String getHighAlchString() { | return RSFormatter.format(high_alch); |
Talon876/RSIRCBot | src/org/nolat/rsircbot/data/json/ItemData.java | // Path: src/org/nolat/rsircbot/tools/RSFormatter.java
// public class RSFormatter {
// public static final DecimalFormat formatter = new DecimalFormat("#,###");
//
// public static String format(int num) {
// return formatter.format(num);
// }
//
// public static String format(double num) {
// return formatter.format(num);
// }
//
// public static String format(String string) {
// return format(Float.parseFloat(string));
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/TimeUtils.java
// public class TimeUtils {
//
// public final static long ONE_SECOND = 1000;
// public final static long SECONDS = 60;
//
// public final static long ONE_MINUTE = ONE_SECOND * 60;
// public final static long MINUTES = 60;
//
// public final static long ONE_HOUR = ONE_MINUTE * 60;
// public final static long HOURS = 24;
//
// public final static long ONE_DAY = ONE_HOUR * 24;
//
// private TimeUtils() {
// }
//
// /**
// * converts time (in milliseconds) to human-readable format "<w> days, <x> hours, <y> minutes and (z) seconds"
// */
// public static String millisToLongDHMS(long duration) {
// StringBuffer res = new StringBuffer();
// long temp = 0;
// if (duration <= ONE_SECOND * 5) {
// res.append("a few seconds");
// return res.toString();
// } else if (duration <= ONE_MINUTE) {
// res.append("a moment");
// return res.toString();
// } else {
// temp = duration / ONE_DAY;
// if (temp > 0) {
// duration -= temp * ONE_DAY;
// res.append(temp).append(" day").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_HOUR;
// if (temp > 0) {
// duration -= temp * ONE_HOUR;
// res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_MINUTE;
// if (temp > 0) {
// duration -= temp * ONE_MINUTE;
// res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
// }
//
// // if (!res.toString().equals("") && duration >= ONE_SECOND) {
// // res.append(" and ");
// // }
// //
// // temp = duration / ONE_SECOND;
// // if (temp > 0) {
// // res.append(temp).append(" second").append(temp > 1 ? "s" : "");
// // }
// return res.toString();
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.nolat.rsircbot.tools.RSFormatter;
import org.nolat.rsircbot.tools.TimeUtils; | return Integer.parseInt(high_alch);
}
public String getHighAlchString() {
return RSFormatter.format(high_alch);
}
public String getPriceString() {
return RSFormatter.format(average);
}
public int getPriceValue() {
return (int) Double.parseDouble(average);
}
public List<HistoryData> getHistory() {
return history;
}
public String getName() {
return name;
}
public List<OfferData> getOffers() {
return offers;
}
public List<OfferData> getRecentOffers(int hours) {
List<OfferData> recentOffers = new ArrayList<OfferData>();
for (OfferData od : getOffers()) { | // Path: src/org/nolat/rsircbot/tools/RSFormatter.java
// public class RSFormatter {
// public static final DecimalFormat formatter = new DecimalFormat("#,###");
//
// public static String format(int num) {
// return formatter.format(num);
// }
//
// public static String format(double num) {
// return formatter.format(num);
// }
//
// public static String format(String string) {
// return format(Float.parseFloat(string));
// }
// }
//
// Path: src/org/nolat/rsircbot/tools/TimeUtils.java
// public class TimeUtils {
//
// public final static long ONE_SECOND = 1000;
// public final static long SECONDS = 60;
//
// public final static long ONE_MINUTE = ONE_SECOND * 60;
// public final static long MINUTES = 60;
//
// public final static long ONE_HOUR = ONE_MINUTE * 60;
// public final static long HOURS = 24;
//
// public final static long ONE_DAY = ONE_HOUR * 24;
//
// private TimeUtils() {
// }
//
// /**
// * converts time (in milliseconds) to human-readable format "<w> days, <x> hours, <y> minutes and (z) seconds"
// */
// public static String millisToLongDHMS(long duration) {
// StringBuffer res = new StringBuffer();
// long temp = 0;
// if (duration <= ONE_SECOND * 5) {
// res.append("a few seconds");
// return res.toString();
// } else if (duration <= ONE_MINUTE) {
// res.append("a moment");
// return res.toString();
// } else {
// temp = duration / ONE_DAY;
// if (temp > 0) {
// duration -= temp * ONE_DAY;
// res.append(temp).append(" day").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_HOUR;
// if (temp > 0) {
// duration -= temp * ONE_HOUR;
// res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
// .append(duration >= ONE_MINUTE ? ", " : "");
// }
//
// temp = duration / ONE_MINUTE;
// if (temp > 0) {
// duration -= temp * ONE_MINUTE;
// res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
// }
//
// // if (!res.toString().equals("") && duration >= ONE_SECOND) {
// // res.append(" and ");
// // }
// //
// // temp = duration / ONE_SECOND;
// // if (temp > 0) {
// // res.append(temp).append(" second").append(temp > 1 ? "s" : "");
// // }
// return res.toString();
// }
// }
// }
// Path: src/org/nolat/rsircbot/data/json/ItemData.java
import java.util.ArrayList;
import java.util.List;
import org.nolat.rsircbot.tools.RSFormatter;
import org.nolat.rsircbot.tools.TimeUtils;
return Integer.parseInt(high_alch);
}
public String getHighAlchString() {
return RSFormatter.format(high_alch);
}
public String getPriceString() {
return RSFormatter.format(average);
}
public int getPriceValue() {
return (int) Double.parseDouble(average);
}
public List<HistoryData> getHistory() {
return history;
}
public String getName() {
return name;
}
public List<OfferData> getOffers() {
return offers;
}
public List<OfferData> getRecentOffers(int hours) {
List<OfferData> recentOffers = new ArrayList<OfferData>();
for (OfferData od : getOffers()) { | if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) { |
Talon876/RSIRCBot | src/org/nolat/rsircbot/Main.java | // Path: src/org/nolat/rsircbot/settings/Settings.java
// public class Settings {
//
// File settingsFile;
// String jsonData;
// BotSettings settings;
//
// public Settings(String path) throws SettingsException {
// File f = new File(path);
// if (f.exists() && f.isFile()) {
// settingsFile = f;
// try {
// jsonData = FileReader.readFile(path);
// } catch (IOException e) {
// throw new SettingsException("Error reading file " + path + ": " + e.getMessage());
// }
// init();
// } else {
// throw new SettingsException("File does not exist: " + path);
// }
// }
//
// private void init() {
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// /**
// * Reloads settings from disk
// */
// public void refresh() {
// try {
// jsonData = FileReader.readFile(settingsFile.getAbsolutePath());
// } catch (IOException e) {
// e.printStackTrace(); //shouldn't happen
// }
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// public void save() {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String json = gson.toJson(settings);
// try {
// FileReader.writeFile(settingsFile.getAbsolutePath(), json);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// }
//
// public String getName() {
// return settings.getName().replaceAll(" ", "_");
// }
//
// public String getServer() {
// return settings.getServer();
// }
//
// public int getPort() {
// return settings.getPort();
// }
//
// public List<Channel> getChannels() {
// return settings.getChannels();
// }
//
// public List<User> getUsers() {
// return settings.getUsers();
// }
//
// public Channel getChannel(String name) {
// refresh();
// return settings.getChannel(name);
// }
//
// public User getUser(String name) {
// refresh();
// return settings.getUser(name);
// }
//
// public boolean isDebugMode() {
// return settings.isDebug();
// }
//
// public String getBroadcastTag() {
// return settings.getBroadcastTag();
// }
//
// public String getWitToken() {
// return settings.getWitToken();
// }
//
// public void addChannel(Channel c) {
// settings.addChannel(c);
// save();
// }
//
// public void removeChannel(String channel) {
// settings.removeChannel(channel);
// save();
// }
//
// public void addUser(User u) {
// settings.addUser(u);
// save();
// }
//
// public void setQotd(String channel, String message) {
// settings.getChannel(channel).setQotd(message);
// save();
// }
//
// public void setRSN(String nick, String rsn) {
// settings.getUser(nick).setRSN(rsn);
// save();
// }
//
// public void toggleQotd(String channel) {
// getChannel(channel).toggleQotd();
// save();
// }
//
// public void toggleGreeting(String channel) {
// getChannel(channel).toggleGreeting();
// save();
// }
//
// public int getMessageCount() {
// return settings.getMessageCount();
// }
//
// public int getCommandCount() {
// return settings.getCommandCount();
// }
//
// public void increaseMessageCount() {
// settings.increaseMessageCount();
// save();
// }
//
// public void increaseCommandCount() {
// settings.increaseCommandCount();
// save();
// }
//
// public void addFeedback(String fb) {
// settings.addFeedback(fb);
// save();
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/SettingsException.java
// public class SettingsException extends Exception {
//
// private static final long serialVersionUID = -4976383656388815952L;
//
// public SettingsException(String msg) {
// super(msg);
// }
// }
| import org.nolat.rsircbot.settings.Settings;
import org.nolat.rsircbot.settings.SettingsException;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Switch; | package org.nolat.rsircbot;
public class Main {
public static void main(String[] args) {
try {
JSAP jsap = new JSAP();
Switch switchOpt = new Switch("help");
switchOpt.setShortFlag('h');
switchOpt.setLongFlag("help");
switchOpt.setHelp("Displays this help message");
jsap.registerParameter(switchOpt);
FlaggedOption fileOpt = new FlaggedOption("file");
fileOpt.setStringParser(JSAP.STRING_PARSER);
fileOpt.setShortFlag('f');
fileOpt.setLongFlag("file");
fileOpt.setHelp("The path to the file to load settings from");
fileOpt.setDefault("settings.json");
jsap.registerParameter(fileOpt);
JSAPResult config = jsap.parse(args);
if (config.success()) {
if (config.getBoolean("help")) {
help(jsap);
} else {
String filePath = config.getString("file"); | // Path: src/org/nolat/rsircbot/settings/Settings.java
// public class Settings {
//
// File settingsFile;
// String jsonData;
// BotSettings settings;
//
// public Settings(String path) throws SettingsException {
// File f = new File(path);
// if (f.exists() && f.isFile()) {
// settingsFile = f;
// try {
// jsonData = FileReader.readFile(path);
// } catch (IOException e) {
// throw new SettingsException("Error reading file " + path + ": " + e.getMessage());
// }
// init();
// } else {
// throw new SettingsException("File does not exist: " + path);
// }
// }
//
// private void init() {
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// /**
// * Reloads settings from disk
// */
// public void refresh() {
// try {
// jsonData = FileReader.readFile(settingsFile.getAbsolutePath());
// } catch (IOException e) {
// e.printStackTrace(); //shouldn't happen
// }
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// public void save() {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String json = gson.toJson(settings);
// try {
// FileReader.writeFile(settingsFile.getAbsolutePath(), json);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// }
//
// public String getName() {
// return settings.getName().replaceAll(" ", "_");
// }
//
// public String getServer() {
// return settings.getServer();
// }
//
// public int getPort() {
// return settings.getPort();
// }
//
// public List<Channel> getChannels() {
// return settings.getChannels();
// }
//
// public List<User> getUsers() {
// return settings.getUsers();
// }
//
// public Channel getChannel(String name) {
// refresh();
// return settings.getChannel(name);
// }
//
// public User getUser(String name) {
// refresh();
// return settings.getUser(name);
// }
//
// public boolean isDebugMode() {
// return settings.isDebug();
// }
//
// public String getBroadcastTag() {
// return settings.getBroadcastTag();
// }
//
// public String getWitToken() {
// return settings.getWitToken();
// }
//
// public void addChannel(Channel c) {
// settings.addChannel(c);
// save();
// }
//
// public void removeChannel(String channel) {
// settings.removeChannel(channel);
// save();
// }
//
// public void addUser(User u) {
// settings.addUser(u);
// save();
// }
//
// public void setQotd(String channel, String message) {
// settings.getChannel(channel).setQotd(message);
// save();
// }
//
// public void setRSN(String nick, String rsn) {
// settings.getUser(nick).setRSN(rsn);
// save();
// }
//
// public void toggleQotd(String channel) {
// getChannel(channel).toggleQotd();
// save();
// }
//
// public void toggleGreeting(String channel) {
// getChannel(channel).toggleGreeting();
// save();
// }
//
// public int getMessageCount() {
// return settings.getMessageCount();
// }
//
// public int getCommandCount() {
// return settings.getCommandCount();
// }
//
// public void increaseMessageCount() {
// settings.increaseMessageCount();
// save();
// }
//
// public void increaseCommandCount() {
// settings.increaseCommandCount();
// save();
// }
//
// public void addFeedback(String fb) {
// settings.addFeedback(fb);
// save();
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/SettingsException.java
// public class SettingsException extends Exception {
//
// private static final long serialVersionUID = -4976383656388815952L;
//
// public SettingsException(String msg) {
// super(msg);
// }
// }
// Path: src/org/nolat/rsircbot/Main.java
import org.nolat.rsircbot.settings.Settings;
import org.nolat.rsircbot.settings.SettingsException;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Switch;
package org.nolat.rsircbot;
public class Main {
public static void main(String[] args) {
try {
JSAP jsap = new JSAP();
Switch switchOpt = new Switch("help");
switchOpt.setShortFlag('h');
switchOpt.setLongFlag("help");
switchOpt.setHelp("Displays this help message");
jsap.registerParameter(switchOpt);
FlaggedOption fileOpt = new FlaggedOption("file");
fileOpt.setStringParser(JSAP.STRING_PARSER);
fileOpt.setShortFlag('f');
fileOpt.setLongFlag("file");
fileOpt.setHelp("The path to the file to load settings from");
fileOpt.setDefault("settings.json");
jsap.registerParameter(fileOpt);
JSAPResult config = jsap.parse(args);
if (config.success()) {
if (config.getBoolean("help")) {
help(jsap);
} else {
String filePath = config.getString("file"); | Settings settings = new Settings(filePath); |
Talon876/RSIRCBot | src/org/nolat/rsircbot/Main.java | // Path: src/org/nolat/rsircbot/settings/Settings.java
// public class Settings {
//
// File settingsFile;
// String jsonData;
// BotSettings settings;
//
// public Settings(String path) throws SettingsException {
// File f = new File(path);
// if (f.exists() && f.isFile()) {
// settingsFile = f;
// try {
// jsonData = FileReader.readFile(path);
// } catch (IOException e) {
// throw new SettingsException("Error reading file " + path + ": " + e.getMessage());
// }
// init();
// } else {
// throw new SettingsException("File does not exist: " + path);
// }
// }
//
// private void init() {
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// /**
// * Reloads settings from disk
// */
// public void refresh() {
// try {
// jsonData = FileReader.readFile(settingsFile.getAbsolutePath());
// } catch (IOException e) {
// e.printStackTrace(); //shouldn't happen
// }
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// public void save() {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String json = gson.toJson(settings);
// try {
// FileReader.writeFile(settingsFile.getAbsolutePath(), json);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// }
//
// public String getName() {
// return settings.getName().replaceAll(" ", "_");
// }
//
// public String getServer() {
// return settings.getServer();
// }
//
// public int getPort() {
// return settings.getPort();
// }
//
// public List<Channel> getChannels() {
// return settings.getChannels();
// }
//
// public List<User> getUsers() {
// return settings.getUsers();
// }
//
// public Channel getChannel(String name) {
// refresh();
// return settings.getChannel(name);
// }
//
// public User getUser(String name) {
// refresh();
// return settings.getUser(name);
// }
//
// public boolean isDebugMode() {
// return settings.isDebug();
// }
//
// public String getBroadcastTag() {
// return settings.getBroadcastTag();
// }
//
// public String getWitToken() {
// return settings.getWitToken();
// }
//
// public void addChannel(Channel c) {
// settings.addChannel(c);
// save();
// }
//
// public void removeChannel(String channel) {
// settings.removeChannel(channel);
// save();
// }
//
// public void addUser(User u) {
// settings.addUser(u);
// save();
// }
//
// public void setQotd(String channel, String message) {
// settings.getChannel(channel).setQotd(message);
// save();
// }
//
// public void setRSN(String nick, String rsn) {
// settings.getUser(nick).setRSN(rsn);
// save();
// }
//
// public void toggleQotd(String channel) {
// getChannel(channel).toggleQotd();
// save();
// }
//
// public void toggleGreeting(String channel) {
// getChannel(channel).toggleGreeting();
// save();
// }
//
// public int getMessageCount() {
// return settings.getMessageCount();
// }
//
// public int getCommandCount() {
// return settings.getCommandCount();
// }
//
// public void increaseMessageCount() {
// settings.increaseMessageCount();
// save();
// }
//
// public void increaseCommandCount() {
// settings.increaseCommandCount();
// save();
// }
//
// public void addFeedback(String fb) {
// settings.addFeedback(fb);
// save();
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/SettingsException.java
// public class SettingsException extends Exception {
//
// private static final long serialVersionUID = -4976383656388815952L;
//
// public SettingsException(String msg) {
// super(msg);
// }
// }
| import org.nolat.rsircbot.settings.Settings;
import org.nolat.rsircbot.settings.SettingsException;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Switch; |
Switch switchOpt = new Switch("help");
switchOpt.setShortFlag('h');
switchOpt.setLongFlag("help");
switchOpt.setHelp("Displays this help message");
jsap.registerParameter(switchOpt);
FlaggedOption fileOpt = new FlaggedOption("file");
fileOpt.setStringParser(JSAP.STRING_PARSER);
fileOpt.setShortFlag('f');
fileOpt.setLongFlag("file");
fileOpt.setHelp("The path to the file to load settings from");
fileOpt.setDefault("settings.json");
jsap.registerParameter(fileOpt);
JSAPResult config = jsap.parse(args);
if (config.success()) {
if (config.getBoolean("help")) {
help(jsap);
} else {
String filePath = config.getString("file");
Settings settings = new Settings(filePath);
RSIRCBot bot = new RSIRCBot(settings);
}
} else {
help(jsap);
}
} catch (JSAPException e) {
e.printStackTrace(); | // Path: src/org/nolat/rsircbot/settings/Settings.java
// public class Settings {
//
// File settingsFile;
// String jsonData;
// BotSettings settings;
//
// public Settings(String path) throws SettingsException {
// File f = new File(path);
// if (f.exists() && f.isFile()) {
// settingsFile = f;
// try {
// jsonData = FileReader.readFile(path);
// } catch (IOException e) {
// throw new SettingsException("Error reading file " + path + ": " + e.getMessage());
// }
// init();
// } else {
// throw new SettingsException("File does not exist: " + path);
// }
// }
//
// private void init() {
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// /**
// * Reloads settings from disk
// */
// public void refresh() {
// try {
// jsonData = FileReader.readFile(settingsFile.getAbsolutePath());
// } catch (IOException e) {
// e.printStackTrace(); //shouldn't happen
// }
// Gson gson = new Gson();
// settings = gson.fromJson(jsonData, BotSettings.class);
// }
//
// public void save() {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String json = gson.toJson(settings);
// try {
// FileReader.writeFile(settingsFile.getAbsolutePath(), json);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// }
//
// public String getName() {
// return settings.getName().replaceAll(" ", "_");
// }
//
// public String getServer() {
// return settings.getServer();
// }
//
// public int getPort() {
// return settings.getPort();
// }
//
// public List<Channel> getChannels() {
// return settings.getChannels();
// }
//
// public List<User> getUsers() {
// return settings.getUsers();
// }
//
// public Channel getChannel(String name) {
// refresh();
// return settings.getChannel(name);
// }
//
// public User getUser(String name) {
// refresh();
// return settings.getUser(name);
// }
//
// public boolean isDebugMode() {
// return settings.isDebug();
// }
//
// public String getBroadcastTag() {
// return settings.getBroadcastTag();
// }
//
// public String getWitToken() {
// return settings.getWitToken();
// }
//
// public void addChannel(Channel c) {
// settings.addChannel(c);
// save();
// }
//
// public void removeChannel(String channel) {
// settings.removeChannel(channel);
// save();
// }
//
// public void addUser(User u) {
// settings.addUser(u);
// save();
// }
//
// public void setQotd(String channel, String message) {
// settings.getChannel(channel).setQotd(message);
// save();
// }
//
// public void setRSN(String nick, String rsn) {
// settings.getUser(nick).setRSN(rsn);
// save();
// }
//
// public void toggleQotd(String channel) {
// getChannel(channel).toggleQotd();
// save();
// }
//
// public void toggleGreeting(String channel) {
// getChannel(channel).toggleGreeting();
// save();
// }
//
// public int getMessageCount() {
// return settings.getMessageCount();
// }
//
// public int getCommandCount() {
// return settings.getCommandCount();
// }
//
// public void increaseMessageCount() {
// settings.increaseMessageCount();
// save();
// }
//
// public void increaseCommandCount() {
// settings.increaseCommandCount();
// save();
// }
//
// public void addFeedback(String fb) {
// settings.addFeedback(fb);
// save();
// }
// }
//
// Path: src/org/nolat/rsircbot/settings/SettingsException.java
// public class SettingsException extends Exception {
//
// private static final long serialVersionUID = -4976383656388815952L;
//
// public SettingsException(String msg) {
// super(msg);
// }
// }
// Path: src/org/nolat/rsircbot/Main.java
import org.nolat.rsircbot.settings.Settings;
import org.nolat.rsircbot.settings.SettingsException;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Switch;
Switch switchOpt = new Switch("help");
switchOpt.setShortFlag('h');
switchOpt.setLongFlag("help");
switchOpt.setHelp("Displays this help message");
jsap.registerParameter(switchOpt);
FlaggedOption fileOpt = new FlaggedOption("file");
fileOpt.setStringParser(JSAP.STRING_PARSER);
fileOpt.setShortFlag('f');
fileOpt.setLongFlag("file");
fileOpt.setHelp("The path to the file to load settings from");
fileOpt.setDefault("settings.json");
jsap.registerParameter(fileOpt);
JSAPResult config = jsap.parse(args);
if (config.success()) {
if (config.getBoolean("help")) {
help(jsap);
} else {
String filePath = config.getString("file");
Settings settings = new Settings(filePath);
RSIRCBot bot = new RSIRCBot(settings);
}
} else {
help(jsap);
}
} catch (JSAPException e) {
e.printStackTrace(); | } catch (SettingsException e) { |
Talon876/RSIRCBot | src/org/nolat/rsircbot/commands/actions/AlchAction.java | // Path: src/org/nolat/rsircbot/data/ItemSearch.java
// public class ItemSearch {
// private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/";
//
// private String item;
//
// ItemData[] results;
//
// public ItemSearch(String item) throws LookupException {
// this.item = item.replaceAll(" ", "_").replaceAll("'", "_");
// refreshData();
// }
//
// public void refreshData() throws LookupException {
// String jsonData = null;
// boolean failed = false;
// try {
// jsonData = URLReader.readUrl(baseUrl + item);
// } catch (Exception e) {
// System.out.println("Failed to retrieve item data for item : " + item);
// e.printStackTrace();
// failed = true;
// }
//
// if (jsonData != null && !failed) {
// Gson gson = new Gson();
// if (jsonData.contains("\"error\"")) {
// HashMap<String, String> result = gson.fromJson(jsonData, HashMap.class);
// throw new LookupException("Server Error: " + result.get("error"));
// } else {
// results = gson.fromJson(jsonData, ItemData[].class);
// }
// } else {
// throw new LookupException("Failed to retrieve data from server for '" + item + "'.");
// }
// }
//
// /**
// * Gets the ItemData for the returned item if there is only one item. <br>
// * Or if one of the items has an exact name match with the query
// *
// * @return the ItemData for the matched item, null if there is more than one
// */
// public ItemData getMatchedItem() {
// if (results.length > 1) {
// for (ItemData result : results) {
// if (result.getName().replaceAll(" ", "_").toLowerCase().equalsIgnoreCase(item)) {
// return result;
// }
// }
// } else {
// return results[0];
// }
// return null;
// }
//
// public ItemData[] getResults() {
// return results;
// }
//
// public String getSuggestionString() {
// StringBuffer buf = new StringBuffer("{");
// for (int i = 0; i < results.length; i++) {
// buf.append(results[i].getName() + (i == results.length - 1 ? "" : ", "));
// }
// buf.append("}");
// return buf.toString();
// }
// }
//
// Path: src/org/nolat/rsircbot/data/LookupException.java
// public class LookupException extends Throwable {
//
// private static final long serialVersionUID = -4246000002994677272L;
//
// public LookupException(String message) {
// super(message);
// }
// }
//
// Path: src/org/nolat/rsircbot/data/json/ItemData.java
// public class ItemData {
// String average;
// String high_alch;
// List<HistoryData> history;
// String id;
// String image;
// String name;
// List<OfferData> offers;
// String recent_high;
// String recent_low;
//
// public int getHighAlchValue() {
// return Integer.parseInt(high_alch);
// }
//
// public String getHighAlchString() {
// return RSFormatter.format(high_alch);
// }
//
// public String getPriceString() {
// return RSFormatter.format(average);
// }
//
// public int getPriceValue() {
// return (int) Double.parseDouble(average);
// }
//
// public List<HistoryData> getHistory() {
// return history;
// }
//
// public String getName() {
// return name;
// }
//
// public List<OfferData> getOffers() {
// return offers;
// }
//
// public List<OfferData> getRecentOffers(int hours) {
// List<OfferData> recentOffers = new ArrayList<OfferData>();
// for (OfferData od : getOffers()) {
// if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) {
// recentOffers.add(od);
// }
// }
// return recentOffers;
// }
//
// public List<OfferData> getRecentBuyers(int hours) {
// List<OfferData> buyers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (!od.isSelling()) {
// buyers.add(od);
// }
// }
// return buyers;
// }
//
// public List<OfferData> getRecentSellers(int hours) {
// List<OfferData> sellers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (od.isSelling()) {
// sellers.add(od);
// }
// }
// return sellers;
// }
//
// public String getRecentHighString() {
// return RSFormatter.format(recent_high);
// }
//
// public String getRecentLowString() {
// return RSFormatter.format(recent_low);
// }
// }
| import org.nolat.rsircbot.data.ItemSearch;
import org.nolat.rsircbot.data.LookupException;
import org.nolat.rsircbot.data.json.ItemData; | package org.nolat.rsircbot.commands.actions;
public class AlchAction extends Action {
private static ItemSearch NATURE_RUNE;
static {
try {
NATURE_RUNE = new ItemSearch("nature rune"); | // Path: src/org/nolat/rsircbot/data/ItemSearch.java
// public class ItemSearch {
// private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/";
//
// private String item;
//
// ItemData[] results;
//
// public ItemSearch(String item) throws LookupException {
// this.item = item.replaceAll(" ", "_").replaceAll("'", "_");
// refreshData();
// }
//
// public void refreshData() throws LookupException {
// String jsonData = null;
// boolean failed = false;
// try {
// jsonData = URLReader.readUrl(baseUrl + item);
// } catch (Exception e) {
// System.out.println("Failed to retrieve item data for item : " + item);
// e.printStackTrace();
// failed = true;
// }
//
// if (jsonData != null && !failed) {
// Gson gson = new Gson();
// if (jsonData.contains("\"error\"")) {
// HashMap<String, String> result = gson.fromJson(jsonData, HashMap.class);
// throw new LookupException("Server Error: " + result.get("error"));
// } else {
// results = gson.fromJson(jsonData, ItemData[].class);
// }
// } else {
// throw new LookupException("Failed to retrieve data from server for '" + item + "'.");
// }
// }
//
// /**
// * Gets the ItemData for the returned item if there is only one item. <br>
// * Or if one of the items has an exact name match with the query
// *
// * @return the ItemData for the matched item, null if there is more than one
// */
// public ItemData getMatchedItem() {
// if (results.length > 1) {
// for (ItemData result : results) {
// if (result.getName().replaceAll(" ", "_").toLowerCase().equalsIgnoreCase(item)) {
// return result;
// }
// }
// } else {
// return results[0];
// }
// return null;
// }
//
// public ItemData[] getResults() {
// return results;
// }
//
// public String getSuggestionString() {
// StringBuffer buf = new StringBuffer("{");
// for (int i = 0; i < results.length; i++) {
// buf.append(results[i].getName() + (i == results.length - 1 ? "" : ", "));
// }
// buf.append("}");
// return buf.toString();
// }
// }
//
// Path: src/org/nolat/rsircbot/data/LookupException.java
// public class LookupException extends Throwable {
//
// private static final long serialVersionUID = -4246000002994677272L;
//
// public LookupException(String message) {
// super(message);
// }
// }
//
// Path: src/org/nolat/rsircbot/data/json/ItemData.java
// public class ItemData {
// String average;
// String high_alch;
// List<HistoryData> history;
// String id;
// String image;
// String name;
// List<OfferData> offers;
// String recent_high;
// String recent_low;
//
// public int getHighAlchValue() {
// return Integer.parseInt(high_alch);
// }
//
// public String getHighAlchString() {
// return RSFormatter.format(high_alch);
// }
//
// public String getPriceString() {
// return RSFormatter.format(average);
// }
//
// public int getPriceValue() {
// return (int) Double.parseDouble(average);
// }
//
// public List<HistoryData> getHistory() {
// return history;
// }
//
// public String getName() {
// return name;
// }
//
// public List<OfferData> getOffers() {
// return offers;
// }
//
// public List<OfferData> getRecentOffers(int hours) {
// List<OfferData> recentOffers = new ArrayList<OfferData>();
// for (OfferData od : getOffers()) {
// if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) {
// recentOffers.add(od);
// }
// }
// return recentOffers;
// }
//
// public List<OfferData> getRecentBuyers(int hours) {
// List<OfferData> buyers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (!od.isSelling()) {
// buyers.add(od);
// }
// }
// return buyers;
// }
//
// public List<OfferData> getRecentSellers(int hours) {
// List<OfferData> sellers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (od.isSelling()) {
// sellers.add(od);
// }
// }
// return sellers;
// }
//
// public String getRecentHighString() {
// return RSFormatter.format(recent_high);
// }
//
// public String getRecentLowString() {
// return RSFormatter.format(recent_low);
// }
// }
// Path: src/org/nolat/rsircbot/commands/actions/AlchAction.java
import org.nolat.rsircbot.data.ItemSearch;
import org.nolat.rsircbot.data.LookupException;
import org.nolat.rsircbot.data.json.ItemData;
package org.nolat.rsircbot.commands.actions;
public class AlchAction extends Action {
private static ItemSearch NATURE_RUNE;
static {
try {
NATURE_RUNE = new ItemSearch("nature rune"); | } catch (LookupException e) { |
Talon876/RSIRCBot | src/org/nolat/rsircbot/commands/actions/AlchAction.java | // Path: src/org/nolat/rsircbot/data/ItemSearch.java
// public class ItemSearch {
// private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/";
//
// private String item;
//
// ItemData[] results;
//
// public ItemSearch(String item) throws LookupException {
// this.item = item.replaceAll(" ", "_").replaceAll("'", "_");
// refreshData();
// }
//
// public void refreshData() throws LookupException {
// String jsonData = null;
// boolean failed = false;
// try {
// jsonData = URLReader.readUrl(baseUrl + item);
// } catch (Exception e) {
// System.out.println("Failed to retrieve item data for item : " + item);
// e.printStackTrace();
// failed = true;
// }
//
// if (jsonData != null && !failed) {
// Gson gson = new Gson();
// if (jsonData.contains("\"error\"")) {
// HashMap<String, String> result = gson.fromJson(jsonData, HashMap.class);
// throw new LookupException("Server Error: " + result.get("error"));
// } else {
// results = gson.fromJson(jsonData, ItemData[].class);
// }
// } else {
// throw new LookupException("Failed to retrieve data from server for '" + item + "'.");
// }
// }
//
// /**
// * Gets the ItemData for the returned item if there is only one item. <br>
// * Or if one of the items has an exact name match with the query
// *
// * @return the ItemData for the matched item, null if there is more than one
// */
// public ItemData getMatchedItem() {
// if (results.length > 1) {
// for (ItemData result : results) {
// if (result.getName().replaceAll(" ", "_").toLowerCase().equalsIgnoreCase(item)) {
// return result;
// }
// }
// } else {
// return results[0];
// }
// return null;
// }
//
// public ItemData[] getResults() {
// return results;
// }
//
// public String getSuggestionString() {
// StringBuffer buf = new StringBuffer("{");
// for (int i = 0; i < results.length; i++) {
// buf.append(results[i].getName() + (i == results.length - 1 ? "" : ", "));
// }
// buf.append("}");
// return buf.toString();
// }
// }
//
// Path: src/org/nolat/rsircbot/data/LookupException.java
// public class LookupException extends Throwable {
//
// private static final long serialVersionUID = -4246000002994677272L;
//
// public LookupException(String message) {
// super(message);
// }
// }
//
// Path: src/org/nolat/rsircbot/data/json/ItemData.java
// public class ItemData {
// String average;
// String high_alch;
// List<HistoryData> history;
// String id;
// String image;
// String name;
// List<OfferData> offers;
// String recent_high;
// String recent_low;
//
// public int getHighAlchValue() {
// return Integer.parseInt(high_alch);
// }
//
// public String getHighAlchString() {
// return RSFormatter.format(high_alch);
// }
//
// public String getPriceString() {
// return RSFormatter.format(average);
// }
//
// public int getPriceValue() {
// return (int) Double.parseDouble(average);
// }
//
// public List<HistoryData> getHistory() {
// return history;
// }
//
// public String getName() {
// return name;
// }
//
// public List<OfferData> getOffers() {
// return offers;
// }
//
// public List<OfferData> getRecentOffers(int hours) {
// List<OfferData> recentOffers = new ArrayList<OfferData>();
// for (OfferData od : getOffers()) {
// if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) {
// recentOffers.add(od);
// }
// }
// return recentOffers;
// }
//
// public List<OfferData> getRecentBuyers(int hours) {
// List<OfferData> buyers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (!od.isSelling()) {
// buyers.add(od);
// }
// }
// return buyers;
// }
//
// public List<OfferData> getRecentSellers(int hours) {
// List<OfferData> sellers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (od.isSelling()) {
// sellers.add(od);
// }
// }
// return sellers;
// }
//
// public String getRecentHighString() {
// return RSFormatter.format(recent_high);
// }
//
// public String getRecentLowString() {
// return RSFormatter.format(recent_low);
// }
// }
| import org.nolat.rsircbot.data.ItemSearch;
import org.nolat.rsircbot.data.LookupException;
import org.nolat.rsircbot.data.json.ItemData; | package org.nolat.rsircbot.commands.actions;
public class AlchAction extends Action {
private static ItemSearch NATURE_RUNE;
static {
try {
NATURE_RUNE = new ItemSearch("nature rune");
} catch (LookupException e) {
e.printStackTrace();
}
}
public AlchAction(String item, ActionResponder responder) {
super(responder);
ItemSearch results = null;
try {
results = new ItemSearch(item);
} catch (LookupException e) {
this.responder.onResponseFailure(e.getMessage());
}
| // Path: src/org/nolat/rsircbot/data/ItemSearch.java
// public class ItemSearch {
// private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/";
//
// private String item;
//
// ItemData[] results;
//
// public ItemSearch(String item) throws LookupException {
// this.item = item.replaceAll(" ", "_").replaceAll("'", "_");
// refreshData();
// }
//
// public void refreshData() throws LookupException {
// String jsonData = null;
// boolean failed = false;
// try {
// jsonData = URLReader.readUrl(baseUrl + item);
// } catch (Exception e) {
// System.out.println("Failed to retrieve item data for item : " + item);
// e.printStackTrace();
// failed = true;
// }
//
// if (jsonData != null && !failed) {
// Gson gson = new Gson();
// if (jsonData.contains("\"error\"")) {
// HashMap<String, String> result = gson.fromJson(jsonData, HashMap.class);
// throw new LookupException("Server Error: " + result.get("error"));
// } else {
// results = gson.fromJson(jsonData, ItemData[].class);
// }
// } else {
// throw new LookupException("Failed to retrieve data from server for '" + item + "'.");
// }
// }
//
// /**
// * Gets the ItemData for the returned item if there is only one item. <br>
// * Or if one of the items has an exact name match with the query
// *
// * @return the ItemData for the matched item, null if there is more than one
// */
// public ItemData getMatchedItem() {
// if (results.length > 1) {
// for (ItemData result : results) {
// if (result.getName().replaceAll(" ", "_").toLowerCase().equalsIgnoreCase(item)) {
// return result;
// }
// }
// } else {
// return results[0];
// }
// return null;
// }
//
// public ItemData[] getResults() {
// return results;
// }
//
// public String getSuggestionString() {
// StringBuffer buf = new StringBuffer("{");
// for (int i = 0; i < results.length; i++) {
// buf.append(results[i].getName() + (i == results.length - 1 ? "" : ", "));
// }
// buf.append("}");
// return buf.toString();
// }
// }
//
// Path: src/org/nolat/rsircbot/data/LookupException.java
// public class LookupException extends Throwable {
//
// private static final long serialVersionUID = -4246000002994677272L;
//
// public LookupException(String message) {
// super(message);
// }
// }
//
// Path: src/org/nolat/rsircbot/data/json/ItemData.java
// public class ItemData {
// String average;
// String high_alch;
// List<HistoryData> history;
// String id;
// String image;
// String name;
// List<OfferData> offers;
// String recent_high;
// String recent_low;
//
// public int getHighAlchValue() {
// return Integer.parseInt(high_alch);
// }
//
// public String getHighAlchString() {
// return RSFormatter.format(high_alch);
// }
//
// public String getPriceString() {
// return RSFormatter.format(average);
// }
//
// public int getPriceValue() {
// return (int) Double.parseDouble(average);
// }
//
// public List<HistoryData> getHistory() {
// return history;
// }
//
// public String getName() {
// return name;
// }
//
// public List<OfferData> getOffers() {
// return offers;
// }
//
// public List<OfferData> getRecentOffers(int hours) {
// List<OfferData> recentOffers = new ArrayList<OfferData>();
// for (OfferData od : getOffers()) {
// if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) {
// recentOffers.add(od);
// }
// }
// return recentOffers;
// }
//
// public List<OfferData> getRecentBuyers(int hours) {
// List<OfferData> buyers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (!od.isSelling()) {
// buyers.add(od);
// }
// }
// return buyers;
// }
//
// public List<OfferData> getRecentSellers(int hours) {
// List<OfferData> sellers = new ArrayList<OfferData>();
// for (OfferData od : getRecentOffers(hours)) {
// if (od.isSelling()) {
// sellers.add(od);
// }
// }
// return sellers;
// }
//
// public String getRecentHighString() {
// return RSFormatter.format(recent_high);
// }
//
// public String getRecentLowString() {
// return RSFormatter.format(recent_low);
// }
// }
// Path: src/org/nolat/rsircbot/commands/actions/AlchAction.java
import org.nolat.rsircbot.data.ItemSearch;
import org.nolat.rsircbot.data.LookupException;
import org.nolat.rsircbot.data.json.ItemData;
package org.nolat.rsircbot.commands.actions;
public class AlchAction extends Action {
private static ItemSearch NATURE_RUNE;
static {
try {
NATURE_RUNE = new ItemSearch("nature rune");
} catch (LookupException e) {
e.printStackTrace();
}
}
public AlchAction(String item, ActionResponder responder) {
super(responder);
ItemSearch results = null;
try {
results = new ItemSearch(item);
} catch (LookupException e) {
this.responder.onResponseFailure(e.getMessage());
}
| ItemData matchedItem = results.getMatchedItem(); |
GeoKnow/LinkedGeoData | linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/OsmRepoCoreDaoImpl.java | // Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/core/init/InitJenaLinkedGeoData.java
// public class InitJenaLinkedGeoData
// implements JenaSubsystemLifecycle
// {
// private static final Logger logger = LoggerFactory.getLogger(InitJenaLinkedGeoData.class);
//
// public void start() {
// logger.debug("LinkedGeoData Jena initialization");
// init();
// }
//
// @Override
// public void stop() {
// }
//
//
// public static final Resource State = ResourceFactory.createResource("http://example.org/osm/State");
//
// public static void init() {
//
// BuiltinPersonalities.model
// .add(State.class, new SimpleImplementation(State.asNode(), StateImpl.class));
// }
//
//
// }
| import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.ws.rs.core.UriBuilder;
import org.aksw.linkedgeodata.core.init.InitJenaLinkedGeoData;
import org.apache.commons.io.IOUtils;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codepoetics.protonpack.StreamUtils;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap; | public State getState(long seqId) throws Exception {
String path = sequenceIdFormatter.apply(seqId) + ".state.txt";
URI uri = UriBuilder.fromUri(baseUri).path(path).build(); // path("state.txt")
State result = getState(uri);
return result;
}
public State getState(URI uri) throws Exception {
logger.info("Retrieving state information for " + uri);
URLConnection conn = uri.toURL().openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
Properties properties = new Properties();
StringWriter w = new StringWriter();
IOUtils.copy(conn.getInputStream(), w, StandardCharsets.UTF_8);
String content = w.toString();
logger.debug("Reponse from " + uri + ":\n" + content);
properties.load(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
// Multimap<String, Entry<Long, String>> rawAttrs = parseMap(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
// Map<String, String> attrs = rawAttrs.entries().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getValue()));
State result = ModelFactory.createDefaultModel()
.createResource() | // Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/core/init/InitJenaLinkedGeoData.java
// public class InitJenaLinkedGeoData
// implements JenaSubsystemLifecycle
// {
// private static final Logger logger = LoggerFactory.getLogger(InitJenaLinkedGeoData.class);
//
// public void start() {
// logger.debug("LinkedGeoData Jena initialization");
// init();
// }
//
// @Override
// public void stop() {
// }
//
//
// public static final Resource State = ResourceFactory.createResource("http://example.org/osm/State");
//
// public static void init() {
//
// BuiltinPersonalities.model
// .add(State.class, new SimpleImplementation(State.asNode(), StateImpl.class));
// }
//
//
// }
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/OsmRepoCoreDaoImpl.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.ws.rs.core.UriBuilder;
import org.aksw.linkedgeodata.core.init.InitJenaLinkedGeoData;
import org.apache.commons.io.IOUtils;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codepoetics.protonpack.StreamUtils;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
public State getState(long seqId) throws Exception {
String path = sequenceIdFormatter.apply(seqId) + ".state.txt";
URI uri = UriBuilder.fromUri(baseUri).path(path).build(); // path("state.txt")
State result = getState(uri);
return result;
}
public State getState(URI uri) throws Exception {
logger.info("Retrieving state information for " + uri);
URLConnection conn = uri.toURL().openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
Properties properties = new Properties();
StringWriter w = new StringWriter();
IOUtils.copy(conn.getInputStream(), w, StandardCharsets.UTF_8);
String content = w.toString();
logger.debug("Reponse from " + uri + ":\n" + content);
properties.load(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
// Multimap<String, Entry<Long, String>> rawAttrs = parseMap(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
// Map<String, String> attrs = rawAttrs.entries().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getValue()));
State result = ModelFactory.createDefaultModel()
.createResource() | .addProperty(RDF.type, InitJenaLinkedGeoData.State) |
GeoKnow/LinkedGeoData | linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/core/init/InitJenaLinkedGeoData.java | // Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/State.java
// public interface State
// extends Resource
// {
// Calendar getTimestamp();
// long getSeqId();
// }
//
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/StateImpl.java
// public class StateImpl
// extends ResourceImpl
// implements State
// {
// public StateImpl(Node node, EnhGraph graph) {
// super(node, graph);
// }
//
// @Override
// public Calendar getTimestamp() {
// Object tmp = this.getRequiredProperty(DCTerms.created).getObject().asLiteral().getValue();
// Calendar result = ((XSDDateTime)tmp).asCalendar();
// return result;
// }
//
// @Override
// public long getSeqId() {
// long result = this.getRequiredProperty(DCTerms.identifier).getLong();
// return result;
// }
//
//
// public static Properties toProperties(Properties result, State state) {
// result.setProperty("timestamp", state.getTimestamp().toInstant().toString());
// result.setProperty("sequenceNumber", Long.toString(state.getSeqId()));
//
// return result;
// }
// }
| import org.aksw.linkedgeodata.osm.replication.dao.State;
import org.aksw.linkedgeodata.osm.replication.dao.StateImpl;
import org.apache.jena.enhanced.BuiltinPersonalities;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.system.JenaSubsystemLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.topbraid.spin.util.SimpleImplementation; | package org.aksw.linkedgeodata.core.init;
public class InitJenaLinkedGeoData
implements JenaSubsystemLifecycle
{
private static final Logger logger = LoggerFactory.getLogger(InitJenaLinkedGeoData.class);
public void start() {
logger.debug("LinkedGeoData Jena initialization");
init();
}
@Override
public void stop() {
}
| // Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/State.java
// public interface State
// extends Resource
// {
// Calendar getTimestamp();
// long getSeqId();
// }
//
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/StateImpl.java
// public class StateImpl
// extends ResourceImpl
// implements State
// {
// public StateImpl(Node node, EnhGraph graph) {
// super(node, graph);
// }
//
// @Override
// public Calendar getTimestamp() {
// Object tmp = this.getRequiredProperty(DCTerms.created).getObject().asLiteral().getValue();
// Calendar result = ((XSDDateTime)tmp).asCalendar();
// return result;
// }
//
// @Override
// public long getSeqId() {
// long result = this.getRequiredProperty(DCTerms.identifier).getLong();
// return result;
// }
//
//
// public static Properties toProperties(Properties result, State state) {
// result.setProperty("timestamp", state.getTimestamp().toInstant().toString());
// result.setProperty("sequenceNumber", Long.toString(state.getSeqId()));
//
// return result;
// }
// }
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/core/init/InitJenaLinkedGeoData.java
import org.aksw.linkedgeodata.osm.replication.dao.State;
import org.aksw.linkedgeodata.osm.replication.dao.StateImpl;
import org.apache.jena.enhanced.BuiltinPersonalities;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.system.JenaSubsystemLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.topbraid.spin.util.SimpleImplementation;
package org.aksw.linkedgeodata.core.init;
public class InitJenaLinkedGeoData
implements JenaSubsystemLifecycle
{
private static final Logger logger = LoggerFactory.getLogger(InitJenaLinkedGeoData.class);
public void start() {
logger.debug("LinkedGeoData Jena initialization");
init();
}
@Override
public void stop() {
}
| public static final Resource State = ResourceFactory.createResource("http://example.org/osm/State"); |
GeoKnow/LinkedGeoData | linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/core/init/InitJenaLinkedGeoData.java | // Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/State.java
// public interface State
// extends Resource
// {
// Calendar getTimestamp();
// long getSeqId();
// }
//
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/StateImpl.java
// public class StateImpl
// extends ResourceImpl
// implements State
// {
// public StateImpl(Node node, EnhGraph graph) {
// super(node, graph);
// }
//
// @Override
// public Calendar getTimestamp() {
// Object tmp = this.getRequiredProperty(DCTerms.created).getObject().asLiteral().getValue();
// Calendar result = ((XSDDateTime)tmp).asCalendar();
// return result;
// }
//
// @Override
// public long getSeqId() {
// long result = this.getRequiredProperty(DCTerms.identifier).getLong();
// return result;
// }
//
//
// public static Properties toProperties(Properties result, State state) {
// result.setProperty("timestamp", state.getTimestamp().toInstant().toString());
// result.setProperty("sequenceNumber", Long.toString(state.getSeqId()));
//
// return result;
// }
// }
| import org.aksw.linkedgeodata.osm.replication.dao.State;
import org.aksw.linkedgeodata.osm.replication.dao.StateImpl;
import org.apache.jena.enhanced.BuiltinPersonalities;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.system.JenaSubsystemLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.topbraid.spin.util.SimpleImplementation; | package org.aksw.linkedgeodata.core.init;
public class InitJenaLinkedGeoData
implements JenaSubsystemLifecycle
{
private static final Logger logger = LoggerFactory.getLogger(InitJenaLinkedGeoData.class);
public void start() {
logger.debug("LinkedGeoData Jena initialization");
init();
}
@Override
public void stop() {
}
public static final Resource State = ResourceFactory.createResource("http://example.org/osm/State");
public static void init() {
BuiltinPersonalities.model | // Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/State.java
// public interface State
// extends Resource
// {
// Calendar getTimestamp();
// long getSeqId();
// }
//
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/osm/replication/dao/StateImpl.java
// public class StateImpl
// extends ResourceImpl
// implements State
// {
// public StateImpl(Node node, EnhGraph graph) {
// super(node, graph);
// }
//
// @Override
// public Calendar getTimestamp() {
// Object tmp = this.getRequiredProperty(DCTerms.created).getObject().asLiteral().getValue();
// Calendar result = ((XSDDateTime)tmp).asCalendar();
// return result;
// }
//
// @Override
// public long getSeqId() {
// long result = this.getRequiredProperty(DCTerms.identifier).getLong();
// return result;
// }
//
//
// public static Properties toProperties(Properties result, State state) {
// result.setProperty("timestamp", state.getTimestamp().toInstant().toString());
// result.setProperty("sequenceNumber", Long.toString(state.getSeqId()));
//
// return result;
// }
// }
// Path: linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/core/init/InitJenaLinkedGeoData.java
import org.aksw.linkedgeodata.osm.replication.dao.State;
import org.aksw.linkedgeodata.osm.replication.dao.StateImpl;
import org.apache.jena.enhanced.BuiltinPersonalities;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.system.JenaSubsystemLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.topbraid.spin.util.SimpleImplementation;
package org.aksw.linkedgeodata.core.init;
public class InitJenaLinkedGeoData
implements JenaSubsystemLifecycle
{
private static final Logger logger = LoggerFactory.getLogger(InitJenaLinkedGeoData.class);
public void start() {
logger.debug("LinkedGeoData Jena initialization");
init();
}
@Override
public void stop() {
}
public static final Resource State = ResourceFactory.createResource("http://example.org/osm/State");
public static void init() {
BuiltinPersonalities.model | .add(State.class, new SimpleImplementation(State.asNode(), StateImpl.class)); |
splendidbits/play-pushservices | module/app/models/pushservices/db/Recipient.java | // Path: module/app/enums/pushservices/RecipientState.java
// public enum RecipientState {
// @EnumValue("IDLE")
// STATE_IDLE,
//
// @EnumValue("PROCESSING")
// STATE_PROCESSING,
//
// @EnumValue("FAILED")
// STATE_FAILED,
//
// @EnumValue("WAITING_RETRY")
// STATE_WAITING_RETRY,
//
// @EnumValue("COMPLETE")
// STATE_COMPLETE;
//
// RecipientState() {
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import enums.pushservices.RecipientState;
import io.ebean.Finder;
import io.ebean.Model;
import javax.annotation.Nonnull;
import javax.persistence.*;
import java.util.Date; | package models.pushservices.db;
@Entity
@Table(name = "recipients", schema = "pushservices")
public class Recipient extends Model {
public static Finder<Long, Recipient> find = new Finder<>(Recipient.class);
@Id
@JsonIgnore
@Column(name = "id")
@SequenceGenerator(name = "gen", sequenceName = "pushservices.recipient_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
private Long id;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private PlatformFailure failure;
@Column(name = "token", columnDefinition = "TEXT")
private String token;
@ManyToOne
private Message message;
@Column(name = "state") | // Path: module/app/enums/pushservices/RecipientState.java
// public enum RecipientState {
// @EnumValue("IDLE")
// STATE_IDLE,
//
// @EnumValue("PROCESSING")
// STATE_PROCESSING,
//
// @EnumValue("FAILED")
// STATE_FAILED,
//
// @EnumValue("WAITING_RETRY")
// STATE_WAITING_RETRY,
//
// @EnumValue("COMPLETE")
// STATE_COMPLETE;
//
// RecipientState() {
// }
// }
// Path: module/app/models/pushservices/db/Recipient.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import enums.pushservices.RecipientState;
import io.ebean.Finder;
import io.ebean.Model;
import javax.annotation.Nonnull;
import javax.persistence.*;
import java.util.Date;
package models.pushservices.db;
@Entity
@Table(name = "recipients", schema = "pushservices")
public class Recipient extends Model {
public static Finder<Long, Recipient> find = new Finder<>(Recipient.class);
@Id
@JsonIgnore
@Column(name = "id")
@SequenceGenerator(name = "gen", sequenceName = "pushservices.recipient_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
private Long id;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private PlatformFailure failure;
@Column(name = "token", columnDefinition = "TEXT")
private String token;
@ManyToOne
private Message message;
@Column(name = "state") | private RecipientState state; |
splendidbits/play-pushservices | module/app/injection/pushservices/providers/PushServicesEbeanServerProvider.java | // Path: module/app/main/pushservices/Constants.java
// public class Constants {
// public static final String CONFIG_PREFIX = "pushservices";
// }
| import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueType;
import io.ebean.EbeanServer;
import io.ebean.EbeanServerFactory;
import io.ebean.config.ServerConfig;
import main.pushservices.Constants;
import models.pushservices.db.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties; | package injection.pushservices.providers;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 4/2/16 Splendid Bits.
*/
@Singleton
public class PushServicesEbeanServerProvider implements Provider<EbeanServer> {
private final Config configuration;
@Inject
public PushServicesEbeanServerProvider(Config configuration) {
this.configuration = configuration;
}
@Override
public EbeanServer get() {
if (configuration == null || configuration.isEmpty()) {
throw new RuntimeException("No Play Framework configuration found.");
}
| // Path: module/app/main/pushservices/Constants.java
// public class Constants {
// public static final String CONFIG_PREFIX = "pushservices";
// }
// Path: module/app/injection/pushservices/providers/PushServicesEbeanServerProvider.java
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueType;
import io.ebean.EbeanServer;
import io.ebean.EbeanServerFactory;
import io.ebean.config.ServerConfig;
import main.pushservices.Constants;
import models.pushservices.db.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
package injection.pushservices.providers;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 4/2/16 Splendid Bits.
*/
@Singleton
public class PushServicesEbeanServerProvider implements Provider<EbeanServer> {
private final Config configuration;
@Inject
public PushServicesEbeanServerProvider(Config configuration) {
this.configuration = configuration;
}
@Override
public EbeanServer get() {
if (configuration == null || configuration.isEmpty()) {
throw new RuntimeException("No Play Framework configuration found.");
}
| Config pushServicesConfig = configuration.withOnlyPath(Constants.CONFIG_PREFIX); |
splendidbits/play-pushservices | module/test/main/PushServicesApplicationTest.java | // Path: module/app/injection/pushservices/modules/PushServicesModule.java
// public class PushServicesModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(EbeanServer.class)
// .annotatedWith(PushServicesEbeanServer.class)
// .toProvider(PushServicesEbeanServerProvider.class)
// .in(Singleton.class);
//
// bind(PushLifecycleListener.class)
// .asEagerSingleton();
// }
// }
| import injection.pushservices.modules.PushServicesModule;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import play.Application;
import play.Mode;
import play.api.inject.Binding;
import play.api.inject.BindingKey;
import play.api.routing.Router;
import play.inject.ApplicationLifecycle;
import play.inject.guice.GuiceApplicationBuilder;
import play.routing.RoutingDsl;
import play.test.Helpers;
import javax.inject.Inject;
import javax.inject.Provider; | package main;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 28/12/2016 Splendid Bits.
*/
public abstract class PushServicesApplicationTest {
public static Application application;
@BeforeClass
public static void startApplicationTest() {
// Mock the router binding.
Binding<Router> routesBindingOverride = new BindingKey<>(Router.class)
.toProvider(MockRouterProvider.class)
.eagerly();
application = new GuiceApplicationBuilder()
.in(Mode.TEST)
.configure("pushservices.name", "sample_app")
.configure("pushservices.driver", "org.postgresql.Driver")
.configure("pushservices.databasePlatformName", "postgres")
.configure("pushservices.url", "jdbc:postgresql://localhost:5432/pushservices_sample")
.configure("pushservices.username", "sampleuser")
.configure("pushservices.password", "samplepass") | // Path: module/app/injection/pushservices/modules/PushServicesModule.java
// public class PushServicesModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(EbeanServer.class)
// .annotatedWith(PushServicesEbeanServer.class)
// .toProvider(PushServicesEbeanServerProvider.class)
// .in(Singleton.class);
//
// bind(PushLifecycleListener.class)
// .asEagerSingleton();
// }
// }
// Path: module/test/main/PushServicesApplicationTest.java
import injection.pushservices.modules.PushServicesModule;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import play.Application;
import play.Mode;
import play.api.inject.Binding;
import play.api.inject.BindingKey;
import play.api.routing.Router;
import play.inject.ApplicationLifecycle;
import play.inject.guice.GuiceApplicationBuilder;
import play.routing.RoutingDsl;
import play.test.Helpers;
import javax.inject.Inject;
import javax.inject.Provider;
package main;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 28/12/2016 Splendid Bits.
*/
public abstract class PushServicesApplicationTest {
public static Application application;
@BeforeClass
public static void startApplicationTest() {
// Mock the router binding.
Binding<Router> routesBindingOverride = new BindingKey<>(Router.class)
.toProvider(MockRouterProvider.class)
.eagerly();
application = new GuiceApplicationBuilder()
.in(Mode.TEST)
.configure("pushservices.name", "sample_app")
.configure("pushservices.driver", "org.postgresql.Driver")
.configure("pushservices.databasePlatformName", "postgres")
.configure("pushservices.url", "jdbc:postgresql://localhost:5432/pushservices_sample")
.configure("pushservices.username", "sampleuser")
.configure("pushservices.password", "samplepass") | .bindings(new PushServicesModule()) |
splendidbits/play-pushservices | module/app/models/pushservices/db/Message.java | // Path: module/app/enums/pushservices/MessagePriority.java
// public enum MessagePriority {
// @EnumValue("low")
// PRIORITY_LOW,
//
// @EnumValue("normal")
// PRIORITY_NORMAL,
//
// @EnumValue("high")
// PRIORITY_HIGH,
// }
| import enums.pushservices.MessagePriority;
import io.ebean.Finder;
import io.ebean.Model;
import io.ebean.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Date;
import java.util.List; | package models.pushservices.db;
@Entity
@Table(name = "messages", schema = "pushservices")
public class Message extends Model {
public static Finder<Long, Message> find = new Finder<>(Message.class);
private static final int TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 7;
@Id
@JsonIgnore
@Column(name = "id")
@SequenceGenerator(name = "gen", sequenceName = "pushservices.message_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Recipient> recipients;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "credentials_id")
private Credentials credentials;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<PayloadElement> payloadData;
@Column(name = "collapse_key")
private String collapseKey;
@Column(name = "priority")
@Enumerated(EnumType.STRING) | // Path: module/app/enums/pushservices/MessagePriority.java
// public enum MessagePriority {
// @EnumValue("low")
// PRIORITY_LOW,
//
// @EnumValue("normal")
// PRIORITY_NORMAL,
//
// @EnumValue("high")
// PRIORITY_HIGH,
// }
// Path: module/app/models/pushservices/db/Message.java
import enums.pushservices.MessagePriority;
import io.ebean.Finder;
import io.ebean.Model;
import io.ebean.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
package models.pushservices.db;
@Entity
@Table(name = "messages", schema = "pushservices")
public class Message extends Model {
public static Finder<Long, Message> find = new Finder<>(Message.class);
private static final int TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 7;
@Id
@JsonIgnore
@Column(name = "id")
@SequenceGenerator(name = "gen", sequenceName = "pushservices.message_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Recipient> recipients;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "credentials_id")
private Credentials credentials;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<PayloadElement> payloadData;
@Column(name = "collapse_key")
private String collapseKey;
@Column(name = "priority")
@Enumerated(EnumType.STRING) | private MessagePriority messagePriority = MessagePriority.PRIORITY_NORMAL; |
splendidbits/play-pushservices | module/app/dao/pushservices/MessagesDao.java | // Path: module/app/enums/pushservices/RecipientState.java
// public enum RecipientState {
// @EnumValue("IDLE")
// STATE_IDLE,
//
// @EnumValue("PROCESSING")
// STATE_PROCESSING,
//
// @EnumValue("FAILED")
// STATE_FAILED,
//
// @EnumValue("WAITING_RETRY")
// STATE_WAITING_RETRY,
//
// @EnumValue("COMPLETE")
// STATE_COMPLETE;
//
// RecipientState() {
// }
// }
//
// Path: module/app/models/pushservices/db/Message.java
// @Entity
// @Table(name = "messages", schema = "pushservices")
// public class Message extends Model {
// public static Finder<Long, Message> find = new Finder<>(Message.class);
// private static final int TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 7;
//
// @Id
// @JsonIgnore
// @Column(name = "id")
// @SequenceGenerator(name = "gen", sequenceName = "pushservices.message_id_seq", allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
// private Long id;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<Recipient> recipients;
//
// @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JoinColumn(name = "credentials_id")
// private Credentials credentials;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<PayloadElement> payloadData;
//
// @Column(name = "collapse_key")
// private String collapseKey;
//
// @Column(name = "priority")
// @Enumerated(EnumType.STRING)
// private MessagePriority messagePriority = MessagePriority.PRIORITY_NORMAL;
//
// @Column(name = "ttl_seconds")
// private int ttlSeconds = TTL_SECONDS_DEFAULT;
//
// @Column(name = "delay_while_idle")
// private boolean shouldDelayWhileIdle;
//
// @Column(name = "dry_run")
// private boolean dryRun;
//
// @Column(name = "maximum_retries")
// private int maximumRetries = 10;
//
// @Basic
// @Column(name = "added_time", columnDefinition = "timestamp without time zone")
// @Temporal(TemporalType.TIMESTAMP)
// private Date addedTime;
//
// @PrePersist
// public void updatedTime() {
// setAddedTime(new Date());
// }
//
// public Long getId() {
// return id;
// }
//
// public List<Recipient> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(List<Recipient> recipients) {
// this.recipients = recipients;
// }
//
// public Credentials getCredentials() {
// return credentials;
// }
//
// public void setCredentials(Credentials credentials) {
// this.credentials = credentials;
// }
//
// public List<PayloadElement> getPayloadData() {
// return payloadData;
// }
//
// public void setPayloadData(List<PayloadElement> payloadData) {
// this.payloadData = payloadData;
// }
//
// public String getCollapseKey() {
// return collapseKey;
// }
//
// public void setCollapseKey(String collapseKey) {
// this.collapseKey = collapseKey;
// }
//
// public MessagePriority getMessagePriority() {
// return messagePriority;
// }
//
// public void setMessagePriority(MessagePriority messagePriority) {
// this.messagePriority = messagePriority;
// }
//
// public int getTtlSeconds() {
// return ttlSeconds;
// }
//
// public void setTtlSeconds(int ttlSeconds) {
// this.ttlSeconds = ttlSeconds;
// }
//
// public boolean isShouldDelayWhileIdle() {
// return shouldDelayWhileIdle;
// }
//
// public void setShouldDelayWhileIdle(boolean shouldDelayWhileIdle) {
// this.shouldDelayWhileIdle = shouldDelayWhileIdle;
// }
//
// public boolean isDryRun() {
// return dryRun;
// }
//
// public void setDryRun(boolean dryRun) {
// this.dryRun = dryRun;
// }
//
// public int getMaximumRetries() {
// return maximumRetries;
// }
//
// public void setMaximumRetries(int maximumRetries) {
// this.maximumRetries = maximumRetries;
// }
//
// public Date getAddedTime() {
// return addedTime;
// }
//
// private void setAddedTime(Date addedTime) {
// this.addedTime = addedTime;
// }
// }
| import annotations.pushservices.PushServicesEbeanServer;
import enums.pushservices.RecipientState;
import io.ebean.EbeanServer;
import io.ebean.FetchConfig;
import models.pushservices.db.Message;
import play.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List; | package dao.pushservices;
/**
* Message persistence.
* <p>
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 5/10/16 Splendid Bits.
*/
public class MessagesDao {
private final EbeanServer mEbeanServer;
@Inject
public MessagesDao(@PushServicesEbeanServer EbeanServer ebeanServer) {
mEbeanServer = ebeanServer;
}
/**
* Delete everything!
* @return success boolean
*/
public boolean wipeAll() {
try { | // Path: module/app/enums/pushservices/RecipientState.java
// public enum RecipientState {
// @EnumValue("IDLE")
// STATE_IDLE,
//
// @EnumValue("PROCESSING")
// STATE_PROCESSING,
//
// @EnumValue("FAILED")
// STATE_FAILED,
//
// @EnumValue("WAITING_RETRY")
// STATE_WAITING_RETRY,
//
// @EnumValue("COMPLETE")
// STATE_COMPLETE;
//
// RecipientState() {
// }
// }
//
// Path: module/app/models/pushservices/db/Message.java
// @Entity
// @Table(name = "messages", schema = "pushservices")
// public class Message extends Model {
// public static Finder<Long, Message> find = new Finder<>(Message.class);
// private static final int TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 7;
//
// @Id
// @JsonIgnore
// @Column(name = "id")
// @SequenceGenerator(name = "gen", sequenceName = "pushservices.message_id_seq", allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
// private Long id;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<Recipient> recipients;
//
// @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JoinColumn(name = "credentials_id")
// private Credentials credentials;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<PayloadElement> payloadData;
//
// @Column(name = "collapse_key")
// private String collapseKey;
//
// @Column(name = "priority")
// @Enumerated(EnumType.STRING)
// private MessagePriority messagePriority = MessagePriority.PRIORITY_NORMAL;
//
// @Column(name = "ttl_seconds")
// private int ttlSeconds = TTL_SECONDS_DEFAULT;
//
// @Column(name = "delay_while_idle")
// private boolean shouldDelayWhileIdle;
//
// @Column(name = "dry_run")
// private boolean dryRun;
//
// @Column(name = "maximum_retries")
// private int maximumRetries = 10;
//
// @Basic
// @Column(name = "added_time", columnDefinition = "timestamp without time zone")
// @Temporal(TemporalType.TIMESTAMP)
// private Date addedTime;
//
// @PrePersist
// public void updatedTime() {
// setAddedTime(new Date());
// }
//
// public Long getId() {
// return id;
// }
//
// public List<Recipient> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(List<Recipient> recipients) {
// this.recipients = recipients;
// }
//
// public Credentials getCredentials() {
// return credentials;
// }
//
// public void setCredentials(Credentials credentials) {
// this.credentials = credentials;
// }
//
// public List<PayloadElement> getPayloadData() {
// return payloadData;
// }
//
// public void setPayloadData(List<PayloadElement> payloadData) {
// this.payloadData = payloadData;
// }
//
// public String getCollapseKey() {
// return collapseKey;
// }
//
// public void setCollapseKey(String collapseKey) {
// this.collapseKey = collapseKey;
// }
//
// public MessagePriority getMessagePriority() {
// return messagePriority;
// }
//
// public void setMessagePriority(MessagePriority messagePriority) {
// this.messagePriority = messagePriority;
// }
//
// public int getTtlSeconds() {
// return ttlSeconds;
// }
//
// public void setTtlSeconds(int ttlSeconds) {
// this.ttlSeconds = ttlSeconds;
// }
//
// public boolean isShouldDelayWhileIdle() {
// return shouldDelayWhileIdle;
// }
//
// public void setShouldDelayWhileIdle(boolean shouldDelayWhileIdle) {
// this.shouldDelayWhileIdle = shouldDelayWhileIdle;
// }
//
// public boolean isDryRun() {
// return dryRun;
// }
//
// public void setDryRun(boolean dryRun) {
// this.dryRun = dryRun;
// }
//
// public int getMaximumRetries() {
// return maximumRetries;
// }
//
// public void setMaximumRetries(int maximumRetries) {
// this.maximumRetries = maximumRetries;
// }
//
// public Date getAddedTime() {
// return addedTime;
// }
//
// private void setAddedTime(Date addedTime) {
// this.addedTime = addedTime;
// }
// }
// Path: module/app/dao/pushservices/MessagesDao.java
import annotations.pushservices.PushServicesEbeanServer;
import enums.pushservices.RecipientState;
import io.ebean.EbeanServer;
import io.ebean.FetchConfig;
import models.pushservices.db.Message;
import play.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
package dao.pushservices;
/**
* Message persistence.
* <p>
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 5/10/16 Splendid Bits.
*/
public class MessagesDao {
private final EbeanServer mEbeanServer;
@Inject
public MessagesDao(@PushServicesEbeanServer EbeanServer ebeanServer) {
mEbeanServer = ebeanServer;
}
/**
* Delete everything!
* @return success boolean
*/
public boolean wipeAll() {
try { | List<Message> messages = mEbeanServer.find(Message.class).findList(); |
splendidbits/play-pushservices | module/app/dao/pushservices/MessagesDao.java | // Path: module/app/enums/pushservices/RecipientState.java
// public enum RecipientState {
// @EnumValue("IDLE")
// STATE_IDLE,
//
// @EnumValue("PROCESSING")
// STATE_PROCESSING,
//
// @EnumValue("FAILED")
// STATE_FAILED,
//
// @EnumValue("WAITING_RETRY")
// STATE_WAITING_RETRY,
//
// @EnumValue("COMPLETE")
// STATE_COMPLETE;
//
// RecipientState() {
// }
// }
//
// Path: module/app/models/pushservices/db/Message.java
// @Entity
// @Table(name = "messages", schema = "pushservices")
// public class Message extends Model {
// public static Finder<Long, Message> find = new Finder<>(Message.class);
// private static final int TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 7;
//
// @Id
// @JsonIgnore
// @Column(name = "id")
// @SequenceGenerator(name = "gen", sequenceName = "pushservices.message_id_seq", allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
// private Long id;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<Recipient> recipients;
//
// @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JoinColumn(name = "credentials_id")
// private Credentials credentials;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<PayloadElement> payloadData;
//
// @Column(name = "collapse_key")
// private String collapseKey;
//
// @Column(name = "priority")
// @Enumerated(EnumType.STRING)
// private MessagePriority messagePriority = MessagePriority.PRIORITY_NORMAL;
//
// @Column(name = "ttl_seconds")
// private int ttlSeconds = TTL_SECONDS_DEFAULT;
//
// @Column(name = "delay_while_idle")
// private boolean shouldDelayWhileIdle;
//
// @Column(name = "dry_run")
// private boolean dryRun;
//
// @Column(name = "maximum_retries")
// private int maximumRetries = 10;
//
// @Basic
// @Column(name = "added_time", columnDefinition = "timestamp without time zone")
// @Temporal(TemporalType.TIMESTAMP)
// private Date addedTime;
//
// @PrePersist
// public void updatedTime() {
// setAddedTime(new Date());
// }
//
// public Long getId() {
// return id;
// }
//
// public List<Recipient> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(List<Recipient> recipients) {
// this.recipients = recipients;
// }
//
// public Credentials getCredentials() {
// return credentials;
// }
//
// public void setCredentials(Credentials credentials) {
// this.credentials = credentials;
// }
//
// public List<PayloadElement> getPayloadData() {
// return payloadData;
// }
//
// public void setPayloadData(List<PayloadElement> payloadData) {
// this.payloadData = payloadData;
// }
//
// public String getCollapseKey() {
// return collapseKey;
// }
//
// public void setCollapseKey(String collapseKey) {
// this.collapseKey = collapseKey;
// }
//
// public MessagePriority getMessagePriority() {
// return messagePriority;
// }
//
// public void setMessagePriority(MessagePriority messagePriority) {
// this.messagePriority = messagePriority;
// }
//
// public int getTtlSeconds() {
// return ttlSeconds;
// }
//
// public void setTtlSeconds(int ttlSeconds) {
// this.ttlSeconds = ttlSeconds;
// }
//
// public boolean isShouldDelayWhileIdle() {
// return shouldDelayWhileIdle;
// }
//
// public void setShouldDelayWhileIdle(boolean shouldDelayWhileIdle) {
// this.shouldDelayWhileIdle = shouldDelayWhileIdle;
// }
//
// public boolean isDryRun() {
// return dryRun;
// }
//
// public void setDryRun(boolean dryRun) {
// this.dryRun = dryRun;
// }
//
// public int getMaximumRetries() {
// return maximumRetries;
// }
//
// public void setMaximumRetries(int maximumRetries) {
// this.maximumRetries = maximumRetries;
// }
//
// public Date getAddedTime() {
// return addedTime;
// }
//
// private void setAddedTime(Date addedTime) {
// this.addedTime = addedTime;
// }
// }
| import annotations.pushservices.PushServicesEbeanServer;
import enums.pushservices.RecipientState;
import io.ebean.EbeanServer;
import io.ebean.FetchConfig;
import models.pushservices.db.Message;
import play.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List; | * @return true if the message was updated.
*/
public boolean saveMessage(@Nonnull Message message) {
try {
mEbeanServer.save(message);
return true;
} catch (Exception e) {
Logger.error(String.format("Error saving/updating messages into database: %s.", e.getMessage()));
}
return false;
}
/**
* Get a list of all {@link Message}s from the database which contains recipients who
* have not yet fully taskCompleted the push lifecycle. Do not filter out message properties,
* as we want them to remain completely unadulterated, as a later .save()
* will need to persist the entire bean children.
*/
@Nonnull
public List<Message> fetchPendingMessages() {
List<Message> pendingMessages = new ArrayList<>();
try {
pendingMessages = mEbeanServer.find(Message.class)
.fetch("recipients", new FetchConfig().lazy())
.fetch("recipients.failure", new FetchConfig().lazy())
.fetch("credentials", new FetchConfig().lazy())
.fetch("payloadData", new FetchConfig().lazy())
.where()
.disjunction() | // Path: module/app/enums/pushservices/RecipientState.java
// public enum RecipientState {
// @EnumValue("IDLE")
// STATE_IDLE,
//
// @EnumValue("PROCESSING")
// STATE_PROCESSING,
//
// @EnumValue("FAILED")
// STATE_FAILED,
//
// @EnumValue("WAITING_RETRY")
// STATE_WAITING_RETRY,
//
// @EnumValue("COMPLETE")
// STATE_COMPLETE;
//
// RecipientState() {
// }
// }
//
// Path: module/app/models/pushservices/db/Message.java
// @Entity
// @Table(name = "messages", schema = "pushservices")
// public class Message extends Model {
// public static Finder<Long, Message> find = new Finder<>(Message.class);
// private static final int TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 7;
//
// @Id
// @JsonIgnore
// @Column(name = "id")
// @SequenceGenerator(name = "gen", sequenceName = "pushservices.message_id_seq", allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
// private Long id;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<Recipient> recipients;
//
// @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// @JoinColumn(name = "credentials_id")
// private Credentials credentials;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private List<PayloadElement> payloadData;
//
// @Column(name = "collapse_key")
// private String collapseKey;
//
// @Column(name = "priority")
// @Enumerated(EnumType.STRING)
// private MessagePriority messagePriority = MessagePriority.PRIORITY_NORMAL;
//
// @Column(name = "ttl_seconds")
// private int ttlSeconds = TTL_SECONDS_DEFAULT;
//
// @Column(name = "delay_while_idle")
// private boolean shouldDelayWhileIdle;
//
// @Column(name = "dry_run")
// private boolean dryRun;
//
// @Column(name = "maximum_retries")
// private int maximumRetries = 10;
//
// @Basic
// @Column(name = "added_time", columnDefinition = "timestamp without time zone")
// @Temporal(TemporalType.TIMESTAMP)
// private Date addedTime;
//
// @PrePersist
// public void updatedTime() {
// setAddedTime(new Date());
// }
//
// public Long getId() {
// return id;
// }
//
// public List<Recipient> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(List<Recipient> recipients) {
// this.recipients = recipients;
// }
//
// public Credentials getCredentials() {
// return credentials;
// }
//
// public void setCredentials(Credentials credentials) {
// this.credentials = credentials;
// }
//
// public List<PayloadElement> getPayloadData() {
// return payloadData;
// }
//
// public void setPayloadData(List<PayloadElement> payloadData) {
// this.payloadData = payloadData;
// }
//
// public String getCollapseKey() {
// return collapseKey;
// }
//
// public void setCollapseKey(String collapseKey) {
// this.collapseKey = collapseKey;
// }
//
// public MessagePriority getMessagePriority() {
// return messagePriority;
// }
//
// public void setMessagePriority(MessagePriority messagePriority) {
// this.messagePriority = messagePriority;
// }
//
// public int getTtlSeconds() {
// return ttlSeconds;
// }
//
// public void setTtlSeconds(int ttlSeconds) {
// this.ttlSeconds = ttlSeconds;
// }
//
// public boolean isShouldDelayWhileIdle() {
// return shouldDelayWhileIdle;
// }
//
// public void setShouldDelayWhileIdle(boolean shouldDelayWhileIdle) {
// this.shouldDelayWhileIdle = shouldDelayWhileIdle;
// }
//
// public boolean isDryRun() {
// return dryRun;
// }
//
// public void setDryRun(boolean dryRun) {
// this.dryRun = dryRun;
// }
//
// public int getMaximumRetries() {
// return maximumRetries;
// }
//
// public void setMaximumRetries(int maximumRetries) {
// this.maximumRetries = maximumRetries;
// }
//
// public Date getAddedTime() {
// return addedTime;
// }
//
// private void setAddedTime(Date addedTime) {
// this.addedTime = addedTime;
// }
// }
// Path: module/app/dao/pushservices/MessagesDao.java
import annotations.pushservices.PushServicesEbeanServer;
import enums.pushservices.RecipientState;
import io.ebean.EbeanServer;
import io.ebean.FetchConfig;
import models.pushservices.db.Message;
import play.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
* @return true if the message was updated.
*/
public boolean saveMessage(@Nonnull Message message) {
try {
mEbeanServer.save(message);
return true;
} catch (Exception e) {
Logger.error(String.format("Error saving/updating messages into database: %s.", e.getMessage()));
}
return false;
}
/**
* Get a list of all {@link Message}s from the database which contains recipients who
* have not yet fully taskCompleted the push lifecycle. Do not filter out message properties,
* as we want them to remain completely unadulterated, as a later .save()
* will need to persist the entire bean children.
*/
@Nonnull
public List<Message> fetchPendingMessages() {
List<Message> pendingMessages = new ArrayList<>();
try {
pendingMessages = mEbeanServer.find(Message.class)
.fetch("recipients", new FetchConfig().lazy())
.fetch("recipients.failure", new FetchConfig().lazy())
.fetch("credentials", new FetchConfig().lazy())
.fetch("payloadData", new FetchConfig().lazy())
.where()
.disjunction() | .eq("recipients.state", RecipientState.STATE_IDLE) |
splendidbits/play-pushservices | module/app/injection/pushservices/modules/PushServicesModule.java | // Path: module/app/injection/pushservices/providers/PushServicesEbeanServerProvider.java
// @Singleton
// public class PushServicesEbeanServerProvider implements Provider<EbeanServer> {
// private final Config configuration;
//
// @Inject
// public PushServicesEbeanServerProvider(Config configuration) {
// this.configuration = configuration;
// }
//
// @Override
// public EbeanServer get() {
// if (configuration == null || configuration.isEmpty()) {
// throw new RuntimeException("No Play Framework configuration found.");
// }
//
// Config pushServicesConfig = configuration.withOnlyPath(Constants.CONFIG_PREFIX);
// if (pushServicesConfig == null) {
// throw new RuntimeException("No push services configuration found. Refer to documentation");
// }
//
// // Build custom properties from main configuration.
// Properties properties = new Properties();
// for (Map.Entry<String, ConfigValue> configEntry : pushServicesConfig.entrySet()) {
// String[] keyParts = configEntry.getKey().split("\\.");
// if (keyParts.length < 2) {
// continue;
// }
//
// String key = keyParts[keyParts.length-1];
// String value = configEntry.getValue().render();
// if (configEntry.getValue().valueType().equals(ConfigValueType.STRING)) {
// value = (String) configEntry.getValue().unwrapped();
// }
// properties.put(key, value);
// }
//
// ArrayList<Class<?>> models = new ArrayList<>();
// models.add(Credentials.class);
// models.add(Message.class);
// models.add(PayloadElement.class);
// models.add(Recipient.class);
// models.add(PlatformFailure.class);
//
// ServerConfig serverConfig = new ServerConfig();
// serverConfig.loadFromProperties(properties);
//
// serverConfig.setRegister(true);
// serverConfig.setDefaultServer(true);
// serverConfig.setUpdatesDeleteMissingChildren(false);
// serverConfig.setClasses(models);
//
// serverConfig.setDdlGenerate(false);
// serverConfig.setName(Constants.CONFIG_PREFIX);
// return EbeanServerFactory.create(serverConfig);
// }
// }
//
// Path: module/app/main/pushservices/PushLifecycleListener.java
// public class PushLifecycleListener {
//
// @Inject
// public PushLifecycleListener(@PushServicesEbeanServer EbeanServer ebeanServer, ApplicationLifecycle lifecycle, TaskQueue taskQueue) {
// taskQueue.startup();
// lifecycle.addStopHook(() -> CompletableFuture.runAsync(() -> {
// ebeanServer.shutdown(true, false);
// taskQueue.shutdown();
// }));
// }
// }
| import annotations.pushservices.PushServicesEbeanServer;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import injection.pushservices.providers.PushServicesEbeanServerProvider;
import io.ebean.EbeanServer;
import main.pushservices.PushLifecycleListener; | package injection.pushservices.modules;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 02/01/2017 Splendid Bits.
*/
public class PushServicesModule extends AbstractModule {
@Override
protected void configure() {
bind(EbeanServer.class)
.annotatedWith(PushServicesEbeanServer.class) | // Path: module/app/injection/pushservices/providers/PushServicesEbeanServerProvider.java
// @Singleton
// public class PushServicesEbeanServerProvider implements Provider<EbeanServer> {
// private final Config configuration;
//
// @Inject
// public PushServicesEbeanServerProvider(Config configuration) {
// this.configuration = configuration;
// }
//
// @Override
// public EbeanServer get() {
// if (configuration == null || configuration.isEmpty()) {
// throw new RuntimeException("No Play Framework configuration found.");
// }
//
// Config pushServicesConfig = configuration.withOnlyPath(Constants.CONFIG_PREFIX);
// if (pushServicesConfig == null) {
// throw new RuntimeException("No push services configuration found. Refer to documentation");
// }
//
// // Build custom properties from main configuration.
// Properties properties = new Properties();
// for (Map.Entry<String, ConfigValue> configEntry : pushServicesConfig.entrySet()) {
// String[] keyParts = configEntry.getKey().split("\\.");
// if (keyParts.length < 2) {
// continue;
// }
//
// String key = keyParts[keyParts.length-1];
// String value = configEntry.getValue().render();
// if (configEntry.getValue().valueType().equals(ConfigValueType.STRING)) {
// value = (String) configEntry.getValue().unwrapped();
// }
// properties.put(key, value);
// }
//
// ArrayList<Class<?>> models = new ArrayList<>();
// models.add(Credentials.class);
// models.add(Message.class);
// models.add(PayloadElement.class);
// models.add(Recipient.class);
// models.add(PlatformFailure.class);
//
// ServerConfig serverConfig = new ServerConfig();
// serverConfig.loadFromProperties(properties);
//
// serverConfig.setRegister(true);
// serverConfig.setDefaultServer(true);
// serverConfig.setUpdatesDeleteMissingChildren(false);
// serverConfig.setClasses(models);
//
// serverConfig.setDdlGenerate(false);
// serverConfig.setName(Constants.CONFIG_PREFIX);
// return EbeanServerFactory.create(serverConfig);
// }
// }
//
// Path: module/app/main/pushservices/PushLifecycleListener.java
// public class PushLifecycleListener {
//
// @Inject
// public PushLifecycleListener(@PushServicesEbeanServer EbeanServer ebeanServer, ApplicationLifecycle lifecycle, TaskQueue taskQueue) {
// taskQueue.startup();
// lifecycle.addStopHook(() -> CompletableFuture.runAsync(() -> {
// ebeanServer.shutdown(true, false);
// taskQueue.shutdown();
// }));
// }
// }
// Path: module/app/injection/pushservices/modules/PushServicesModule.java
import annotations.pushservices.PushServicesEbeanServer;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import injection.pushservices.providers.PushServicesEbeanServerProvider;
import io.ebean.EbeanServer;
import main.pushservices.PushLifecycleListener;
package injection.pushservices.modules;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 02/01/2017 Splendid Bits.
*/
public class PushServicesModule extends AbstractModule {
@Override
protected void configure() {
bind(EbeanServer.class)
.annotatedWith(PushServicesEbeanServer.class) | .toProvider(PushServicesEbeanServerProvider.class) |
splendidbits/play-pushservices | module/app/injection/pushservices/modules/PushServicesModule.java | // Path: module/app/injection/pushservices/providers/PushServicesEbeanServerProvider.java
// @Singleton
// public class PushServicesEbeanServerProvider implements Provider<EbeanServer> {
// private final Config configuration;
//
// @Inject
// public PushServicesEbeanServerProvider(Config configuration) {
// this.configuration = configuration;
// }
//
// @Override
// public EbeanServer get() {
// if (configuration == null || configuration.isEmpty()) {
// throw new RuntimeException("No Play Framework configuration found.");
// }
//
// Config pushServicesConfig = configuration.withOnlyPath(Constants.CONFIG_PREFIX);
// if (pushServicesConfig == null) {
// throw new RuntimeException("No push services configuration found. Refer to documentation");
// }
//
// // Build custom properties from main configuration.
// Properties properties = new Properties();
// for (Map.Entry<String, ConfigValue> configEntry : pushServicesConfig.entrySet()) {
// String[] keyParts = configEntry.getKey().split("\\.");
// if (keyParts.length < 2) {
// continue;
// }
//
// String key = keyParts[keyParts.length-1];
// String value = configEntry.getValue().render();
// if (configEntry.getValue().valueType().equals(ConfigValueType.STRING)) {
// value = (String) configEntry.getValue().unwrapped();
// }
// properties.put(key, value);
// }
//
// ArrayList<Class<?>> models = new ArrayList<>();
// models.add(Credentials.class);
// models.add(Message.class);
// models.add(PayloadElement.class);
// models.add(Recipient.class);
// models.add(PlatformFailure.class);
//
// ServerConfig serverConfig = new ServerConfig();
// serverConfig.loadFromProperties(properties);
//
// serverConfig.setRegister(true);
// serverConfig.setDefaultServer(true);
// serverConfig.setUpdatesDeleteMissingChildren(false);
// serverConfig.setClasses(models);
//
// serverConfig.setDdlGenerate(false);
// serverConfig.setName(Constants.CONFIG_PREFIX);
// return EbeanServerFactory.create(serverConfig);
// }
// }
//
// Path: module/app/main/pushservices/PushLifecycleListener.java
// public class PushLifecycleListener {
//
// @Inject
// public PushLifecycleListener(@PushServicesEbeanServer EbeanServer ebeanServer, ApplicationLifecycle lifecycle, TaskQueue taskQueue) {
// taskQueue.startup();
// lifecycle.addStopHook(() -> CompletableFuture.runAsync(() -> {
// ebeanServer.shutdown(true, false);
// taskQueue.shutdown();
// }));
// }
// }
| import annotations.pushservices.PushServicesEbeanServer;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import injection.pushservices.providers.PushServicesEbeanServerProvider;
import io.ebean.EbeanServer;
import main.pushservices.PushLifecycleListener; | package injection.pushservices.modules;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 02/01/2017 Splendid Bits.
*/
public class PushServicesModule extends AbstractModule {
@Override
protected void configure() {
bind(EbeanServer.class)
.annotatedWith(PushServicesEbeanServer.class)
.toProvider(PushServicesEbeanServerProvider.class)
.in(Singleton.class);
| // Path: module/app/injection/pushservices/providers/PushServicesEbeanServerProvider.java
// @Singleton
// public class PushServicesEbeanServerProvider implements Provider<EbeanServer> {
// private final Config configuration;
//
// @Inject
// public PushServicesEbeanServerProvider(Config configuration) {
// this.configuration = configuration;
// }
//
// @Override
// public EbeanServer get() {
// if (configuration == null || configuration.isEmpty()) {
// throw new RuntimeException("No Play Framework configuration found.");
// }
//
// Config pushServicesConfig = configuration.withOnlyPath(Constants.CONFIG_PREFIX);
// if (pushServicesConfig == null) {
// throw new RuntimeException("No push services configuration found. Refer to documentation");
// }
//
// // Build custom properties from main configuration.
// Properties properties = new Properties();
// for (Map.Entry<String, ConfigValue> configEntry : pushServicesConfig.entrySet()) {
// String[] keyParts = configEntry.getKey().split("\\.");
// if (keyParts.length < 2) {
// continue;
// }
//
// String key = keyParts[keyParts.length-1];
// String value = configEntry.getValue().render();
// if (configEntry.getValue().valueType().equals(ConfigValueType.STRING)) {
// value = (String) configEntry.getValue().unwrapped();
// }
// properties.put(key, value);
// }
//
// ArrayList<Class<?>> models = new ArrayList<>();
// models.add(Credentials.class);
// models.add(Message.class);
// models.add(PayloadElement.class);
// models.add(Recipient.class);
// models.add(PlatformFailure.class);
//
// ServerConfig serverConfig = new ServerConfig();
// serverConfig.loadFromProperties(properties);
//
// serverConfig.setRegister(true);
// serverConfig.setDefaultServer(true);
// serverConfig.setUpdatesDeleteMissingChildren(false);
// serverConfig.setClasses(models);
//
// serverConfig.setDdlGenerate(false);
// serverConfig.setName(Constants.CONFIG_PREFIX);
// return EbeanServerFactory.create(serverConfig);
// }
// }
//
// Path: module/app/main/pushservices/PushLifecycleListener.java
// public class PushLifecycleListener {
//
// @Inject
// public PushLifecycleListener(@PushServicesEbeanServer EbeanServer ebeanServer, ApplicationLifecycle lifecycle, TaskQueue taskQueue) {
// taskQueue.startup();
// lifecycle.addStopHook(() -> CompletableFuture.runAsync(() -> {
// ebeanServer.shutdown(true, false);
// taskQueue.shutdown();
// }));
// }
// }
// Path: module/app/injection/pushservices/modules/PushServicesModule.java
import annotations.pushservices.PushServicesEbeanServer;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import injection.pushservices.providers.PushServicesEbeanServerProvider;
import io.ebean.EbeanServer;
import main.pushservices.PushLifecycleListener;
package injection.pushservices.modules;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 02/01/2017 Splendid Bits.
*/
public class PushServicesModule extends AbstractModule {
@Override
protected void configure() {
bind(EbeanServer.class)
.annotatedWith(PushServicesEbeanServer.class)
.toProvider(PushServicesEbeanServerProvider.class)
.in(Singleton.class);
| bind(PushLifecycleListener.class) |
splendidbits/play-pushservices | module/app/models/pushservices/db/Credentials.java | // Path: module/app/enums/pushservices/PlatformType.java
// public enum PlatformType {
// @EnumValue("GCM")
// SERVICE_GCM("GCM", "https://fcm.googleapis.com/fcm/send"),
//
// @EnumValue( "APNS")
// SERVICE_APNS("APNS", "https://gateway.sandbox.push.apple.com");
//
// public String name;
// public String url;
// PlatformType(String name, String url) {
// this.name = name;
// this.url = url;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import enums.pushservices.PlatformType;
import io.ebean.Finder;
import io.ebean.Model;
import javax.persistence.*; | package models.pushservices.db;
@Entity
@Table(name = "credentials", schema = "pushservices")
public class Credentials extends Model {
public static Finder<Long, Credentials> find = new Finder<>(Credentials.class);
@Id
@JsonIgnore
@Column(name = "id")
@SequenceGenerator(name = "gen", sequenceName = "pushservices.credentials_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
protected Long id;
@OneToOne(mappedBy = "credentials")
private Message message;
@Enumerated(EnumType.STRING)
@Column(name = "platform") | // Path: module/app/enums/pushservices/PlatformType.java
// public enum PlatformType {
// @EnumValue("GCM")
// SERVICE_GCM("GCM", "https://fcm.googleapis.com/fcm/send"),
//
// @EnumValue( "APNS")
// SERVICE_APNS("APNS", "https://gateway.sandbox.push.apple.com");
//
// public String name;
// public String url;
// PlatformType(String name, String url) {
// this.name = name;
// this.url = url;
// }
// }
// Path: module/app/models/pushservices/db/Credentials.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import enums.pushservices.PlatformType;
import io.ebean.Finder;
import io.ebean.Model;
import javax.persistence.*;
package models.pushservices.db;
@Entity
@Table(name = "credentials", schema = "pushservices")
public class Credentials extends Model {
public static Finder<Long, Credentials> find = new Finder<>(Credentials.class);
@Id
@JsonIgnore
@Column(name = "id")
@SequenceGenerator(name = "gen", sequenceName = "pushservices.credentials_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
protected Long id;
@OneToOne(mappedBy = "credentials")
private Message message;
@Enumerated(EnumType.STRING)
@Column(name = "platform") | private PlatformType platformType; |
splendidbits/play-pushservices | sample/app/injection/ApplicationClassLoader.java | // Path: module/app/injection/pushservices/modules/PushServicesModule.java
// public class PushServicesModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(EbeanServer.class)
// .annotatedWith(PushServicesEbeanServer.class)
// .toProvider(PushServicesEbeanServerProvider.class)
// .in(Singleton.class);
//
// bind(PushLifecycleListener.class)
// .asEagerSingleton();
// }
// }
| import injection.pushservices.modules.PushServicesModule;
import play.ApplicationLoader;
import play.inject.guice.GuiceApplicationBuilder;
import play.inject.guice.GuiceApplicationLoader; | package injection;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 01/01/2017 Splendid Bits.
*/
public class ApplicationClassLoader extends GuiceApplicationLoader {
@Override
public GuiceApplicationBuilder builder(ApplicationLoader.Context context) {
return initialBuilder
.in(context.environment()) | // Path: module/app/injection/pushservices/modules/PushServicesModule.java
// public class PushServicesModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(EbeanServer.class)
// .annotatedWith(PushServicesEbeanServer.class)
// .toProvider(PushServicesEbeanServerProvider.class)
// .in(Singleton.class);
//
// bind(PushLifecycleListener.class)
// .asEagerSingleton();
// }
// }
// Path: sample/app/injection/ApplicationClassLoader.java
import injection.pushservices.modules.PushServicesModule;
import play.ApplicationLoader;
import play.inject.guice.GuiceApplicationBuilder;
import play.inject.guice.GuiceApplicationLoader;
package injection;
/**
* GNU General Public License v3.0.
* (This means you can use it as you wish, host and share modifications.)
* Copyright 01/01/2017 Splendid Bits.
*/
public class ApplicationClassLoader extends GuiceApplicationLoader {
@Override
public GuiceApplicationBuilder builder(ApplicationLoader.Context context) {
return initialBuilder
.in(context.environment()) | .bindings(new PushServicesModule()); |
aikuma/aikuma | Aikuma/src/org/lp20/aikuma/audio/record/analyzers/ThresholdSpeechAnalyzer.java | // Path: Aikuma/src/org/lp20/aikuma/audio/record/AudioHandler.java
// public interface AudioHandler {
//
// /**
// * The caller has detected non-silent audio.
// *
// * @param buffer An array of samples.
// * @param justChanged Whether the caller has just changed
// * from silence to audio.
// */
// public void audioTriggered(short[] buffer, boolean justChanged);
//
// /**
// * The caller has detected silent audio.
// *
// * @param buffer An array of samples.
// * @param justChanged Whether the caller has just changed
// * from audio to silence.
// */
// public void silenceTriggered(short[] buffer, boolean justChanged);
// }
//
// Path: Aikuma/src/org/lp20/aikuma/audio/record/analyzers/Analyzer.java
// public abstract class Analyzer {
//
// /**
// * A recorder calls this to analyze the incoming
// * audio data.
// *
// * Depending on the outcome, it either calls back
// * * audioTriggered
// * * silenceTriggered
// * where the first should be called if there is
// * something worthwhile to record and the second
// * if we detected only silence.
// *
// * @param handler Any AudioHandler.
// * @param buffer An array of audio samples.
// */
// public abstract void analyze(AudioHandler handler, short[] buffer);
//
// /**
// * Resets the analyzer to default values.
// */
// public abstract void reset();
// }
//
// Path: Aikuma/src/org/lp20/aikuma/audio/record/recognizers/Recognizer.java
// public abstract class Recognizer {
//
// /**
// * Determines whether a buffer represents silence.
// *
// * @param buffer The buffer containing the audio
// * @return true if silence; false otherwise
// */
// public abstract boolean isSilence(short[] buffer);
//
// /**
// * Determines whether a buffer represents speech.
// *
// * @param buffer The buffer containing the audio
// * @return true if speech; false otherwise
// */
// public abstract boolean isSpeech(short[] buffer);
// }
| import java.util.Arrays;
import android.util.Log;
import org.lp20.aikuma.audio.record.AudioHandler;
import org.lp20.aikuma.audio.record.analyzers.Analyzer;
import org.lp20.aikuma.audio.record.recognizers.Recognizer;
import org.lp20.aikuma.audio.record.recognizers.AverageRecognizer; | short[] copiedBuffer = Arrays.copyOf(buffer, buffer.length);
// Add the copied current buffer onto the end.
//
for (int i = 0; i < buffer.length; i++) {
onsetBuffer[i + offset] = copiedBuffer[i];
}
}
/** Clear the before speech buffer. */
protected void clearOnsetBuffer() {
onsetBuffer = new short[] {};
}
/** Clear the after speech buffer. */
protected void clearAfterBuffer() {
afterBuffer = new short[] {};
}
/** Analyzes if there's speech.
*
* Switches back and forth between modes:
* If in silent mode (speech == false), it will
* wait until speech occurs.
* If speech occurs, it will hand over a combined buffer.
*
* @param handler An AudioHandler that handles audio/silence.
* @param buffer The buffer with audio samples.
*/ | // Path: Aikuma/src/org/lp20/aikuma/audio/record/AudioHandler.java
// public interface AudioHandler {
//
// /**
// * The caller has detected non-silent audio.
// *
// * @param buffer An array of samples.
// * @param justChanged Whether the caller has just changed
// * from silence to audio.
// */
// public void audioTriggered(short[] buffer, boolean justChanged);
//
// /**
// * The caller has detected silent audio.
// *
// * @param buffer An array of samples.
// * @param justChanged Whether the caller has just changed
// * from audio to silence.
// */
// public void silenceTriggered(short[] buffer, boolean justChanged);
// }
//
// Path: Aikuma/src/org/lp20/aikuma/audio/record/analyzers/Analyzer.java
// public abstract class Analyzer {
//
// /**
// * A recorder calls this to analyze the incoming
// * audio data.
// *
// * Depending on the outcome, it either calls back
// * * audioTriggered
// * * silenceTriggered
// * where the first should be called if there is
// * something worthwhile to record and the second
// * if we detected only silence.
// *
// * @param handler Any AudioHandler.
// * @param buffer An array of audio samples.
// */
// public abstract void analyze(AudioHandler handler, short[] buffer);
//
// /**
// * Resets the analyzer to default values.
// */
// public abstract void reset();
// }
//
// Path: Aikuma/src/org/lp20/aikuma/audio/record/recognizers/Recognizer.java
// public abstract class Recognizer {
//
// /**
// * Determines whether a buffer represents silence.
// *
// * @param buffer The buffer containing the audio
// * @return true if silence; false otherwise
// */
// public abstract boolean isSilence(short[] buffer);
//
// /**
// * Determines whether a buffer represents speech.
// *
// * @param buffer The buffer containing the audio
// * @return true if speech; false otherwise
// */
// public abstract boolean isSpeech(short[] buffer);
// }
// Path: Aikuma/src/org/lp20/aikuma/audio/record/analyzers/ThresholdSpeechAnalyzer.java
import java.util.Arrays;
import android.util.Log;
import org.lp20.aikuma.audio.record.AudioHandler;
import org.lp20.aikuma.audio.record.analyzers.Analyzer;
import org.lp20.aikuma.audio.record.recognizers.Recognizer;
import org.lp20.aikuma.audio.record.recognizers.AverageRecognizer;
short[] copiedBuffer = Arrays.copyOf(buffer, buffer.length);
// Add the copied current buffer onto the end.
//
for (int i = 0; i < buffer.length; i++) {
onsetBuffer[i + offset] = copiedBuffer[i];
}
}
/** Clear the before speech buffer. */
protected void clearOnsetBuffer() {
onsetBuffer = new short[] {};
}
/** Clear the after speech buffer. */
protected void clearAfterBuffer() {
afterBuffer = new short[] {};
}
/** Analyzes if there's speech.
*
* Switches back and forth between modes:
* If in silent mode (speech == false), it will
* wait until speech occurs.
* If speech occurs, it will hand over a combined buffer.
*
* @param handler An AudioHandler that handles audio/silence.
* @param buffer The buffer with audio samples.
*/ | public void analyze(AudioHandler handler, short[] buffer) { |
pentaho/pentaho-engineering-samples | Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/groups/PentahoSamlNativeUserRoleListService.java | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
| import org.pentaho.platform.api.engine.IUserRoleListService;
import org.pentaho.platform.api.mt.ITenant;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.spring.security.saml.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set; | package org.pentaho.platform.spring.security.saml.groups;
public class PentahoSamlNativeUserRoleListService implements IUserRoleListService {
private static final Logger logger = LoggerFactory.getLogger( PentahoSamlNativeUserRoleListService.class );
private List<String> systemRoles;
private PentahoSamlNativeUserDetailsService userDetailsService;
public PentahoSamlNativeUserRoleListService( PentahoSamlNativeUserDetailsService userDetailsService ) {
Assert.notNull( userDetailsService );
setUserDetailsService( userDetailsService );
}
@Override
public List<String> getAllRoles() { | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
// Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/groups/PentahoSamlNativeUserRoleListService.java
import org.pentaho.platform.api.engine.IUserRoleListService;
import org.pentaho.platform.api.mt.ITenant;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.spring.security.saml.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
package org.pentaho.platform.spring.security.saml.groups;
public class PentahoSamlNativeUserRoleListService implements IUserRoleListService {
private static final Logger logger = LoggerFactory.getLogger( PentahoSamlNativeUserRoleListService.class );
private List<String> systemRoles;
private PentahoSamlNativeUserDetailsService userDetailsService;
public PentahoSamlNativeUserRoleListService( PentahoSamlNativeUserDetailsService userDetailsService ) {
Assert.notNull( userDetailsService );
setUserDetailsService( userDetailsService );
}
@Override
public List<String> getAllRoles() { | return Arrays.asList( Utils.getDefaultRole().getAuthority() ); |
pentaho/pentaho-engineering-samples | Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/logout/PentahoSamlSuccessLogoutHandler.java | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
| import org.pentaho.platform.spring.security.saml.Utils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; | package org.pentaho.platform.spring.security.saml.logout;
public class PentahoSamlSuccessLogoutHandler extends SimpleUrlLogoutSuccessHandler {
public void onLogoutSuccess( HttpServletRequest request, HttpServletResponse response, Authentication auth ) throws
IOException, ServletException {
if( auth != null ) { | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
// Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/logout/PentahoSamlSuccessLogoutHandler.java
import org.pentaho.platform.spring.security.saml.Utils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
package org.pentaho.platform.spring.security.saml.logout;
public class PentahoSamlSuccessLogoutHandler extends SimpleUrlLogoutSuccessHandler {
public void onLogoutSuccess( HttpServletRequest request, HttpServletResponse response, Authentication auth ) throws
IOException, ServletException {
if( auth != null ) { | Utils.getUserMap().remove( auth.getPrincipal().toString() ); |
pentaho/pentaho-engineering-samples | Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/logout/PentahoSamlLogoutProcessingFilter.java | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
| import org.pentaho.platform.proxy.impl.ProxyException;
import org.pentaho.platform.spring.security.saml.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.saml.SAMLLogoutProcessingFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException; | package org.pentaho.platform.spring.security.saml.logout;
public class PentahoSamlLogoutProcessingFilter extends SAMLLogoutProcessingFilter {
private static final Logger LOGGER = LoggerFactory.getLogger( PentahoSamlLogoutProcessingFilter.class );
private boolean requireProxyWrapping = true;
public PentahoSamlLogoutProcessingFilter( String logoutSuccessUrl, LogoutHandler... handlers ) {
super( logoutSuccessUrl, handlers );
}
public PentahoSamlLogoutProcessingFilter( LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers ) {
super( logoutSuccessHandler, handlers );
}
@Override
public void processLogout( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
throws IOException, ServletException {
if ( requiresLogout( request, response ) ) {
try {
| // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
// Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/logout/PentahoSamlLogoutProcessingFilter.java
import org.pentaho.platform.proxy.impl.ProxyException;
import org.pentaho.platform.spring.security.saml.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.saml.SAMLLogoutProcessingFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
package org.pentaho.platform.spring.security.saml.logout;
public class PentahoSamlLogoutProcessingFilter extends SAMLLogoutProcessingFilter {
private static final Logger LOGGER = LoggerFactory.getLogger( PentahoSamlLogoutProcessingFilter.class );
private boolean requireProxyWrapping = true;
public PentahoSamlLogoutProcessingFilter( String logoutSuccessUrl, LogoutHandler... handlers ) {
super( logoutSuccessUrl, handlers );
}
public PentahoSamlLogoutProcessingFilter( LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers ) {
super( logoutSuccessHandler, handlers );
}
@Override
public void processLogout( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
throws IOException, ServletException {
if ( requiresLogout( request, response ) ) {
try {
| Authentication auth = Utils.getAuthenticationFromRequest( request, isRequireProxyWrapping() ); |
pentaho/pentaho-engineering-samples | Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/groups/PentahoSamlNativeUserDetailsService.java | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.schema.impl.XSAnyImpl;
import org.opensaml.xml.schema.impl.XSStringImpl;
import org.pentaho.platform.api.mt.ITenantedPrincipleNameResolver;
import org.pentaho.platform.spring.security.saml.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.saml.SAMLCredential;
import org.springframework.security.saml.userdetails.SAMLUserDetailsService; | package org.pentaho.platform.spring.security.saml.groups;
/**
* Checks the users attributes list, to try and fetch the roles from there
* The user credentials are those sent within the SAML Authentication Response
*/
public class PentahoSamlNativeUserDetailsService implements SAMLUserDetailsService, UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger( PentahoSamlNativeUserDetailsService.class );
/**
* The attribute in the users' attribute list that corresponds to our Pentaho Roles.
* A user may carry a multitude of attributes ( age, email, drivers' license, list of favourite books , ..
* One such attribute will be a 'list of Pentaho Roles'
* */
private String roleRelatedUserAttributeName;
/**
* (optional) attribute values may hold a prefix that helps to contextualize that specific value;
* Example: in a attribute such as 'List of OKTA SSO-based Application Roles' the values may be:
* 'Pentaho:Report Author',
* 'Zendesk:CTools Support',
* 'Office365:Contributor C1',
* 'Pentaho:Authenticated',
* ...
*/
private String roleRelatedAttributePrefix;
ITenantedPrincipleNameResolver tenantedPrincipleNameResolver;
@Override
public Object loadUserBySAML( SAMLCredential credential ) throws UsernameNotFoundException {
if( credential == null || credential.getNameID() == null || credential.getNameID().getValue() == null ){
throw new UsernameNotFoundException( "invalid/null SAMLCredential" );
}
String username = credential.getNameID().getValue();
try {
// check the userDetailsMap for a UserDetails stored for this username. If we have one already, use it
return loadUserByUsername( username );
} catch ( UsernameNotFoundException usernameNotFoundException ) {
// no UserDetails found = new user coming in, create a UserDetails for it and store it in the userDetailsMap
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
// Add the defaultRole. default role is usually "Authenticated" | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/Utils.java
// public class Utils {
//
// public final static String SPRING_2_SECURITY_CTX_KEY = "SPRING_SECURITY_CONTEXT";
//
// /**
// * roles considered to be the basic ones and that should be immediately assigned to any SAML authenticated user;
// */
// static GrantedAuthority defaultRole;
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request ) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// return getAuthenticationFromRequest( request, true );
// }
//
// public static Authentication getAuthenticationFromRequest( ServletRequest request, boolean requireProxyWrapping) throws NoSuchMethodException,
// InvocationTargetException, IllegalAccessException, ProxyException {
// Authentication authentication = null;
//
// if ( request != null && request instanceof HttpServletRequest
// && ( (HttpServletRequest) request ).getSession( false ) != null
// && ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY ) != null ) {
//
// // step 1 - get spring 2 SecurityContext object stored in the HttpRequest
// Object s2SecurityContextObj =
// ( (HttpServletRequest) request ).getSession( false ).getAttribute( SPRING_2_SECURITY_CTX_KEY );
//
// // step 2 - grab spring 2 SecurityContext's getAuthentication() method
// Method getAuthenticationMethod = s2SecurityContextObj.getClass().getMethod( "getAuthentication" /* no-args */ );
//
// if ( getAuthenticationMethod != null ) {
//
// // to ensure no IllegalAccessException occurs
// getAuthenticationMethod.setAccessible( true );
//
// // step 3 - get spring 2 Authentication object
// Object s2AuthenticationObj = getAuthenticationMethod.invoke( s2SecurityContextObj );
//
// if(s2AuthenticationObj != null) {
// if (requireProxyWrapping ) {
// // step 4 - proxy wrap spring 2 Authentication object into a spring 4 one
// IProxyFactory factory = PentahoSystem.get( IProxyFactory.class );
// Object s4AuthenticationProxy = factory.createProxy( s2AuthenticationObj );
//
// if ( s4AuthenticationProxy != null && s4AuthenticationProxy instanceof Authentication ) {
// authentication = (Authentication) s4AuthenticationProxy;
// }
// } else {
// authentication = (Authentication)s2AuthenticationObj;
// }
//
// }
// }
// }
//
// return authentication;
// }
//
// public static Map<String, UserDetails> getUserMap() {
// Map<String, String> props = new HashMap();
// props.put( "name", "saml.user.map" );
// return PentahoSystem.get( Map.class, null, props );
// }
//
// public static GrantedAuthority getDefaultRole() {
// if ( defaultRole == null ) {
// String defaultRoleAsString = PentahoSystem.get( String.class, "defaultRole", null );
// if ( defaultRoleAsString != null && defaultRoleAsString.length() > 0 ) {
// defaultRole = new SimpleGrantedAuthority( defaultRoleAsString );
// }
// }
// return defaultRole;
// }
// }
// Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/groups/PentahoSamlNativeUserDetailsService.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.schema.impl.XSAnyImpl;
import org.opensaml.xml.schema.impl.XSStringImpl;
import org.pentaho.platform.api.mt.ITenantedPrincipleNameResolver;
import org.pentaho.platform.spring.security.saml.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.saml.SAMLCredential;
import org.springframework.security.saml.userdetails.SAMLUserDetailsService;
package org.pentaho.platform.spring.security.saml.groups;
/**
* Checks the users attributes list, to try and fetch the roles from there
* The user credentials are those sent within the SAML Authentication Response
*/
public class PentahoSamlNativeUserDetailsService implements SAMLUserDetailsService, UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger( PentahoSamlNativeUserDetailsService.class );
/**
* The attribute in the users' attribute list that corresponds to our Pentaho Roles.
* A user may carry a multitude of attributes ( age, email, drivers' license, list of favourite books , ..
* One such attribute will be a 'list of Pentaho Roles'
* */
private String roleRelatedUserAttributeName;
/**
* (optional) attribute values may hold a prefix that helps to contextualize that specific value;
* Example: in a attribute such as 'List of OKTA SSO-based Application Roles' the values may be:
* 'Pentaho:Report Author',
* 'Zendesk:CTools Support',
* 'Office365:Contributor C1',
* 'Pentaho:Authenticated',
* ...
*/
private String roleRelatedAttributePrefix;
ITenantedPrincipleNameResolver tenantedPrincipleNameResolver;
@Override
public Object loadUserBySAML( SAMLCredential credential ) throws UsernameNotFoundException {
if( credential == null || credential.getNameID() == null || credential.getNameID().getValue() == null ){
throw new UsernameNotFoundException( "invalid/null SAMLCredential" );
}
String username = credential.getNameID().getValue();
try {
// check the userDetailsMap for a UserDetails stored for this username. If we have one already, use it
return loadUserByUsername( username );
} catch ( UsernameNotFoundException usernameNotFoundException ) {
// no UserDetails found = new user coming in, create a UserDetails for it and store it in the userDetailsMap
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
// Add the defaultRole. default role is usually "Authenticated" | authorities.add( Utils.getDefaultRole() ); |
pentaho/pentaho-engineering-samples | Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/PentahoSamlUserRoleListService.java | // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/groups/PentahoSamlNativeUserRoleListService.java
// public class PentahoSamlNativeUserRoleListService implements IUserRoleListService {
//
// private static final Logger logger = LoggerFactory.getLogger( PentahoSamlNativeUserRoleListService.class );
//
// private List<String> systemRoles;
//
// private PentahoSamlNativeUserDetailsService userDetailsService;
//
// public PentahoSamlNativeUserRoleListService( PentahoSamlNativeUserDetailsService userDetailsService ) {
// Assert.notNull( userDetailsService );
// setUserDetailsService( userDetailsService );
// }
//
// @Override
// public List<String> getAllRoles() {
// return Arrays.asList( Utils.getDefaultRole().getAuthority() );
// }
//
// @Override
// public List<String> getSystemRoles() {
// if ( systemRoles == null ) {
// systemRoles = PentahoSystem.get( ArrayList.class, "singleTenantSystemAuthorities", null );
// }
// return systemRoles;
// }
//
// @Override
// public List<String> getAllRoles( ITenant iTenant ) {
// // Return the default role as the only possible role from SAML
// return getAllRoles();
// }
//
// @Override
// public List<String> getAllUsers() {
// return null; /* not supported */
// }
//
// @Override
// public List<String> getAllUsers( ITenant iTenant ) {
// return null; /* not supported */
// }
//
// @Override
// public List<String> getUsersInRole( ITenant iTenant, String role ) {
//
// /* iTenant is not supported */
//
// List<String> usersInRole = new ArrayList<String>();
//
// Set<String> usernameSet = Utils.getUserMap().keySet();
//
// for ( String username : usernameSet ) {
//
// List<String> userRoles = null;
//
// if ( ( userRoles = getRolesForUser( null, username ) ) != null ) {
//
// if ( userRoles.contains( role ) ) {
// usersInRole.add( username );
// }
// }
// }
//
// return usersInRole;
// }
//
// @Override
// public List<String> getRolesForUser( ITenant iTenant, String user ) throws UsernameNotFoundException {
//
// /* iTenant is not supported */
//
// List<String> roles = new ArrayList<String>();
//
// try {
// UserDetails userDetails = getUserDetailsService().loadUserByUsername( user );
//
// if ( userDetails == null ) {
// logger.warn( "Got a null from calling the method loadUserByUsername( String username ) of UserDetailsService: "
// + getUserDetailsService()
// + ". This is an interface violation beacuse it is specified that loadUserByUsername method should never return null. Throwing a UsernameNotFoundException." );
// throw new UsernameNotFoundException( user );
// }
//
// Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
//
// if ( authorities != null ) {
// for ( GrantedAuthority authority : authorities ) {
// roles.add( authority.getAuthority() );
// }
// } else {
// logger.warn( "Got a null from calling the method getAuthorities() of UserDetails: " + userDetails
// + ". This is an interface violation beacuse it is specified that getAuthorities() method should never return null. Considered no GrantedAuthorities for username "
// + user );
// }
//
// } catch ( UsernameNotFoundException usernameNotFoundException ) {
// // The user does not exist in the UserDetailsService. Do nothing and return an empty list of roles
// }
// return roles;
// }
//
// public PentahoSamlNativeUserDetailsService getUserDetailsService() {
// return userDetailsService;
// }
//
// public void setUserDetailsService( PentahoSamlNativeUserDetailsService userDetailsService ) {
// this.userDetailsService = userDetailsService;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.pentaho.platform.api.engine.IUserRoleListService;
import org.pentaho.platform.api.mt.ITenant;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.spring.security.saml.groups.PentahoSamlNativeUserRoleListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert; | package org.pentaho.platform.spring.security.saml;
public class PentahoSamlUserRoleListService implements IUserRoleListService {
private static Logger logger = LoggerFactory.getLogger( PentahoSamlUserRoleListService.class );
private static final String PROVIDER_NAME = "providerName";
//Delegate user role list service
private IUserRoleListService service;
private String selectedAuthorizationProvider;
| // Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/groups/PentahoSamlNativeUserRoleListService.java
// public class PentahoSamlNativeUserRoleListService implements IUserRoleListService {
//
// private static final Logger logger = LoggerFactory.getLogger( PentahoSamlNativeUserRoleListService.class );
//
// private List<String> systemRoles;
//
// private PentahoSamlNativeUserDetailsService userDetailsService;
//
// public PentahoSamlNativeUserRoleListService( PentahoSamlNativeUserDetailsService userDetailsService ) {
// Assert.notNull( userDetailsService );
// setUserDetailsService( userDetailsService );
// }
//
// @Override
// public List<String> getAllRoles() {
// return Arrays.asList( Utils.getDefaultRole().getAuthority() );
// }
//
// @Override
// public List<String> getSystemRoles() {
// if ( systemRoles == null ) {
// systemRoles = PentahoSystem.get( ArrayList.class, "singleTenantSystemAuthorities", null );
// }
// return systemRoles;
// }
//
// @Override
// public List<String> getAllRoles( ITenant iTenant ) {
// // Return the default role as the only possible role from SAML
// return getAllRoles();
// }
//
// @Override
// public List<String> getAllUsers() {
// return null; /* not supported */
// }
//
// @Override
// public List<String> getAllUsers( ITenant iTenant ) {
// return null; /* not supported */
// }
//
// @Override
// public List<String> getUsersInRole( ITenant iTenant, String role ) {
//
// /* iTenant is not supported */
//
// List<String> usersInRole = new ArrayList<String>();
//
// Set<String> usernameSet = Utils.getUserMap().keySet();
//
// for ( String username : usernameSet ) {
//
// List<String> userRoles = null;
//
// if ( ( userRoles = getRolesForUser( null, username ) ) != null ) {
//
// if ( userRoles.contains( role ) ) {
// usersInRole.add( username );
// }
// }
// }
//
// return usersInRole;
// }
//
// @Override
// public List<String> getRolesForUser( ITenant iTenant, String user ) throws UsernameNotFoundException {
//
// /* iTenant is not supported */
//
// List<String> roles = new ArrayList<String>();
//
// try {
// UserDetails userDetails = getUserDetailsService().loadUserByUsername( user );
//
// if ( userDetails == null ) {
// logger.warn( "Got a null from calling the method loadUserByUsername( String username ) of UserDetailsService: "
// + getUserDetailsService()
// + ". This is an interface violation beacuse it is specified that loadUserByUsername method should never return null. Throwing a UsernameNotFoundException." );
// throw new UsernameNotFoundException( user );
// }
//
// Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
//
// if ( authorities != null ) {
// for ( GrantedAuthority authority : authorities ) {
// roles.add( authority.getAuthority() );
// }
// } else {
// logger.warn( "Got a null from calling the method getAuthorities() of UserDetails: " + userDetails
// + ". This is an interface violation beacuse it is specified that getAuthorities() method should never return null. Considered no GrantedAuthorities for username "
// + user );
// }
//
// } catch ( UsernameNotFoundException usernameNotFoundException ) {
// // The user does not exist in the UserDetailsService. Do nothing and return an empty list of roles
// }
// return roles;
// }
//
// public PentahoSamlNativeUserDetailsService getUserDetailsService() {
// return userDetailsService;
// }
//
// public void setUserDetailsService( PentahoSamlNativeUserDetailsService userDetailsService ) {
// this.userDetailsService = userDetailsService;
// }
// }
// Path: Samples_for_Extending_Pentaho/Reference Implementations/Security/SAML 2.0/pentaho-saml/src/main/java/org/pentaho/platform/spring/security/saml/PentahoSamlUserRoleListService.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.pentaho.platform.api.engine.IUserRoleListService;
import org.pentaho.platform.api.mt.ITenant;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.spring.security.saml.groups.PentahoSamlNativeUserRoleListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
package org.pentaho.platform.spring.security.saml;
public class PentahoSamlUserRoleListService implements IUserRoleListService {
private static Logger logger = LoggerFactory.getLogger( PentahoSamlUserRoleListService.class );
private static final String PROVIDER_NAME = "providerName";
//Delegate user role list service
private IUserRoleListService service;
private String selectedAuthorizationProvider;
| private PentahoSamlNativeUserRoleListService samlUserRoleListService; |
nativelibs4java/BridJ | src/main/java/org/bridj/jawt/JAWT.java | // Path: src/main/java/org/bridj/jawt/JawtLibrary.java
// public static class JNIEnv extends TypedPointer {
//
// public JNIEnv(long address) {
// super(address);
// }
//
// public JNIEnv(Pointer address) {
// super(address);
// }
// };
| import org.bridj.Callback;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Convention;
import org.bridj.ann.Field;
import org.bridj.ann.Library;
import org.bridj.jawt.JawtLibrary.JNIEnv; | return this;
}
@Field(1)
public Pointer<GetDrawingSurface_callback> GetDrawingSurface() {
return this.io.getPointerField(this, 1);
}
@Field(2)
public Pointer<FreeDrawingSurface_callback> FreeDrawingSurface() {
return this.io.getPointerField(this, 2);
}
@Field(3)
public Pointer<Lock_callback> Lock() {
return this.io.getPointerField(this, 3);
}
@Field(4)
public Pointer<Unlock_callback> Unlock() {
return this.io.getPointerField(this, 4);
}
@Field(5)
public Pointer<GetComponent_callback> GetComponent() {
return this.io.getPointerField(this, 5);
}
public static abstract class GetDrawingSurface_callback extends Callback {
| // Path: src/main/java/org/bridj/jawt/JawtLibrary.java
// public static class JNIEnv extends TypedPointer {
//
// public JNIEnv(long address) {
// super(address);
// }
//
// public JNIEnv(Pointer address) {
// super(address);
// }
// };
// Path: src/main/java/org/bridj/jawt/JAWT.java
import org.bridj.Callback;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Convention;
import org.bridj.ann.Field;
import org.bridj.ann.Library;
import org.bridj.jawt.JawtLibrary.JNIEnv;
return this;
}
@Field(1)
public Pointer<GetDrawingSurface_callback> GetDrawingSurface() {
return this.io.getPointerField(this, 1);
}
@Field(2)
public Pointer<FreeDrawingSurface_callback> FreeDrawingSurface() {
return this.io.getPointerField(this, 2);
}
@Field(3)
public Pointer<Lock_callback> Lock() {
return this.io.getPointerField(this, 3);
}
@Field(4)
public Pointer<Unlock_callback> Unlock() {
return this.io.getPointerField(this, 4);
}
@Field(5)
public Pointer<GetComponent_callback> GetComponent() {
return this.io.getPointerField(this, 5);
}
public static abstract class GetDrawingSurface_callback extends Callback {
| public abstract Pointer<org.bridj.jawt.JAWT_DrawingSurface> invoke(Pointer<JNIEnv> env, Pointer<?> target); |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/Set.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
| import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minlp;
/**
*
* @author marcio
*/
public class Set {
private final MINLP mip;
protected final LinkedList<Integer> set;
public Set(MINLP mip, LinkedList<Integer> set) {
this.mip = mip;
this.set = set;
}
public Set(MINLP cplex, Integer ...array) {
this.mip = cplex;
this.set = new LinkedList<>();
for(Integer e: array){
this.set.add(e);
}
}
public int size(){
return set.size();
}
/*public void forAll(Consumer<? super T> action){
set.stream().forEach(action);
}*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
// Path: MINLP/src/minlp/Set.java
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minlp;
/**
*
* @author marcio
*/
public class Set {
private final MINLP mip;
protected final LinkedList<Integer> set;
public Set(MINLP mip, LinkedList<Integer> set) {
this.mip = mip;
this.set = set;
}
public Set(MINLP cplex, Integer ...array) {
this.mip = cplex;
this.set = new LinkedList<>();
for(Integer e: array){
this.set.add(e);
}
}
public int size(){
return set.size();
}
/*public void forAll(Consumer<? super T> action){
set.stream().forEach(action);
}*/ | public void forAll(Consumer action) throws Exception{ |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/Set.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
| import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minlp;
/**
*
* @author marcio
*/
public class Set {
private final MINLP mip;
protected final LinkedList<Integer> set;
public Set(MINLP mip, LinkedList<Integer> set) {
this.mip = mip;
this.set = set;
}
public Set(MINLP cplex, Integer ...array) {
this.mip = cplex;
this.set = new LinkedList<>();
for(Integer e: array){
this.set.add(e);
}
}
public int size(){
return set.size();
}
/*public void forAll(Consumer<? super T> action){
set.stream().forEach(action);
}*/
public void forAll(Consumer action) throws Exception{
set.stream().forEach((e)->{
try {
action.accept(e);
} catch (Exception ex) {
ex.printStackTrace();
}
});
} | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
// Path: MINLP/src/minlp/Set.java
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minlp;
/**
*
* @author marcio
*/
public class Set {
private final MINLP mip;
protected final LinkedList<Integer> set;
public Set(MINLP mip, LinkedList<Integer> set) {
this.mip = mip;
this.set = set;
}
public Set(MINLP cplex, Integer ...array) {
this.mip = cplex;
this.set = new LinkedList<>();
for(Integer e: array){
this.set.add(e);
}
}
public int size(){
return set.size();
}
/*public void forAll(Consumer<? super T> action){
set.stream().forEach(action);
}*/
public void forAll(Consumer action) throws Exception{
set.stream().forEach((e)->{
try {
action.accept(e);
} catch (Exception ex) {
ex.printStackTrace();
}
});
} | public Expr sum(final Function mapper) throws Exception{ |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * @return
* @throws Exception
*/
public final Set range(int begin, int end) throws Exception {
LinkedList<Integer> list = new LinkedList<>();
for(int i=begin; i<=end; i++){
list.addLast(i);
}
return new Set(this, list);
}
/**
* <pre>
* Interpratation:
* for all j in J {
* //do something here
* }
* Simtax:
* cplex.forAll(J, (j)->{
* //do something here
* });
* Sample:
* cplex.forAll(J, (j)->{
* cplex.addLe(x[j], 3);
* });
* </pre>
* @param set set of indexes
* @param action the action to be performed
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* @return
* @throws Exception
*/
public final Set range(int begin, int end) throws Exception {
LinkedList<Integer> list = new LinkedList<>();
for(int i=begin; i<=end; i++){
list.addLast(i);
}
return new Set(this, list);
}
/**
* <pre>
* Interpratation:
* for all j in J {
* //do something here
* }
* Simtax:
* cplex.forAll(J, (j)->{
* //do something here
* });
* Sample:
* cplex.forAll(J, (j)->{
* cplex.addLe(x[j], 3);
* });
* </pre>
* @param set set of indexes
* @param action the action to be performed
* @throws java.lang.Exception
*/ | public void forAll(Set set, Consumer action) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * cplex.addLe(x[j], 3);
* });
* </pre>
* @param set set of indexes
* @param action the action to be performed
* @throws java.lang.Exception
*/
public void forAll(Set set, Consumer action) throws Exception {
set.forAll(action);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, (i, j)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, (i, j)->{
* cplex.addLe(x[i][j], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* cplex.addLe(x[j], 3);
* });
* </pre>
* @param set set of indexes
* @param action the action to be performed
* @throws java.lang.Exception
*/
public void forAll(Set set, Consumer action) throws Exception {
set.forAll(action);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, (i, j)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, (i, j)->{
* cplex.addLe(x[i][j], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | public void forAll(Set s1, Set s2, Consumer2p action) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * @throws java.lang.Exception
*/
public void forAll(Set s1, Set s2, Consumer2p action) throws Exception {
s1.forAll(i ->
s2.forAll(j ->
action.accept(i, j)
)
);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J and k in K) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, K, (i, j, k)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, K, (i, j, k)->{
* cplex.addLe(x[i][j][k], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* @throws java.lang.Exception
*/
public void forAll(Set s1, Set s2, Consumer2p action) throws Exception {
s1.forAll(i ->
s2.forAll(j ->
action.accept(i, j)
)
);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J and k in K) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, K, (i, j, k)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, K, (i, j, k)->{
* cplex.addLe(x[i][j][k], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | public void forAll(Set s1, Set s2, Set s3, Consumer3p action) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | s1.forAll(i ->
s2.forAll(j ->
s3.forAll(k ->
action.accept(i, j, k)
)
)
);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J and k in K and m in M) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, K, M, (i, j, k, m)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, K, M, (i, j, k, m)->{
* cplex.addLe(x[i][j][k][m], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
s1.forAll(i ->
s2.forAll(j ->
s3.forAll(k ->
action.accept(i, j, k)
)
)
);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J and k in K and m in M) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, K, M, (i, j, k, m)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, K, M, (i, j, k, m)->{
* cplex.addLe(x[i][j][k][m], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | public void forAll(Set s1, Set s2, Set s3, Set s4, Consumer4p action) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | s4.forAll(m ->
action.accept(i, j, k, m)
)
)
)
);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J and k in K and m in M and n in N) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, K, M, N, (i, j, k, m, n)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, K, M, N, (i, j, k, m, n)->{
* cplex.addLe(x[i][j][k][m][n], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param s5 fifth set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
s4.forAll(m ->
action.accept(i, j, k, m)
)
)
)
);
}
/**
* <pre>
* Interpratation:
* for all(i in I and j in J and k in K and m in M and n in N) {
* //do something here
* }
* Simtax:
* cplex.forAll(I, J, K, M, N, (i, j, k, m, n)->{
* //do something here
* });
* Sample:
* cplex.forAll(I, J, K, M, N, (i, j, k, m, n)->{
* cplex.addLe(x[i][j][k][m][n], 3);
* });
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param s5 fifth set of index
* @param action the action to be performed
* @throws java.lang.Exception
*/ | public void forAll(Set s1, Set s2, Set s3, Set s4, Set s5, Consumer5p action) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * @param action the action to be performed
* @throws java.lang.Exception
*/
public void forAll(Set s1, Set s2, Set s3, Set s4, Set s5, Consumer5p action) throws Exception {
s1.forAll(i ->
s2.forAll(j ->
s3.forAll(k ->
s4.forAll(m ->
s5.forAll(n ->
action.accept(i, j, k, m, n)
)
)
)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I}{expression}
* Simtax:
* cplex.sum(I, i -> expression)
* Sample:
* cplex.sum(I, i -> cplex.prod(C[i],x[i]))
* </pre>
* @param set
* @param mapper
* @return
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* @param action the action to be performed
* @throws java.lang.Exception
*/
public void forAll(Set s1, Set s2, Set s3, Set s4, Set s5, Consumer5p action) throws Exception {
s1.forAll(i ->
s2.forAll(j ->
s3.forAll(k ->
s4.forAll(m ->
s5.forAll(n ->
action.accept(i, j, k, m, n)
)
)
)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I}{expression}
* Simtax:
* cplex.sum(I, i -> expression)
* Sample:
* cplex.sum(I, i -> cplex.prod(C[i],x[i]))
* </pre>
* @param set
* @param mapper
* @return
* @throws java.lang.Exception
*/ | public Expr sum(Set set, Function mapper) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * Interpratation:
* sum_{i in I}{expression}
* Simtax:
* cplex.sum(I, i -> expression)
* Sample:
* cplex.sum(I, i -> cplex.prod(C[i],x[i]))
* </pre>
* @param set
* @param mapper
* @return
* @throws java.lang.Exception
*/
public Expr sum(Set set, Function mapper) throws Exception {
return set.sum(mapper);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J}{expression}
* Simtax:
* cplex.sum(I, J, (i,j) -> expression)
* Sample:
* cplex.sum(I, J, (i,j) -> cplex.prod(C[i][j],x[i][j]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* Interpratation:
* sum_{i in I}{expression}
* Simtax:
* cplex.sum(I, i -> expression)
* Sample:
* cplex.sum(I, i -> cplex.prod(C[i],x[i]))
* </pre>
* @param set
* @param mapper
* @return
* @throws java.lang.Exception
*/
public Expr sum(Set set, Function mapper) throws Exception {
return set.sum(mapper);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J}{expression}
* Simtax:
* cplex.sum(I, J, (i,j) -> expression)
* Sample:
* cplex.sum(I, J, (i,j) -> cplex.prod(C[i][j],x[i][j]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | public Expr sum(Set s1, Set s2, Function2p mapper) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * @param s1 first set of index
* @param s2 second set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/
public Expr sum(Set s1, Set s2, Function2p mapper) throws Exception {
return
s1.sum(i ->
s2.sum(j ->
mapper.accept(i, j)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J, k in K}{expression}
* Simtax:
* cplex.sum(I, J, K, (i,j,k) -> expression)
* Sample:
* cplex.sum(I, J, K, (i,j,k) -> cplex.prod(C[i][j][k],x[i][j][k]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* @param s1 first set of index
* @param s2 second set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/
public Expr sum(Set s1, Set s2, Function2p mapper) throws Exception {
return
s1.sum(i ->
s2.sum(j ->
mapper.accept(i, j)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J, k in K}{expression}
* Simtax:
* cplex.sum(I, J, K, (i,j,k) -> expression)
* Sample:
* cplex.sum(I, J, K, (i,j,k) -> cplex.prod(C[i][j][k],x[i][j][k]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | public Expr sum(Set s1, Set s2, Set s3, Function3p mapper) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | * @return
* @throws java.lang.Exception
*/
public Expr sum(Set s1, Set s2, Set s3, Function3p mapper) throws Exception {
return
s1.sum(i ->
s2.sum(j ->
s3.sum(k ->
mapper.accept(i, j, k)
)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J, k in K, m in M}{expression}
* Simtax:
* cplex.sum(I, J, K, M, (i,j,k,m) -> expression)
* Sample:
* cplex.sum(I, J, K, M, (i,j,k,m) -> cplex.prod(C[i][j][k][m],x[i][j][k][m]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
* @return
* @throws java.lang.Exception
*/
public Expr sum(Set s1, Set s2, Set s3, Function3p mapper) throws Exception {
return
s1.sum(i ->
s2.sum(j ->
s3.sum(k ->
mapper.accept(i, j, k)
)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J, k in K, m in M}{expression}
* Simtax:
* cplex.sum(I, J, K, M, (i,j,k,m) -> expression)
* Sample:
* cplex.sum(I, J, K, M, (i,j,k,m) -> cplex.prod(C[i][j][k][m],x[i][j][k][m]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | public Expr sum(Set s1, Set s2, Set s3, Set s4, Function4p mapper) throws Exception { |
marcio-da-silva-arantes/MINLP | MINLP/src/minlp/MINLP.java | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
| import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p; | public Expr sum(Set s1, Set s2, Set s3, Set s4, Function4p mapper) throws Exception {
return
s1.sum(i ->
s2.sum(j ->
s3.sum(k ->
s4.sum(m ->
mapper.accept(i, j, k, m)
)
)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J, k in K, m in M, n in N}{expression}
* Simtax:
* cplex.sum(I, J, K, M, N, (i,j,k,m,n) -> expression)
* Sample:
* cplex.sum(I, J, K, M, N, (i,j,k,m,n) -> cplex.prod(C[i][j][k][m][n],x[i][j][k][m][n]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param s5 fifth set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | // Path: MINLP/src/minlp/stream/Function.java
// public interface Function {
// public Expr accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer.java
// public interface Consumer {
// public void accept(Integer t) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer2p.java
// public interface Consumer2p {
// public void accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer3p.java
// public interface Consumer3p {
// public void accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer4p.java
// public interface Consumer4p {
// public void accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Consumer5p.java
// public interface Consumer5p {
// public void accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function2p.java
// public interface Function2p {
// public Expr accept(Integer i, Integer j) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function3p.java
// public interface Function3p {
// public Expr accept(Integer i, Integer j, Integer k) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function4p.java
// public interface Function4p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m) throws Exception;
// }
//
// Path: MINLP/src/minlp/stream/Function5p.java
// public interface Function5p {
// public Expr accept(Integer i, Integer j, Integer k, Integer m, Integer n) throws Exception;
// }
// Path: MINLP/src/minlp/MINLP.java
import java.io.PrintStream;
import java.util.Arrays;
import minlp.stream.Function;
import minlp.stream.Consumer;
import java.util.LinkedList;
import minlp.stream.Consumer2p;
import minlp.stream.Consumer3p;
import minlp.stream.Consumer4p;
import minlp.stream.Consumer5p;
import minlp.stream.Function2p;
import minlp.stream.Function3p;
import minlp.stream.Function4p;
import minlp.stream.Function5p;
public Expr sum(Set s1, Set s2, Set s3, Set s4, Function4p mapper) throws Exception {
return
s1.sum(i ->
s2.sum(j ->
s3.sum(k ->
s4.sum(m ->
mapper.accept(i, j, k, m)
)
)
)
);
}
/**
* <pre>
* Interpratation:
* sum_{i in I, j in J, k in K, m in M, n in N}{expression}
* Simtax:
* cplex.sum(I, J, K, M, N, (i,j,k,m,n) -> expression)
* Sample:
* cplex.sum(I, J, K, M, N, (i,j,k,m,n) -> cplex.prod(C[i][j][k][m][n],x[i][j][k][m][n]))
* </pre>
* @param s1 first set of index
* @param s2 second set of index
* @param s3 third set of index
* @param s4 forth set of index
* @param s5 fifth set of index
* @param mapper
* @return
* @throws java.lang.Exception
*/ | public Expr sum(Set s1, Set s2, Set s3, Set s4, Set s5, Function5p mapper) throws Exception { |
flexgp/flexgp | comm-library/src/node/NodeList.java | // Path: comm-library/src/network/MessageType.java
// public class MessageType {
// // Control-related messages
// public final static int PING = 0;
// public static final int PING_RESPONSE = 1;
// public static int STATUS = 2;
// public static int STATUS_RESPONSE = 3;
// public static int CONTROL_FLOW = 4;
// public static int NODELIST = 5;
// public static int NODELIST_RESPONSE = 6;
// // the boundary
// public static int CONTROL = 31;
//
// // Evolve-related messages
// public static int MIGRANT_MESSAGE = 32;
// public static int BEST_INDIVIDUAL = 33;
// // the boundary
// public static int EVOLVE = 64;
//
// // Data-related messages
// public static int DATA_DESCRIPTION = 64;
// // the boundary
// public static int DATA = 96;
//
// }
//
// Path: comm-library/src/utility/IP.java
// public class IP {
// public String id;
// public String ip;
// public int port;
//
// public IP(String _id, String _ip, int _port) {
// id = _id;
// ip = _ip;
// port = _port;
// }
//
// public boolean equals(IP other) {
// return ((this.id == other.id) && (this.ip.equals(other.ip)) && (this.port == other.port));
// }
//
// @Override
// public String toString() {
// return String.valueOf(id) + ":" + ip + ":" + String.valueOf(port);
// }
//
// public static final int ipToInt(String addr) {
// String[] addrArray = addr.split("\\.");
// if (addrArray.length != 4) {
// System.err.println("Improper ip address:" + addr);
// return 0;
// }
// int num = 0;
// for (int i = 0; i < addrArray.length; i++) {
// num += ((Integer.parseInt(addrArray[i]) % 256 * Math
// .pow(256, 3 - i)));
// }
// return num;
// }
//
// public static String makeID(String ip, int port) {
// return ip + ":" + port;
// }
//
// public static String intToIp(int i) {
// return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
// + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
// }
//
// /**
// * Translate an "ip:port" pair into an IP object
// * @param ip
// * @return
// */
// public static IP fromString(String ip) {
// // split into ip and port
// // TODO this should be done in a more stable/predictable way, plus tests
// String[] splitted = ip.split(":");
// if (splitted.length == 2) {
// String id = IP.makeID(splitted[0], Integer.parseInt(splitted[1]));
// IP result = new IP(id, splitted[0], Integer.parseInt(splitted[1]));
// System.out
// .println(String.format(
// "String: %s after formatting (2): %s", ip,
// result.toString()));
// return result;
// } else if (splitted.length == 1) {
// String id = IP.makeID(splitted[0], Control.PORT);
// IP result = new IP(id, splitted[0], Control.PORT);
// System.out
// .println(String.format(
// "String: %s after formatting (1): %s", ip,
// result.toString()));
// return result;
// } else {
// System.err.println(String.format("Invalid IP entered: %s", ip));
// System.exit(-1);
// return null;
// }
// }
// }
| import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import network.MessageType;
import utility.IP; | * Return values indicating if the good/bad node tables contain an entry for
* nID
*
* @param nID
*/
public synchronized Status contains(String nID) {
if (goodNodeTable.containsKey(nID))
return Status.GOOD;
else if (badNodeTable.containsKey(nID))
return Status.BAD;
return Status.NONE;
}
public class NoSuchNodeIDException extends Exception {
private static final long serialVersionUID = 5780011381489528722L;
}
public class NoSuchIPException extends Exception {
private static final long serialVersionUID = 812997894613089723L;
}
/**
* Get a current timestamp
*
* @return
*/
public static Timestamp currTime() {
return new Timestamp(new Date().getTime());
}
| // Path: comm-library/src/network/MessageType.java
// public class MessageType {
// // Control-related messages
// public final static int PING = 0;
// public static final int PING_RESPONSE = 1;
// public static int STATUS = 2;
// public static int STATUS_RESPONSE = 3;
// public static int CONTROL_FLOW = 4;
// public static int NODELIST = 5;
// public static int NODELIST_RESPONSE = 6;
// // the boundary
// public static int CONTROL = 31;
//
// // Evolve-related messages
// public static int MIGRANT_MESSAGE = 32;
// public static int BEST_INDIVIDUAL = 33;
// // the boundary
// public static int EVOLVE = 64;
//
// // Data-related messages
// public static int DATA_DESCRIPTION = 64;
// // the boundary
// public static int DATA = 96;
//
// }
//
// Path: comm-library/src/utility/IP.java
// public class IP {
// public String id;
// public String ip;
// public int port;
//
// public IP(String _id, String _ip, int _port) {
// id = _id;
// ip = _ip;
// port = _port;
// }
//
// public boolean equals(IP other) {
// return ((this.id == other.id) && (this.ip.equals(other.ip)) && (this.port == other.port));
// }
//
// @Override
// public String toString() {
// return String.valueOf(id) + ":" + ip + ":" + String.valueOf(port);
// }
//
// public static final int ipToInt(String addr) {
// String[] addrArray = addr.split("\\.");
// if (addrArray.length != 4) {
// System.err.println("Improper ip address:" + addr);
// return 0;
// }
// int num = 0;
// for (int i = 0; i < addrArray.length; i++) {
// num += ((Integer.parseInt(addrArray[i]) % 256 * Math
// .pow(256, 3 - i)));
// }
// return num;
// }
//
// public static String makeID(String ip, int port) {
// return ip + ":" + port;
// }
//
// public static String intToIp(int i) {
// return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
// + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
// }
//
// /**
// * Translate an "ip:port" pair into an IP object
// * @param ip
// * @return
// */
// public static IP fromString(String ip) {
// // split into ip and port
// // TODO this should be done in a more stable/predictable way, plus tests
// String[] splitted = ip.split(":");
// if (splitted.length == 2) {
// String id = IP.makeID(splitted[0], Integer.parseInt(splitted[1]));
// IP result = new IP(id, splitted[0], Integer.parseInt(splitted[1]));
// System.out
// .println(String.format(
// "String: %s after formatting (2): %s", ip,
// result.toString()));
// return result;
// } else if (splitted.length == 1) {
// String id = IP.makeID(splitted[0], Control.PORT);
// IP result = new IP(id, splitted[0], Control.PORT);
// System.out
// .println(String.format(
// "String: %s after formatting (1): %s", ip,
// result.toString()));
// return result;
// } else {
// System.err.println(String.format("Invalid IP entered: %s", ip));
// System.exit(-1);
// return null;
// }
// }
// }
// Path: comm-library/src/node/NodeList.java
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import network.MessageType;
import utility.IP;
* Return values indicating if the good/bad node tables contain an entry for
* nID
*
* @param nID
*/
public synchronized Status contains(String nID) {
if (goodNodeTable.containsKey(nID))
return Status.GOOD;
else if (badNodeTable.containsKey(nID))
return Status.BAD;
return Status.NONE;
}
public class NoSuchNodeIDException extends Exception {
private static final long serialVersionUID = 5780011381489528722L;
}
public class NoSuchIPException extends Exception {
private static final long serialVersionUID = 812997894613089723L;
}
/**
* Get a current timestamp
*
* @return
*/
public static Timestamp currTime() {
return new Timestamp(new Date().getTime());
}
| public void succeed(IP ip, String s, Timestamp t) { |
flexgp/flexgp | comm-library/src/node/NodeList.java | // Path: comm-library/src/network/MessageType.java
// public class MessageType {
// // Control-related messages
// public final static int PING = 0;
// public static final int PING_RESPONSE = 1;
// public static int STATUS = 2;
// public static int STATUS_RESPONSE = 3;
// public static int CONTROL_FLOW = 4;
// public static int NODELIST = 5;
// public static int NODELIST_RESPONSE = 6;
// // the boundary
// public static int CONTROL = 31;
//
// // Evolve-related messages
// public static int MIGRANT_MESSAGE = 32;
// public static int BEST_INDIVIDUAL = 33;
// // the boundary
// public static int EVOLVE = 64;
//
// // Data-related messages
// public static int DATA_DESCRIPTION = 64;
// // the boundary
// public static int DATA = 96;
//
// }
//
// Path: comm-library/src/utility/IP.java
// public class IP {
// public String id;
// public String ip;
// public int port;
//
// public IP(String _id, String _ip, int _port) {
// id = _id;
// ip = _ip;
// port = _port;
// }
//
// public boolean equals(IP other) {
// return ((this.id == other.id) && (this.ip.equals(other.ip)) && (this.port == other.port));
// }
//
// @Override
// public String toString() {
// return String.valueOf(id) + ":" + ip + ":" + String.valueOf(port);
// }
//
// public static final int ipToInt(String addr) {
// String[] addrArray = addr.split("\\.");
// if (addrArray.length != 4) {
// System.err.println("Improper ip address:" + addr);
// return 0;
// }
// int num = 0;
// for (int i = 0; i < addrArray.length; i++) {
// num += ((Integer.parseInt(addrArray[i]) % 256 * Math
// .pow(256, 3 - i)));
// }
// return num;
// }
//
// public static String makeID(String ip, int port) {
// return ip + ":" + port;
// }
//
// public static String intToIp(int i) {
// return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
// + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
// }
//
// /**
// * Translate an "ip:port" pair into an IP object
// * @param ip
// * @return
// */
// public static IP fromString(String ip) {
// // split into ip and port
// // TODO this should be done in a more stable/predictable way, plus tests
// String[] splitted = ip.split(":");
// if (splitted.length == 2) {
// String id = IP.makeID(splitted[0], Integer.parseInt(splitted[1]));
// IP result = new IP(id, splitted[0], Integer.parseInt(splitted[1]));
// System.out
// .println(String.format(
// "String: %s after formatting (2): %s", ip,
// result.toString()));
// return result;
// } else if (splitted.length == 1) {
// String id = IP.makeID(splitted[0], Control.PORT);
// IP result = new IP(id, splitted[0], Control.PORT);
// System.out
// .println(String.format(
// "String: %s after formatting (1): %s", ip,
// result.toString()));
// return result;
// } else {
// System.err.println(String.format("Invalid IP entered: %s", ip));
// System.exit(-1);
// return null;
// }
// }
// }
| import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import network.MessageType;
import utility.IP; | /**
* Get a current timestamp
*
* @return
*/
public static Timestamp currTime() {
return new Timestamp(new Date().getTime());
}
public void succeed(IP ip, String s, Timestamp t) {
succeed(ip.id, ip.ip, ip.port, s, t);
}
public void succeed(String nodeID, NodeListEntry nle, Timestamp t) {
succeed(nodeID, nle.ip, nle.port, nle.subnetLabel, t);
}
public synchronized void succeed(String nodeID, String ip, int port,
String s, Timestamp t) {
if (nodeID.equals(this.nodeID)) {
// Don't add ourselves!
return;
}
// add an entry to the goodNodeTable
// TODO CHECK TO MAKE SURE THIS ENTRY IS MORE UP-TO-DATE
Control.println(String.format("NodeList: recording success for node %s:%d",ip,port));
if (!goodNodeTable.containsKey(nodeID)) {
if (badNodeTable.containsKey(nodeID)) {
badNodeTable.remove(nodeID);
reportDeltas(1, goodNodeTable.size(), 1, 0, -1, 0, | // Path: comm-library/src/network/MessageType.java
// public class MessageType {
// // Control-related messages
// public final static int PING = 0;
// public static final int PING_RESPONSE = 1;
// public static int STATUS = 2;
// public static int STATUS_RESPONSE = 3;
// public static int CONTROL_FLOW = 4;
// public static int NODELIST = 5;
// public static int NODELIST_RESPONSE = 6;
// // the boundary
// public static int CONTROL = 31;
//
// // Evolve-related messages
// public static int MIGRANT_MESSAGE = 32;
// public static int BEST_INDIVIDUAL = 33;
// // the boundary
// public static int EVOLVE = 64;
//
// // Data-related messages
// public static int DATA_DESCRIPTION = 64;
// // the boundary
// public static int DATA = 96;
//
// }
//
// Path: comm-library/src/utility/IP.java
// public class IP {
// public String id;
// public String ip;
// public int port;
//
// public IP(String _id, String _ip, int _port) {
// id = _id;
// ip = _ip;
// port = _port;
// }
//
// public boolean equals(IP other) {
// return ((this.id == other.id) && (this.ip.equals(other.ip)) && (this.port == other.port));
// }
//
// @Override
// public String toString() {
// return String.valueOf(id) + ":" + ip + ":" + String.valueOf(port);
// }
//
// public static final int ipToInt(String addr) {
// String[] addrArray = addr.split("\\.");
// if (addrArray.length != 4) {
// System.err.println("Improper ip address:" + addr);
// return 0;
// }
// int num = 0;
// for (int i = 0; i < addrArray.length; i++) {
// num += ((Integer.parseInt(addrArray[i]) % 256 * Math
// .pow(256, 3 - i)));
// }
// return num;
// }
//
// public static String makeID(String ip, int port) {
// return ip + ":" + port;
// }
//
// public static String intToIp(int i) {
// return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
// + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
// }
//
// /**
// * Translate an "ip:port" pair into an IP object
// * @param ip
// * @return
// */
// public static IP fromString(String ip) {
// // split into ip and port
// // TODO this should be done in a more stable/predictable way, plus tests
// String[] splitted = ip.split(":");
// if (splitted.length == 2) {
// String id = IP.makeID(splitted[0], Integer.parseInt(splitted[1]));
// IP result = new IP(id, splitted[0], Integer.parseInt(splitted[1]));
// System.out
// .println(String.format(
// "String: %s after formatting (2): %s", ip,
// result.toString()));
// return result;
// } else if (splitted.length == 1) {
// String id = IP.makeID(splitted[0], Control.PORT);
// IP result = new IP(id, splitted[0], Control.PORT);
// System.out
// .println(String.format(
// "String: %s after formatting (1): %s", ip,
// result.toString()));
// return result;
// } else {
// System.err.println(String.format("Invalid IP entered: %s", ip));
// System.exit(-1);
// return null;
// }
// }
// }
// Path: comm-library/src/node/NodeList.java
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import network.MessageType;
import utility.IP;
/**
* Get a current timestamp
*
* @return
*/
public static Timestamp currTime() {
return new Timestamp(new Date().getTime());
}
public void succeed(IP ip, String s, Timestamp t) {
succeed(ip.id, ip.ip, ip.port, s, t);
}
public void succeed(String nodeID, NodeListEntry nle, Timestamp t) {
succeed(nodeID, nle.ip, nle.port, nle.subnetLabel, t);
}
public synchronized void succeed(String nodeID, String ip, int port,
String s, Timestamp t) {
if (nodeID.equals(this.nodeID)) {
// Don't add ourselves!
return;
}
// add an entry to the goodNodeTable
// TODO CHECK TO MAKE SURE THIS ENTRY IS MORE UP-TO-DATE
Control.println(String.format("NodeList: recording success for node %s:%d",ip,port));
if (!goodNodeTable.containsKey(nodeID)) {
if (badNodeTable.containsKey(nodeID)) {
badNodeTable.remove(nodeID);
reportDeltas(1, goodNodeTable.size(), 1, 0, -1, 0, | badNodeTable.size(), 0, 1, 0, MessageType.PING); |
flexgp/flexgp | mrgp-flexgp/src/evogpj/math/Var.java | // Path: mrgp-flexgp/src/evogpj/gp/GPException.java
// public class GPException extends Exception {
//
// /**
// * Constructor for GP exceptions
// * @param string
// */
// public GPException(String string) {
// super(string);
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 2346788405132405602L;
//
// }
| import evogpj.gp.GPException;
import java.util.ArrayList;
import java.util.List; | /**
* Copyright (c) 2011-2013 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package evogpj.math;
/**
*
* @author Owen Derby and Ignacio Arnaldo
*/
public class Var extends ZeroArgFunction {
private final int ind;
/**
*
* @param label
* @param acoeff
* @throws GPException
*/ | // Path: mrgp-flexgp/src/evogpj/gp/GPException.java
// public class GPException extends Exception {
//
// /**
// * Constructor for GP exceptions
// * @param string
// */
// public GPException(String string) {
// super(string);
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 2346788405132405602L;
//
// }
// Path: mrgp-flexgp/src/evogpj/math/Var.java
import evogpj.gp.GPException;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright (c) 2011-2013 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package evogpj.math;
/**
*
* @author Owen Derby and Ignacio Arnaldo
*/
public class Var extends ZeroArgFunction {
private final int ind;
/**
*
* @param label
* @param acoeff
* @throws GPException
*/ | public Var(String label,double acoeff) throws GPException { |
flexgp/flexgp | mrgp-flexgp/src/evogpj/evaluation/java/ScaledData.java | // Path: mrgp-flexgp/src/evogpj/math/means/ArithmeticMean.java
// public class ArithmeticMean extends Mean {
//
// @Override
// public Double getMean() {
// return sum / (double) n;
// }
//
// @Override
// public void addValue(Double val) {
// incrementN();
// sum += val;
// }
//
// }
| import evogpj.math.means.ArithmeticMean;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter; | /**
* Copyright (c) 2011-2013 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package evogpj.evaluation.java;
/**
* Class which provides DataJava interface with target values scaled to the range
* [0, 1]. Using data with this transformation frees GP from having to search
* for the proper scale, allowing it to focus on just identifying the proper
* shape. See E. Y. Vladislavleva, Model-based problem solving through symbolic
* regression via pareto genetic programming, CentER, Tilburg University, 2008.
*
* @author Owen Derby and Ignacio Arnaldo
*/
public abstract class ScaledData implements DataJava {
/**
* the number of fitness cases
*/
protected int numberOfFitnessCases;
/**
* the number of features
*/
protected int numberOfFeatures;
/**
* the datapoints (input values) to evaluate individual's fitness on.
*/
protected final double[][] fitnessCases;
/**
* the datapoints (output values) to compare individual's output against to
* determine their fitness
*/
protected final double[] target;
/**
* In addition, keep a copy of the target which is scaled to be in the range
* [0, 1] This is from Vladislavleva, to "allow the GP to focus on finding
* the structure of the solution, instead of the scale"
*/
protected final double[] scaled_target;
private Double target_min;
private Double target_max;
/**
* Store the minimum value for each feature
*/
protected double[] minFeatures;
/**
* Store the maximum value for each feature
*/
protected double[] maxFeatures;
/**
* A running mean for target values, used in ModelScaler
*/ | // Path: mrgp-flexgp/src/evogpj/math/means/ArithmeticMean.java
// public class ArithmeticMean extends Mean {
//
// @Override
// public Double getMean() {
// return sum / (double) n;
// }
//
// @Override
// public void addValue(Double val) {
// incrementN();
// sum += val;
// }
//
// }
// Path: mrgp-flexgp/src/evogpj/evaluation/java/ScaledData.java
import evogpj.math.means.ArithmeticMean;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Copyright (c) 2011-2013 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package evogpj.evaluation.java;
/**
* Class which provides DataJava interface with target values scaled to the range
* [0, 1]. Using data with this transformation frees GP from having to search
* for the proper scale, allowing it to focus on just identifying the proper
* shape. See E. Y. Vladislavleva, Model-based problem solving through symbolic
* regression via pareto genetic programming, CentER, Tilburg University, 2008.
*
* @author Owen Derby and Ignacio Arnaldo
*/
public abstract class ScaledData implements DataJava {
/**
* the number of fitness cases
*/
protected int numberOfFitnessCases;
/**
* the number of features
*/
protected int numberOfFeatures;
/**
* the datapoints (input values) to evaluate individual's fitness on.
*/
protected final double[][] fitnessCases;
/**
* the datapoints (output values) to compare individual's output against to
* determine their fitness
*/
protected final double[] target;
/**
* In addition, keep a copy of the target which is scaled to be in the range
* [0, 1] This is from Vladislavleva, to "allow the GP to focus on finding
* the structure of the solution, instead of the scale"
*/
protected final double[] scaled_target;
private Double target_min;
private Double target_max;
/**
* Store the minimum value for each feature
*/
protected double[] minFeatures;
/**
* Store the maximum value for each feature
*/
protected double[] maxFeatures;
/**
* A running mean for target values, used in ModelScaler
*/ | public ArithmeticMean targetMean; |
flexgp/flexgp | mrgp-flexgp/src/evogpj/evaluation/java/CSVDataJava.java | // Path: mrgp-flexgp/src/evogpj/evaluation/DataSizeRetreiver.java
// public class DataSizeRetreiver {
// /**
// * Set the number of explanatory variables present in the file
// *
// * @param filepath
// * @return number of explanatory variables in the data
// */
// public static int num_terminals(String filepath) {
// try {
// BufferedReader f = new BufferedReader(new FileReader(filepath));
// if (!f.ready()) {
// System.err.println(String.format("Error: empty file %s", filepath));
// }
// String[] tokens = f.readLine().split(",");
// f.close();
// return tokens.length - 1; // assuming one output variable
// } catch (FileNotFoundException e) {
// System.err.println(String.format("Error: file not found in num_terminals"));
// } catch (IOException e) {
// System.err.println(String.format("Error: IO Exception in num_terminals"));
// }
// return -1;
// }
//
// /**
// * Return the number of lines found in the file
// *
// * @param filepath
// * @return number of lines in the file
// */
// public static int num_fitness_cases(String filepath) {
// try {
// InputStream is = new BufferedInputStream(new FileInputStream(filepath));
// try {
// byte[] c = new byte[1024];
// int count = 0;
// int readChars;
// boolean empty = true;
// while ((readChars = is.read(c)) != -1) {
// empty = false;
// for (int i = 0; i < readChars; ++i) {
// if (c[i] == '\n') {
// ++count;
// }
// }
// }
// return (count == 0 && !empty) ? 1 : count;
// } finally {
// is.close();
// }
// } catch (FileNotFoundException e) {
// System.err.println(String.format("Error: file %s not found.", filepath));
// } catch (IOException e) {
// System.err.println(String.format("Error: IO exception in num_fitness_cases"));
// }
// return -1;
// }
// }
| import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import evogpj.evaluation.DataSizeRetreiver; | /**
* Copyright (c) 2011-2013 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package evogpj.evaluation.java;
/**
* Class for ingesting data from a Comma Separated Value (CSV) text file. All
* data is assumed to be doubles.
*
* @author Owen Derby and Ignacio Arnaldo
*/
public class CSVDataJava extends ScaledData {
/**
* Parse given csvfile into set of input and target values.
*
* @param csvfile file of comma-separated values, last value in each line is
* the target value
*/
public CSVDataJava(String csvfile) { | // Path: mrgp-flexgp/src/evogpj/evaluation/DataSizeRetreiver.java
// public class DataSizeRetreiver {
// /**
// * Set the number of explanatory variables present in the file
// *
// * @param filepath
// * @return number of explanatory variables in the data
// */
// public static int num_terminals(String filepath) {
// try {
// BufferedReader f = new BufferedReader(new FileReader(filepath));
// if (!f.ready()) {
// System.err.println(String.format("Error: empty file %s", filepath));
// }
// String[] tokens = f.readLine().split(",");
// f.close();
// return tokens.length - 1; // assuming one output variable
// } catch (FileNotFoundException e) {
// System.err.println(String.format("Error: file not found in num_terminals"));
// } catch (IOException e) {
// System.err.println(String.format("Error: IO Exception in num_terminals"));
// }
// return -1;
// }
//
// /**
// * Return the number of lines found in the file
// *
// * @param filepath
// * @return number of lines in the file
// */
// public static int num_fitness_cases(String filepath) {
// try {
// InputStream is = new BufferedInputStream(new FileInputStream(filepath));
// try {
// byte[] c = new byte[1024];
// int count = 0;
// int readChars;
// boolean empty = true;
// while ((readChars = is.read(c)) != -1) {
// empty = false;
// for (int i = 0; i < readChars; ++i) {
// if (c[i] == '\n') {
// ++count;
// }
// }
// }
// return (count == 0 && !empty) ? 1 : count;
// } finally {
// is.close();
// }
// } catch (FileNotFoundException e) {
// System.err.println(String.format("Error: file %s not found.", filepath));
// } catch (IOException e) {
// System.err.println(String.format("Error: IO exception in num_fitness_cases"));
// }
// return -1;
// }
// }
// Path: mrgp-flexgp/src/evogpj/evaluation/java/CSVDataJava.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import evogpj.evaluation.DataSizeRetreiver;
/**
* Copyright (c) 2011-2013 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package evogpj.evaluation.java;
/**
* Class for ingesting data from a Comma Separated Value (CSV) text file. All
* data is assumed to be doubles.
*
* @author Owen Derby and Ignacio Arnaldo
*/
public class CSVDataJava extends ScaledData {
/**
* Parse given csvfile into set of input and target values.
*
* @param csvfile file of comma-separated values, last value in each line is
* the target value
*/
public CSVDataJava(String csvfile) { | super(DataSizeRetreiver.num_fitness_cases(csvfile), DataSizeRetreiver.num_terminals(csvfile)); |
flexgp/flexgp | comm-library/src/network/MessageWrapper.java | // Path: comm-library/src/node/NodeListEntry.java
// public class NodeListEntry extends Object implements Serializable {
// private static final long serialVersionUID = -1638892096321023484L;
//
// // the IP
// public String ip;
// // the port
// public int port;
// // sub-network label for second-tier nodes
// public String subnetLabel;
// // timestamp indicating last valid connection
// public Timestamp timestamp;
//
// public NodeListEntry(String _ip, int _port, String _subnetLabel, Timestamp _timestamp) {
// ip = _ip;
// port = _port;
// subnetLabel = _subnetLabel;
// timestamp = _timestamp;
// }
//
// // can ignore socket for equals method
// public boolean equals(NodeListEntry other) {
// return ((ip.equals(other.ip)) && (port == other.port) && (timestamp
// .compareTo(other.timestamp) == 0) && (subnetLabel.equals(other.subnetLabel)));
// }
//
// @Override
// public String toString() {
// return ip + ":" + Integer.toString(port) + "--" + subnetLabel + "--" + timestamp.toString();
// }
// }
| import node.NodeListEntry; | /**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package network;
/**
* Simple class to provide metadata about messages.
*
* @author Owen Derby
*
* @param <T>
* type of message to wrap
*/
public class MessageWrapper<T extends AbstractMessage> {
public final T msg;
public final String destID; | // Path: comm-library/src/node/NodeListEntry.java
// public class NodeListEntry extends Object implements Serializable {
// private static final long serialVersionUID = -1638892096321023484L;
//
// // the IP
// public String ip;
// // the port
// public int port;
// // sub-network label for second-tier nodes
// public String subnetLabel;
// // timestamp indicating last valid connection
// public Timestamp timestamp;
//
// public NodeListEntry(String _ip, int _port, String _subnetLabel, Timestamp _timestamp) {
// ip = _ip;
// port = _port;
// subnetLabel = _subnetLabel;
// timestamp = _timestamp;
// }
//
// // can ignore socket for equals method
// public boolean equals(NodeListEntry other) {
// return ((ip.equals(other.ip)) && (port == other.port) && (timestamp
// .compareTo(other.timestamp) == 0) && (subnetLabel.equals(other.subnetLabel)));
// }
//
// @Override
// public String toString() {
// return ip + ":" + Integer.toString(port) + "--" + subnetLabel + "--" + timestamp.toString();
// }
// }
// Path: comm-library/src/network/MessageWrapper.java
import node.NodeListEntry;
/**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package network;
/**
* Simple class to provide metadata about messages.
*
* @author Owen Derby
*
* @param <T>
* type of message to wrap
*/
public class MessageWrapper<T extends AbstractMessage> {
public final T msg;
public final String destID; | public final NodeListEntry nle; |
flexgp/flexgp | comm-library/src/node/NodeDescriptor.java | // Path: comm-library/src/utility/IP.java
// public class IP {
// public String id;
// public String ip;
// public int port;
//
// public IP(String _id, String _ip, int _port) {
// id = _id;
// ip = _ip;
// port = _port;
// }
//
// public boolean equals(IP other) {
// return ((this.id == other.id) && (this.ip.equals(other.ip)) && (this.port == other.port));
// }
//
// @Override
// public String toString() {
// return String.valueOf(id) + ":" + ip + ":" + String.valueOf(port);
// }
//
// public static final int ipToInt(String addr) {
// String[] addrArray = addr.split("\\.");
// if (addrArray.length != 4) {
// System.err.println("Improper ip address:" + addr);
// return 0;
// }
// int num = 0;
// for (int i = 0; i < addrArray.length; i++) {
// num += ((Integer.parseInt(addrArray[i]) % 256 * Math
// .pow(256, 3 - i)));
// }
// return num;
// }
//
// public static String makeID(String ip, int port) {
// return ip + ":" + port;
// }
//
// public static String intToIp(int i) {
// return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
// + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
// }
//
// /**
// * Translate an "ip:port" pair into an IP object
// * @param ip
// * @return
// */
// public static IP fromString(String ip) {
// // split into ip and port
// // TODO this should be done in a more stable/predictable way, plus tests
// String[] splitted = ip.split(":");
// if (splitted.length == 2) {
// String id = IP.makeID(splitted[0], Integer.parseInt(splitted[1]));
// IP result = new IP(id, splitted[0], Integer.parseInt(splitted[1]));
// System.out
// .println(String.format(
// "String: %s after formatting (2): %s", ip,
// result.toString()));
// return result;
// } else if (splitted.length == 1) {
// String id = IP.makeID(splitted[0], Control.PORT);
// IP result = new IP(id, splitted[0], Control.PORT);
// System.out
// .println(String.format(
// "String: %s after formatting (1): %s", ip,
// result.toString()));
// return result;
// } else {
// System.err.println(String.format("Invalid IP entered: %s", ip));
// System.exit(-1);
// return null;
// }
// }
// }
| import utility.IP; | /**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* The structure responsible for maintaining identifying information about this node
*
* @author Owen Derby
*/
public class NodeDescriptor {
// level 0 means learner, 1 means first-level reporter, 2 means second-level reporter, etc.
public int level = -1;
public static final int FUNCS = 0x1;
public static final int TERMS = 0x10;
public static final int NORMS = 0x100;
public static final int DATA = 0x1000;
public int factorizations;
private final long startTime; | // Path: comm-library/src/utility/IP.java
// public class IP {
// public String id;
// public String ip;
// public int port;
//
// public IP(String _id, String _ip, int _port) {
// id = _id;
// ip = _ip;
// port = _port;
// }
//
// public boolean equals(IP other) {
// return ((this.id == other.id) && (this.ip.equals(other.ip)) && (this.port == other.port));
// }
//
// @Override
// public String toString() {
// return String.valueOf(id) + ":" + ip + ":" + String.valueOf(port);
// }
//
// public static final int ipToInt(String addr) {
// String[] addrArray = addr.split("\\.");
// if (addrArray.length != 4) {
// System.err.println("Improper ip address:" + addr);
// return 0;
// }
// int num = 0;
// for (int i = 0; i < addrArray.length; i++) {
// num += ((Integer.parseInt(addrArray[i]) % 256 * Math
// .pow(256, 3 - i)));
// }
// return num;
// }
//
// public static String makeID(String ip, int port) {
// return ip + ":" + port;
// }
//
// public static String intToIp(int i) {
// return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
// + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
// }
//
// /**
// * Translate an "ip:port" pair into an IP object
// * @param ip
// * @return
// */
// public static IP fromString(String ip) {
// // split into ip and port
// // TODO this should be done in a more stable/predictable way, plus tests
// String[] splitted = ip.split(":");
// if (splitted.length == 2) {
// String id = IP.makeID(splitted[0], Integer.parseInt(splitted[1]));
// IP result = new IP(id, splitted[0], Integer.parseInt(splitted[1]));
// System.out
// .println(String.format(
// "String: %s after formatting (2): %s", ip,
// result.toString()));
// return result;
// } else if (splitted.length == 1) {
// String id = IP.makeID(splitted[0], Control.PORT);
// IP result = new IP(id, splitted[0], Control.PORT);
// System.out
// .println(String.format(
// "String: %s after formatting (1): %s", ip,
// result.toString()));
// return result;
// } else {
// System.err.println(String.format("Invalid IP entered: %s", ip));
// System.exit(-1);
// return null;
// }
// }
// }
// Path: comm-library/src/node/NodeDescriptor.java
import utility.IP;
/**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* The structure responsible for maintaining identifying information about this node
*
* @author Owen Derby
*/
public class NodeDescriptor {
// level 0 means learner, 1 means first-level reporter, 2 means second-level reporter, etc.
public int level = -1;
public static final int FUNCS = 0x1;
public static final int TERMS = 0x10;
public static final int NORMS = 0x100;
public static final int DATA = 0x1000;
public int factorizations;
private final long startTime; | private final IP ip; |
flexgp/flexgp | mrgp-flexgp/src/evogpj/genotype/Tree.java | // Path: mrgp-flexgp/src/evogpj/gp/GPException.java
// public class GPException extends Exception {
//
// /**
// * Constructor for GP exceptions
// * @param string
// */
// public GPException(String string) {
// super(string);
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 2346788405132405602L;
//
// }
//
// Path: mrgp-flexgp/src/evogpj/math/Function.java
// public abstract class Function {
//
// /**
// * Given the set of assignments of features to values for a particular
// * training case, return the double result of evaluating this function on
// * that training case.
// *
// * @param t the training case to evaluate.
// * @return value computed by applying this function to the training case.
// */
// public abstract Double eval(List<Double> t);
//
// /**
// * Eval with LASSO weights
// * @param t
// * @param interVals
// * @return
// */
// public abstract Double evalIntermediate(List<Double> t, ArrayList<Double> interVals);
//
// /**
// * Encapsulate the mapping from a textual label to a Function object's
// * class. To be used for introspectively determining how to generate a
// * Function for evaluation.
// *
// * @param label the string from an S-expression encoding a particular
// * function
// * @return the class of the function encoded in label.
// */
// public static Class<? extends Function> getClassFromLabel(String label) {
// if (label.startsWith("X") || label.equals("x") || label.equals("y")) {
// return Var.class;
// } else if (label.equals("+") || label.equals("plus")) {
// return Plus.class;
// } else if (label.equals("*") || label.equals(".*") || label.equals("times")) {
// return Multiply.class;
// } else if (label.equals("-") || label.equals("minus")) {
// return Minus.class;
// } else if (label.equals("/") || label.equals("./") || label.equals("mydivide")) {
// return Divide.class;
// } else if (label.equals("sin")) {
// return Sin.class;
// } else if (label.equals("cos")) {
// return Cos.class;
// } else if (label.equals("log") || label.equals("mylog")) {
// return Log.class;
// } else if (label.equals("exp")) {
// return Exp.class;
// } else if ((label.equals("sqrt")) || label.equals("mysqrt")) {
// return Sqrt.class;
// } else if (label.equals("square")) {
// return Square.class;
// } else if (label.equals("cube")) {
// return Cube.class;
// } else if (label.equals("quart")) {
// return Quart.class;
// }else{
// return null;
// }
// }
//
//
// /**
// * Given a label, return the constructor for the class of the function which
// * represents the label.
// *
// * @param label
// * @return
// * @throws SecurityException
// * @throws NoSuchMethodException
// */
// public static Constructor<? extends Function> getConstructorFromLabel(String label) throws SecurityException, NoSuchMethodException {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// int arity = Function.getArityFromLabel(label);
// if (arity == 1) {
// return f.getConstructor(Function.class);
// } else if (arity == 2) {
// return f.getConstructor(Function.class, Function.class);
// }
// //return f.getConstructor(String.class);
// return null;
// }
//
// /**
// * Simple method for extracting the arity of the function (number of args
// * the function takes) encoded by the provided label string by introspecting
// * on the function class represented by the label.
// *
// * @param label string of function, from an S-expression.
// * @return arity of encoded function
// */
// public static int getArityFromLabel(String label) {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// if (OneArgFunction.class.isAssignableFrom(f)) {
// return 1;
// } else if (TwoArgFunction.class.isAssignableFrom(f)) {
// return 2;
// } else {
// // Common terminals and default case
// return 0;
// }
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getInfixFormatString(){
// return "";
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getFinalString(){
// return "";
// }
//
//
// }
| import evogpj.gp.GPException;
import java.util.List;
import evogpj.math.Function; | /**
* Set the scaling slope (the "b" in y = ax + b) of this individual
* @param slope
*/
public void setScalingSlope(Double slope) {
scalingCoeffs[0] = slope;
}
/**
* @return the "b" coefficient in y = ax + b
*/
public Double getScalingIntercept() {
return scalingCoeffs[1];
}
/**
* Set the scaling intercept (the "b" in y = ax + b) of this individual
* @param intercept
*/
public void setScalingIntercept(Double intercept) {
scalingCoeffs[1] = intercept;
}
/**
* Create a new {@link Function} object to represent this tree in
* preparation for computing the fitness.
*
* @return
* @see Function
*/ | // Path: mrgp-flexgp/src/evogpj/gp/GPException.java
// public class GPException extends Exception {
//
// /**
// * Constructor for GP exceptions
// * @param string
// */
// public GPException(String string) {
// super(string);
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 2346788405132405602L;
//
// }
//
// Path: mrgp-flexgp/src/evogpj/math/Function.java
// public abstract class Function {
//
// /**
// * Given the set of assignments of features to values for a particular
// * training case, return the double result of evaluating this function on
// * that training case.
// *
// * @param t the training case to evaluate.
// * @return value computed by applying this function to the training case.
// */
// public abstract Double eval(List<Double> t);
//
// /**
// * Eval with LASSO weights
// * @param t
// * @param interVals
// * @return
// */
// public abstract Double evalIntermediate(List<Double> t, ArrayList<Double> interVals);
//
// /**
// * Encapsulate the mapping from a textual label to a Function object's
// * class. To be used for introspectively determining how to generate a
// * Function for evaluation.
// *
// * @param label the string from an S-expression encoding a particular
// * function
// * @return the class of the function encoded in label.
// */
// public static Class<? extends Function> getClassFromLabel(String label) {
// if (label.startsWith("X") || label.equals("x") || label.equals("y")) {
// return Var.class;
// } else if (label.equals("+") || label.equals("plus")) {
// return Plus.class;
// } else if (label.equals("*") || label.equals(".*") || label.equals("times")) {
// return Multiply.class;
// } else if (label.equals("-") || label.equals("minus")) {
// return Minus.class;
// } else if (label.equals("/") || label.equals("./") || label.equals("mydivide")) {
// return Divide.class;
// } else if (label.equals("sin")) {
// return Sin.class;
// } else if (label.equals("cos")) {
// return Cos.class;
// } else if (label.equals("log") || label.equals("mylog")) {
// return Log.class;
// } else if (label.equals("exp")) {
// return Exp.class;
// } else if ((label.equals("sqrt")) || label.equals("mysqrt")) {
// return Sqrt.class;
// } else if (label.equals("square")) {
// return Square.class;
// } else if (label.equals("cube")) {
// return Cube.class;
// } else if (label.equals("quart")) {
// return Quart.class;
// }else{
// return null;
// }
// }
//
//
// /**
// * Given a label, return the constructor for the class of the function which
// * represents the label.
// *
// * @param label
// * @return
// * @throws SecurityException
// * @throws NoSuchMethodException
// */
// public static Constructor<? extends Function> getConstructorFromLabel(String label) throws SecurityException, NoSuchMethodException {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// int arity = Function.getArityFromLabel(label);
// if (arity == 1) {
// return f.getConstructor(Function.class);
// } else if (arity == 2) {
// return f.getConstructor(Function.class, Function.class);
// }
// //return f.getConstructor(String.class);
// return null;
// }
//
// /**
// * Simple method for extracting the arity of the function (number of args
// * the function takes) encoded by the provided label string by introspecting
// * on the function class represented by the label.
// *
// * @param label string of function, from an S-expression.
// * @return arity of encoded function
// */
// public static int getArityFromLabel(String label) {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// if (OneArgFunction.class.isAssignableFrom(f)) {
// return 1;
// } else if (TwoArgFunction.class.isAssignableFrom(f)) {
// return 2;
// } else {
// // Common terminals and default case
// return 0;
// }
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getInfixFormatString(){
// return "";
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getFinalString(){
// return "";
// }
//
//
// }
// Path: mrgp-flexgp/src/evogpj/genotype/Tree.java
import evogpj.gp.GPException;
import java.util.List;
import evogpj.math.Function;
/**
* Set the scaling slope (the "b" in y = ax + b) of this individual
* @param slope
*/
public void setScalingSlope(Double slope) {
scalingCoeffs[0] = slope;
}
/**
* @return the "b" coefficient in y = ax + b
*/
public Double getScalingIntercept() {
return scalingCoeffs[1];
}
/**
* Set the scaling intercept (the "b" in y = ax + b) of this individual
* @param intercept
*/
public void setScalingIntercept(Double intercept) {
scalingCoeffs[1] = intercept;
}
/**
* Create a new {@link Function} object to represent this tree in
* preparation for computing the fitness.
*
* @return
* @see Function
*/ | public Function generate() { |
flexgp/flexgp | mrgp-flexgp/src/evogpj/genotype/Tree.java | // Path: mrgp-flexgp/src/evogpj/gp/GPException.java
// public class GPException extends Exception {
//
// /**
// * Constructor for GP exceptions
// * @param string
// */
// public GPException(String string) {
// super(string);
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 2346788405132405602L;
//
// }
//
// Path: mrgp-flexgp/src/evogpj/math/Function.java
// public abstract class Function {
//
// /**
// * Given the set of assignments of features to values for a particular
// * training case, return the double result of evaluating this function on
// * that training case.
// *
// * @param t the training case to evaluate.
// * @return value computed by applying this function to the training case.
// */
// public abstract Double eval(List<Double> t);
//
// /**
// * Eval with LASSO weights
// * @param t
// * @param interVals
// * @return
// */
// public abstract Double evalIntermediate(List<Double> t, ArrayList<Double> interVals);
//
// /**
// * Encapsulate the mapping from a textual label to a Function object's
// * class. To be used for introspectively determining how to generate a
// * Function for evaluation.
// *
// * @param label the string from an S-expression encoding a particular
// * function
// * @return the class of the function encoded in label.
// */
// public static Class<? extends Function> getClassFromLabel(String label) {
// if (label.startsWith("X") || label.equals("x") || label.equals("y")) {
// return Var.class;
// } else if (label.equals("+") || label.equals("plus")) {
// return Plus.class;
// } else if (label.equals("*") || label.equals(".*") || label.equals("times")) {
// return Multiply.class;
// } else if (label.equals("-") || label.equals("minus")) {
// return Minus.class;
// } else if (label.equals("/") || label.equals("./") || label.equals("mydivide")) {
// return Divide.class;
// } else if (label.equals("sin")) {
// return Sin.class;
// } else if (label.equals("cos")) {
// return Cos.class;
// } else if (label.equals("log") || label.equals("mylog")) {
// return Log.class;
// } else if (label.equals("exp")) {
// return Exp.class;
// } else if ((label.equals("sqrt")) || label.equals("mysqrt")) {
// return Sqrt.class;
// } else if (label.equals("square")) {
// return Square.class;
// } else if (label.equals("cube")) {
// return Cube.class;
// } else if (label.equals("quart")) {
// return Quart.class;
// }else{
// return null;
// }
// }
//
//
// /**
// * Given a label, return the constructor for the class of the function which
// * represents the label.
// *
// * @param label
// * @return
// * @throws SecurityException
// * @throws NoSuchMethodException
// */
// public static Constructor<? extends Function> getConstructorFromLabel(String label) throws SecurityException, NoSuchMethodException {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// int arity = Function.getArityFromLabel(label);
// if (arity == 1) {
// return f.getConstructor(Function.class);
// } else if (arity == 2) {
// return f.getConstructor(Function.class, Function.class);
// }
// //return f.getConstructor(String.class);
// return null;
// }
//
// /**
// * Simple method for extracting the arity of the function (number of args
// * the function takes) encoded by the provided label string by introspecting
// * on the function class represented by the label.
// *
// * @param label string of function, from an S-expression.
// * @return arity of encoded function
// */
// public static int getArityFromLabel(String label) {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// if (OneArgFunction.class.isAssignableFrom(f)) {
// return 1;
// } else if (TwoArgFunction.class.isAssignableFrom(f)) {
// return 2;
// } else {
// // Common terminals and default case
// return 0;
// }
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getInfixFormatString(){
// return "";
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getFinalString(){
// return "";
// }
//
//
// }
| import evogpj.gp.GPException;
import java.util.List;
import evogpj.math.Function; | scalingCoeffs[0] = slope;
}
/**
* @return the "b" coefficient in y = ax + b
*/
public Double getScalingIntercept() {
return scalingCoeffs[1];
}
/**
* Set the scaling intercept (the "b" in y = ax + b) of this individual
* @param intercept
*/
public void setScalingIntercept(Double intercept) {
scalingCoeffs[1] = intercept;
}
/**
* Create a new {@link Function} object to represent this tree in
* preparation for computing the fitness.
*
* @return
* @see Function
*/
public Function generate() {
try {
TreeNode r = getRoot();
Function f = r.generate();
return f; | // Path: mrgp-flexgp/src/evogpj/gp/GPException.java
// public class GPException extends Exception {
//
// /**
// * Constructor for GP exceptions
// * @param string
// */
// public GPException(String string) {
// super(string);
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 2346788405132405602L;
//
// }
//
// Path: mrgp-flexgp/src/evogpj/math/Function.java
// public abstract class Function {
//
// /**
// * Given the set of assignments of features to values for a particular
// * training case, return the double result of evaluating this function on
// * that training case.
// *
// * @param t the training case to evaluate.
// * @return value computed by applying this function to the training case.
// */
// public abstract Double eval(List<Double> t);
//
// /**
// * Eval with LASSO weights
// * @param t
// * @param interVals
// * @return
// */
// public abstract Double evalIntermediate(List<Double> t, ArrayList<Double> interVals);
//
// /**
// * Encapsulate the mapping from a textual label to a Function object's
// * class. To be used for introspectively determining how to generate a
// * Function for evaluation.
// *
// * @param label the string from an S-expression encoding a particular
// * function
// * @return the class of the function encoded in label.
// */
// public static Class<? extends Function> getClassFromLabel(String label) {
// if (label.startsWith("X") || label.equals("x") || label.equals("y")) {
// return Var.class;
// } else if (label.equals("+") || label.equals("plus")) {
// return Plus.class;
// } else if (label.equals("*") || label.equals(".*") || label.equals("times")) {
// return Multiply.class;
// } else if (label.equals("-") || label.equals("minus")) {
// return Minus.class;
// } else if (label.equals("/") || label.equals("./") || label.equals("mydivide")) {
// return Divide.class;
// } else if (label.equals("sin")) {
// return Sin.class;
// } else if (label.equals("cos")) {
// return Cos.class;
// } else if (label.equals("log") || label.equals("mylog")) {
// return Log.class;
// } else if (label.equals("exp")) {
// return Exp.class;
// } else if ((label.equals("sqrt")) || label.equals("mysqrt")) {
// return Sqrt.class;
// } else if (label.equals("square")) {
// return Square.class;
// } else if (label.equals("cube")) {
// return Cube.class;
// } else if (label.equals("quart")) {
// return Quart.class;
// }else{
// return null;
// }
// }
//
//
// /**
// * Given a label, return the constructor for the class of the function which
// * represents the label.
// *
// * @param label
// * @return
// * @throws SecurityException
// * @throws NoSuchMethodException
// */
// public static Constructor<? extends Function> getConstructorFromLabel(String label) throws SecurityException, NoSuchMethodException {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// int arity = Function.getArityFromLabel(label);
// if (arity == 1) {
// return f.getConstructor(Function.class);
// } else if (arity == 2) {
// return f.getConstructor(Function.class, Function.class);
// }
// //return f.getConstructor(String.class);
// return null;
// }
//
// /**
// * Simple method for extracting the arity of the function (number of args
// * the function takes) encoded by the provided label string by introspecting
// * on the function class represented by the label.
// *
// * @param label string of function, from an S-expression.
// * @return arity of encoded function
// */
// public static int getArityFromLabel(String label) {
// Class<? extends Function> f = Function.getClassFromLabel(label);
// if (OneArgFunction.class.isAssignableFrom(f)) {
// return 1;
// } else if (TwoArgFunction.class.isAssignableFrom(f)) {
// return 2;
// } else {
// // Common terminals and default case
// return 0;
// }
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getInfixFormatString(){
// return "";
// }
//
// /**
// * @return an infix format string representing this function, with #arity %s inclusions.
// */
// public String getFinalString(){
// return "";
// }
//
//
// }
// Path: mrgp-flexgp/src/evogpj/genotype/Tree.java
import evogpj.gp.GPException;
import java.util.List;
import evogpj.math.Function;
scalingCoeffs[0] = slope;
}
/**
* @return the "b" coefficient in y = ax + b
*/
public Double getScalingIntercept() {
return scalingCoeffs[1];
}
/**
* Set the scaling intercept (the "b" in y = ax + b) of this individual
* @param intercept
*/
public void setScalingIntercept(Double intercept) {
scalingCoeffs[1] = intercept;
}
/**
* Create a new {@link Function} object to represent this tree in
* preparation for computing the fitness.
*
* @return
* @see Function
*/
public Function generate() {
try {
TreeNode r = getRoot();
Function f = r.generate();
return f; | } catch (GPException e) { |
flexgp/flexgp | comm-library/src/test/ArgLexerTest.java | // Path: comm-library/src/utility/ArgLexer.java
// public class ArgLexer {
// // the raw arguments
// public String[] args;
// // the lexed tokens
// public ArrayList<String> tokens;
// // the grouped tokens, of the form '-i' --> 'commandLine text'
// public HashMap<String, String> groups;
//
// public ArgLexer(String[] _args) {
// args = _args;
// makeTokens();
// }
//
// public ArgLexer(String _args) {
// this(_args.split(" "));
// }
//
// public ArrayList<String> getTokens() {
// return tokens;
// }
//
// public HashMap<String, String> getGroups() {
// return groups;
// }
//
// /**
// * Iteratively process raw args into tokens
// *
// * @return
// */
// public void makeTokens() {
// groups = new HashMap<String, String>();
// tokens = new ArrayList<String>();
// String next = "";
// String lastFlag = "";
// boolean flag = true;
// for (int i = 0; i < args.length; i++) {
// // get next token
// next = args[i];
// if (next.substring(0, 1).equals("-")) {
// // the next raw chunk starts with "-", make a new token
// tokens.add(next);
// // add to groups
// groups.put(next, "");
// lastFlag = next;
// // toggle flag
// flag = true;
// } else if (flag) {
// // the previous chunk was a flag, and this chunk is not -- new
// tokens.add(next);
// // new entry in groups map
// groups.put(lastFlag, next);
// // toggle flag
// flag = false;
// } else {
// // the previous chunk was not a flag, and this is a continuation
// tokens.set(tokens.size() - 1, tokens.get(tokens.size() - 1)
// + " " + next);
// // update groups map
// String p = groups.get(lastFlag)
// + ((groups.get(lastFlag).equals("")) ? "" : " ") + next;
// groups.put(lastFlag, p);
// }
// }
// }
// }
| import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.junit.Test;
import utility.ArgLexer; | /**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package test;
public class ArgLexerTest {
/**
* A test of the ArgLexer This code should be used to write
* Control.processArgs or similar.
*/
@Test
public void simpleLexTest() {
String argstring = "-1 one -2 two -v -3 three four five -6 -7 seven";
String expected = "|-1| |one| |-2| |two| |-v| |-3| |three four five| |-6| |-7| |seven|";
HashMap<String, String> expectedGroups = new HashMap<String, String>();
expectedGroups.put("-1", "one");
expectedGroups.put("-2", "two");
expectedGroups.put("-v", "");
expectedGroups.put("-3", "three four five");
expectedGroups.put("-6", "");
expectedGroups.put("-7", "seven");
String s = "";
String[] args = argstring.split(" ");
// get results | // Path: comm-library/src/utility/ArgLexer.java
// public class ArgLexer {
// // the raw arguments
// public String[] args;
// // the lexed tokens
// public ArrayList<String> tokens;
// // the grouped tokens, of the form '-i' --> 'commandLine text'
// public HashMap<String, String> groups;
//
// public ArgLexer(String[] _args) {
// args = _args;
// makeTokens();
// }
//
// public ArgLexer(String _args) {
// this(_args.split(" "));
// }
//
// public ArrayList<String> getTokens() {
// return tokens;
// }
//
// public HashMap<String, String> getGroups() {
// return groups;
// }
//
// /**
// * Iteratively process raw args into tokens
// *
// * @return
// */
// public void makeTokens() {
// groups = new HashMap<String, String>();
// tokens = new ArrayList<String>();
// String next = "";
// String lastFlag = "";
// boolean flag = true;
// for (int i = 0; i < args.length; i++) {
// // get next token
// next = args[i];
// if (next.substring(0, 1).equals("-")) {
// // the next raw chunk starts with "-", make a new token
// tokens.add(next);
// // add to groups
// groups.put(next, "");
// lastFlag = next;
// // toggle flag
// flag = true;
// } else if (flag) {
// // the previous chunk was a flag, and this chunk is not -- new
// tokens.add(next);
// // new entry in groups map
// groups.put(lastFlag, next);
// // toggle flag
// flag = false;
// } else {
// // the previous chunk was not a flag, and this is a continuation
// tokens.set(tokens.size() - 1, tokens.get(tokens.size() - 1)
// + " " + next);
// // update groups map
// String p = groups.get(lastFlag)
// + ((groups.get(lastFlag).equals("")) ? "" : " ") + next;
// groups.put(lastFlag, p);
// }
// }
// }
// }
// Path: comm-library/src/test/ArgLexerTest.java
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.junit.Test;
import utility.ArgLexer;
/**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package test;
public class ArgLexerTest {
/**
* A test of the ArgLexer This code should be used to write
* Control.processArgs or similar.
*/
@Test
public void simpleLexTest() {
String argstring = "-1 one -2 two -v -3 three four five -6 -7 seven";
String expected = "|-1| |one| |-2| |two| |-v| |-3| |three four five| |-6| |-7| |seven|";
HashMap<String, String> expectedGroups = new HashMap<String, String>();
expectedGroups.put("-1", "one");
expectedGroups.put("-2", "two");
expectedGroups.put("-v", "");
expectedGroups.put("-3", "three four five");
expectedGroups.put("-6", "");
expectedGroups.put("-7", "seven");
String s = "";
String[] args = argstring.split(" ");
// get results | ArgLexer al = new ArgLexer(args); |
flexgp/flexgp | comm-library/src/node/Reporter.java | // Path: comm-library/src/utility/JSONFilter.java
// public class JSONFilter implements Filter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Filter#isLoggable(java.util.logging.LogRecord)
// */
// @Override
// public boolean isLoggable(LogRecord record) {
// return JSONValue.isValidJsonStrict(record.getMessage());
// }
//
// }
//
// Path: comm-library/src/utility/JSONFormatter.java
// public class JSONFormatter extends Formatter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
// */
// @Override
// public String format(LogRecord record) {
// if (JSONValue.isValidJson(record.getMessage())) {
// return record.getMessage() + "\n";
// } else {
//
// return null;
// }
// }
//
// }
//
// Path: comm-library/src/utility/Signal.java
// public class Signal extends AbstractThread {
// // time to wait between signaling
// private final int pauseOffset;
// // the signal boolean
// private boolean signal;
// // a shutdown signal
// private boolean go;
//
// public Signal(int offset) {
// pauseOffset = offset;
// signal = false;
// go = true;
// }
//
// public synchronized void shutdown() {
// go = false;
// }
//
// public synchronized boolean getSignal() {
// return signal;
// }
//
// public synchronized void signalTrue() {
// signal = true;
// }
//
// public synchronized void signalFalse() {
// signal = false;
// }
//
// @Override
// public void run() {
// try {
// // initial sleep to allow for initialization
// Thread.sleep(1000 * pauseOffset);
// while (go) {
// // signal
// signalTrue();
// // sleep
// Thread.sleep(1000 * pauseOffset);
// }
// System.out.println("Signal: finished");
// } catch (InterruptedException e) {
// System.err.println("Signal: failed");
// e.printStackTrace();
// }
//
// }
// }
| import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minidev.json.JSONObject;
import utility.JSONFilter;
import utility.JSONFormatter;
import utility.Signal; | /**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* A thread for recording JSON logs
*
* @author Owen Derby
*/
public class Reporter extends AbstractThread {
private final BlockingQueue<JSONObject> reportSend; | // Path: comm-library/src/utility/JSONFilter.java
// public class JSONFilter implements Filter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Filter#isLoggable(java.util.logging.LogRecord)
// */
// @Override
// public boolean isLoggable(LogRecord record) {
// return JSONValue.isValidJsonStrict(record.getMessage());
// }
//
// }
//
// Path: comm-library/src/utility/JSONFormatter.java
// public class JSONFormatter extends Formatter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
// */
// @Override
// public String format(LogRecord record) {
// if (JSONValue.isValidJson(record.getMessage())) {
// return record.getMessage() + "\n";
// } else {
//
// return null;
// }
// }
//
// }
//
// Path: comm-library/src/utility/Signal.java
// public class Signal extends AbstractThread {
// // time to wait between signaling
// private final int pauseOffset;
// // the signal boolean
// private boolean signal;
// // a shutdown signal
// private boolean go;
//
// public Signal(int offset) {
// pauseOffset = offset;
// signal = false;
// go = true;
// }
//
// public synchronized void shutdown() {
// go = false;
// }
//
// public synchronized boolean getSignal() {
// return signal;
// }
//
// public synchronized void signalTrue() {
// signal = true;
// }
//
// public synchronized void signalFalse() {
// signal = false;
// }
//
// @Override
// public void run() {
// try {
// // initial sleep to allow for initialization
// Thread.sleep(1000 * pauseOffset);
// while (go) {
// // signal
// signalTrue();
// // sleep
// Thread.sleep(1000 * pauseOffset);
// }
// System.out.println("Signal: finished");
// } catch (InterruptedException e) {
// System.err.println("Signal: failed");
// e.printStackTrace();
// }
//
// }
// }
// Path: comm-library/src/node/Reporter.java
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minidev.json.JSONObject;
import utility.JSONFilter;
import utility.JSONFormatter;
import utility.Signal;
/**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* A thread for recording JSON logs
*
* @author Owen Derby
*/
public class Reporter extends AbstractThread {
private final BlockingQueue<JSONObject> reportSend; | private Signal sig; |
flexgp/flexgp | comm-library/src/node/Reporter.java | // Path: comm-library/src/utility/JSONFilter.java
// public class JSONFilter implements Filter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Filter#isLoggable(java.util.logging.LogRecord)
// */
// @Override
// public boolean isLoggable(LogRecord record) {
// return JSONValue.isValidJsonStrict(record.getMessage());
// }
//
// }
//
// Path: comm-library/src/utility/JSONFormatter.java
// public class JSONFormatter extends Formatter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
// */
// @Override
// public String format(LogRecord record) {
// if (JSONValue.isValidJson(record.getMessage())) {
// return record.getMessage() + "\n";
// } else {
//
// return null;
// }
// }
//
// }
//
// Path: comm-library/src/utility/Signal.java
// public class Signal extends AbstractThread {
// // time to wait between signaling
// private final int pauseOffset;
// // the signal boolean
// private boolean signal;
// // a shutdown signal
// private boolean go;
//
// public Signal(int offset) {
// pauseOffset = offset;
// signal = false;
// go = true;
// }
//
// public synchronized void shutdown() {
// go = false;
// }
//
// public synchronized boolean getSignal() {
// return signal;
// }
//
// public synchronized void signalTrue() {
// signal = true;
// }
//
// public synchronized void signalFalse() {
// signal = false;
// }
//
// @Override
// public void run() {
// try {
// // initial sleep to allow for initialization
// Thread.sleep(1000 * pauseOffset);
// while (go) {
// // signal
// signalTrue();
// // sleep
// Thread.sleep(1000 * pauseOffset);
// }
// System.out.println("Signal: finished");
// } catch (InterruptedException e) {
// System.err.println("Signal: failed");
// e.printStackTrace();
// }
//
// }
// }
| import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minidev.json.JSONObject;
import utility.JSONFilter;
import utility.JSONFormatter;
import utility.Signal; | /**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* A thread for recording JSON logs
*
* @author Owen Derby
*/
public class Reporter extends AbstractThread {
private final BlockingQueue<JSONObject> reportSend;
private Signal sig;
private final static int signalFreq = 5; // seconds
private static Logger localLog = Logger.getLogger("node.Reporter");
private static Logger sendLog = Logger.getLogger("node.Reporter_send");
private JSONObject myReport;
public Reporter(BlockingQueue<JSONObject> reportSend2) {
Handler fh;
try {
localLog.setUseParentHandlers(false);
fh = new FileHandler("reporter.json"); | // Path: comm-library/src/utility/JSONFilter.java
// public class JSONFilter implements Filter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Filter#isLoggable(java.util.logging.LogRecord)
// */
// @Override
// public boolean isLoggable(LogRecord record) {
// return JSONValue.isValidJsonStrict(record.getMessage());
// }
//
// }
//
// Path: comm-library/src/utility/JSONFormatter.java
// public class JSONFormatter extends Formatter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
// */
// @Override
// public String format(LogRecord record) {
// if (JSONValue.isValidJson(record.getMessage())) {
// return record.getMessage() + "\n";
// } else {
//
// return null;
// }
// }
//
// }
//
// Path: comm-library/src/utility/Signal.java
// public class Signal extends AbstractThread {
// // time to wait between signaling
// private final int pauseOffset;
// // the signal boolean
// private boolean signal;
// // a shutdown signal
// private boolean go;
//
// public Signal(int offset) {
// pauseOffset = offset;
// signal = false;
// go = true;
// }
//
// public synchronized void shutdown() {
// go = false;
// }
//
// public synchronized boolean getSignal() {
// return signal;
// }
//
// public synchronized void signalTrue() {
// signal = true;
// }
//
// public synchronized void signalFalse() {
// signal = false;
// }
//
// @Override
// public void run() {
// try {
// // initial sleep to allow for initialization
// Thread.sleep(1000 * pauseOffset);
// while (go) {
// // signal
// signalTrue();
// // sleep
// Thread.sleep(1000 * pauseOffset);
// }
// System.out.println("Signal: finished");
// } catch (InterruptedException e) {
// System.err.println("Signal: failed");
// e.printStackTrace();
// }
//
// }
// }
// Path: comm-library/src/node/Reporter.java
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minidev.json.JSONObject;
import utility.JSONFilter;
import utility.JSONFormatter;
import utility.Signal;
/**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* A thread for recording JSON logs
*
* @author Owen Derby
*/
public class Reporter extends AbstractThread {
private final BlockingQueue<JSONObject> reportSend;
private Signal sig;
private final static int signalFreq = 5; // seconds
private static Logger localLog = Logger.getLogger("node.Reporter");
private static Logger sendLog = Logger.getLogger("node.Reporter_send");
private JSONObject myReport;
public Reporter(BlockingQueue<JSONObject> reportSend2) {
Handler fh;
try {
localLog.setUseParentHandlers(false);
fh = new FileHandler("reporter.json"); | fh.setFormatter(new JSONFormatter()); |
flexgp/flexgp | comm-library/src/node/Reporter.java | // Path: comm-library/src/utility/JSONFilter.java
// public class JSONFilter implements Filter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Filter#isLoggable(java.util.logging.LogRecord)
// */
// @Override
// public boolean isLoggable(LogRecord record) {
// return JSONValue.isValidJsonStrict(record.getMessage());
// }
//
// }
//
// Path: comm-library/src/utility/JSONFormatter.java
// public class JSONFormatter extends Formatter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
// */
// @Override
// public String format(LogRecord record) {
// if (JSONValue.isValidJson(record.getMessage())) {
// return record.getMessage() + "\n";
// } else {
//
// return null;
// }
// }
//
// }
//
// Path: comm-library/src/utility/Signal.java
// public class Signal extends AbstractThread {
// // time to wait between signaling
// private final int pauseOffset;
// // the signal boolean
// private boolean signal;
// // a shutdown signal
// private boolean go;
//
// public Signal(int offset) {
// pauseOffset = offset;
// signal = false;
// go = true;
// }
//
// public synchronized void shutdown() {
// go = false;
// }
//
// public synchronized boolean getSignal() {
// return signal;
// }
//
// public synchronized void signalTrue() {
// signal = true;
// }
//
// public synchronized void signalFalse() {
// signal = false;
// }
//
// @Override
// public void run() {
// try {
// // initial sleep to allow for initialization
// Thread.sleep(1000 * pauseOffset);
// while (go) {
// // signal
// signalTrue();
// // sleep
// Thread.sleep(1000 * pauseOffset);
// }
// System.out.println("Signal: finished");
// } catch (InterruptedException e) {
// System.err.println("Signal: failed");
// e.printStackTrace();
// }
//
// }
// }
| import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minidev.json.JSONObject;
import utility.JSONFilter;
import utility.JSONFormatter;
import utility.Signal; | /**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* A thread for recording JSON logs
*
* @author Owen Derby
*/
public class Reporter extends AbstractThread {
private final BlockingQueue<JSONObject> reportSend;
private Signal sig;
private final static int signalFreq = 5; // seconds
private static Logger localLog = Logger.getLogger("node.Reporter");
private static Logger sendLog = Logger.getLogger("node.Reporter_send");
private JSONObject myReport;
public Reporter(BlockingQueue<JSONObject> reportSend2) {
Handler fh;
try {
localLog.setUseParentHandlers(false);
fh = new FileHandler("reporter.json");
fh.setFormatter(new JSONFormatter()); | // Path: comm-library/src/utility/JSONFilter.java
// public class JSONFilter implements Filter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Filter#isLoggable(java.util.logging.LogRecord)
// */
// @Override
// public boolean isLoggable(LogRecord record) {
// return JSONValue.isValidJsonStrict(record.getMessage());
// }
//
// }
//
// Path: comm-library/src/utility/JSONFormatter.java
// public class JSONFormatter extends Formatter {
//
// /* (non-Javadoc)
// * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
// */
// @Override
// public String format(LogRecord record) {
// if (JSONValue.isValidJson(record.getMessage())) {
// return record.getMessage() + "\n";
// } else {
//
// return null;
// }
// }
//
// }
//
// Path: comm-library/src/utility/Signal.java
// public class Signal extends AbstractThread {
// // time to wait between signaling
// private final int pauseOffset;
// // the signal boolean
// private boolean signal;
// // a shutdown signal
// private boolean go;
//
// public Signal(int offset) {
// pauseOffset = offset;
// signal = false;
// go = true;
// }
//
// public synchronized void shutdown() {
// go = false;
// }
//
// public synchronized boolean getSignal() {
// return signal;
// }
//
// public synchronized void signalTrue() {
// signal = true;
// }
//
// public synchronized void signalFalse() {
// signal = false;
// }
//
// @Override
// public void run() {
// try {
// // initial sleep to allow for initialization
// Thread.sleep(1000 * pauseOffset);
// while (go) {
// // signal
// signalTrue();
// // sleep
// Thread.sleep(1000 * pauseOffset);
// }
// System.out.println("Signal: finished");
// } catch (InterruptedException e) {
// System.err.println("Signal: failed");
// e.printStackTrace();
// }
//
// }
// }
// Path: comm-library/src/node/Reporter.java
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minidev.json.JSONObject;
import utility.JSONFilter;
import utility.JSONFormatter;
import utility.Signal;
/**
* Copyright (c) 2012 Evolutionary Design and Optimization Group
*
* Licensed under the MIT License.
*
* See the "LICENSE" file for a copy of the license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package node;
/**
* A thread for recording JSON logs
*
* @author Owen Derby
*/
public class Reporter extends AbstractThread {
private final BlockingQueue<JSONObject> reportSend;
private Signal sig;
private final static int signalFreq = 5; // seconds
private static Logger localLog = Logger.getLogger("node.Reporter");
private static Logger sendLog = Logger.getLogger("node.Reporter_send");
private JSONObject myReport;
public Reporter(BlockingQueue<JSONObject> reportSend2) {
Handler fh;
try {
localLog.setUseParentHandlers(false);
fh = new FileHandler("reporter.json");
fh.setFormatter(new JSONFormatter()); | fh.setFilter(new JSONFilter()); |
flexgp/flexgp | mrgp-flexgp/src/evogpj/gp/Population.java | // Path: mrgp-flexgp/src/evogpj/evaluation/FitnessComparisonStandardizer.java
// public class FitnessComparisonStandardizer {
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param individual
// * @param funcName
// * @param fitnessFunctions
// * @return transformed fitness value
// */
// public static Double getFitnessForMinimization(Individual individual,String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = individual.getFitness(funcName);
// if (fitnessFunctions.get(funcName).isMaximizingFunction()) {
// fitness = invert(fitness);
// }
// return fitness;
// }
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param fitnesses a LinkedHashMap mapping fitness function name to fitness score
// * @param funcName
// * @param fitnessFunctions
// * @return
// */
// public static Double getFitnessForMinimization(LinkedHashMap<String, Double> fitnesses, String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = fitnesses.get(funcName);
// return handleInversionForMinimization(fitness, fitnessFunctions.get(funcName));
// }
//
// /**
// * handle Inversion For Minimization
// * @param fitnessValue
// * @param fitnessFunction
// * @return
// */
// private static Double handleInversionForMinimization(Double fitnessValue, FitnessFunction fitnessFunction) {
// if (fitnessFunction.isMaximizingFunction())
// fitnessValue = invert(fitnessValue);
// return fitnessValue;
// }
// /**
// * Invert a fitness value, thus converting from maximization to minimization
// * score, or vice versa
// *
// * @param fitness
// * @return inverted fitness value
// */
// public static Double invert(Double fitness) {
// return (1 - fitness) / (1 + fitness);
// }
// }
//
// Path: mrgp-flexgp/src/evogpj/evaluation/FitnessFunction.java
// public abstract class FitnessFunction {
//
// // used to access this fitness function's position in the
// // gp.Individual.fitnesses HashMap. Each subclass must
// // define this value
// //public static String FITNESS_KEY;
//
// // should this value be maximized (true) or minimized (false)?
// // used by non-dominated sort to convert all fitness functions
// // to minimizers
// // public Boolean isMaximizingFunction;
//
// /**
// * Evaluate a single individual
// *
// * @param pop
// */
//
// /**
// * Evaluate each individual in a population
// *
// * @param pop
// */
// public abstract void evalPop(Population pop);
//
// /**
// * Determine whether the fitness function needs to be minimized or maximized
// * @return flag for minimization or maximization
// */
// public abstract Boolean isMaximizingFunction();
//
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import evogpj.evaluation.FitnessComparisonStandardizer;
import evogpj.evaluation.FitnessFunction; | if (!this.get(i).equals(otherL.get(i)))
return false;
}
return true;
}
/**
* perform a deep copy of the population
* @return
*/
public Population deepCopy() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return (Population) ois.readObject();
} catch (IOException e) {
System.err.println("IO Exception in deepCopy");
} catch (ClassNotFoundException e) {
System.err.println("Class not found Exception in deepCopy");
}
return null;
}
/**
* Calculates the euclidean distance of all individuals in the first front. Others will keep a distance of Double.MAX_VALUE
* @param fitnessFunctions
*/ | // Path: mrgp-flexgp/src/evogpj/evaluation/FitnessComparisonStandardizer.java
// public class FitnessComparisonStandardizer {
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param individual
// * @param funcName
// * @param fitnessFunctions
// * @return transformed fitness value
// */
// public static Double getFitnessForMinimization(Individual individual,String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = individual.getFitness(funcName);
// if (fitnessFunctions.get(funcName).isMaximizingFunction()) {
// fitness = invert(fitness);
// }
// return fitness;
// }
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param fitnesses a LinkedHashMap mapping fitness function name to fitness score
// * @param funcName
// * @param fitnessFunctions
// * @return
// */
// public static Double getFitnessForMinimization(LinkedHashMap<String, Double> fitnesses, String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = fitnesses.get(funcName);
// return handleInversionForMinimization(fitness, fitnessFunctions.get(funcName));
// }
//
// /**
// * handle Inversion For Minimization
// * @param fitnessValue
// * @param fitnessFunction
// * @return
// */
// private static Double handleInversionForMinimization(Double fitnessValue, FitnessFunction fitnessFunction) {
// if (fitnessFunction.isMaximizingFunction())
// fitnessValue = invert(fitnessValue);
// return fitnessValue;
// }
// /**
// * Invert a fitness value, thus converting from maximization to minimization
// * score, or vice versa
// *
// * @param fitness
// * @return inverted fitness value
// */
// public static Double invert(Double fitness) {
// return (1 - fitness) / (1 + fitness);
// }
// }
//
// Path: mrgp-flexgp/src/evogpj/evaluation/FitnessFunction.java
// public abstract class FitnessFunction {
//
// // used to access this fitness function's position in the
// // gp.Individual.fitnesses HashMap. Each subclass must
// // define this value
// //public static String FITNESS_KEY;
//
// // should this value be maximized (true) or minimized (false)?
// // used by non-dominated sort to convert all fitness functions
// // to minimizers
// // public Boolean isMaximizingFunction;
//
// /**
// * Evaluate a single individual
// *
// * @param pop
// */
//
// /**
// * Evaluate each individual in a population
// *
// * @param pop
// */
// public abstract void evalPop(Population pop);
//
// /**
// * Determine whether the fitness function needs to be minimized or maximized
// * @return flag for minimization or maximization
// */
// public abstract Boolean isMaximizingFunction();
//
// }
// Path: mrgp-flexgp/src/evogpj/gp/Population.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import evogpj.evaluation.FitnessComparisonStandardizer;
import evogpj.evaluation.FitnessFunction;
if (!this.get(i).equals(otherL.get(i)))
return false;
}
return true;
}
/**
* perform a deep copy of the population
* @return
*/
public Population deepCopy() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return (Population) ois.readObject();
} catch (IOException e) {
System.err.println("IO Exception in deepCopy");
} catch (ClassNotFoundException e) {
System.err.println("Class not found Exception in deepCopy");
}
return null;
}
/**
* Calculates the euclidean distance of all individuals in the first front. Others will keep a distance of Double.MAX_VALUE
* @param fitnessFunctions
*/ | public void calculateEuclideanDistances(LinkedHashMap<String, FitnessFunction> fitnessFunctions) { |
flexgp/flexgp | mrgp-flexgp/src/evogpj/gp/Population.java | // Path: mrgp-flexgp/src/evogpj/evaluation/FitnessComparisonStandardizer.java
// public class FitnessComparisonStandardizer {
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param individual
// * @param funcName
// * @param fitnessFunctions
// * @return transformed fitness value
// */
// public static Double getFitnessForMinimization(Individual individual,String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = individual.getFitness(funcName);
// if (fitnessFunctions.get(funcName).isMaximizingFunction()) {
// fitness = invert(fitness);
// }
// return fitness;
// }
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param fitnesses a LinkedHashMap mapping fitness function name to fitness score
// * @param funcName
// * @param fitnessFunctions
// * @return
// */
// public static Double getFitnessForMinimization(LinkedHashMap<String, Double> fitnesses, String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = fitnesses.get(funcName);
// return handleInversionForMinimization(fitness, fitnessFunctions.get(funcName));
// }
//
// /**
// * handle Inversion For Minimization
// * @param fitnessValue
// * @param fitnessFunction
// * @return
// */
// private static Double handleInversionForMinimization(Double fitnessValue, FitnessFunction fitnessFunction) {
// if (fitnessFunction.isMaximizingFunction())
// fitnessValue = invert(fitnessValue);
// return fitnessValue;
// }
// /**
// * Invert a fitness value, thus converting from maximization to minimization
// * score, or vice versa
// *
// * @param fitness
// * @return inverted fitness value
// */
// public static Double invert(Double fitness) {
// return (1 - fitness) / (1 + fitness);
// }
// }
//
// Path: mrgp-flexgp/src/evogpj/evaluation/FitnessFunction.java
// public abstract class FitnessFunction {
//
// // used to access this fitness function's position in the
// // gp.Individual.fitnesses HashMap. Each subclass must
// // define this value
// //public static String FITNESS_KEY;
//
// // should this value be maximized (true) or minimized (false)?
// // used by non-dominated sort to convert all fitness functions
// // to minimizers
// // public Boolean isMaximizingFunction;
//
// /**
// * Evaluate a single individual
// *
// * @param pop
// */
//
// /**
// * Evaluate each individual in a population
// *
// * @param pop
// */
// public abstract void evalPop(Population pop);
//
// /**
// * Determine whether the fitness function needs to be minimized or maximized
// * @return flag for minimization or maximization
// */
// public abstract Boolean isMaximizingFunction();
//
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import evogpj.evaluation.FitnessComparisonStandardizer;
import evogpj.evaluation.FitnessFunction; | */
public Population deepCopy() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return (Population) ois.readObject();
} catch (IOException e) {
System.err.println("IO Exception in deepCopy");
} catch (ClassNotFoundException e) {
System.err.println("Class not found Exception in deepCopy");
}
return null;
}
/**
* Calculates the euclidean distance of all individuals in the first front. Others will keep a distance of Double.MAX_VALUE
* @param fitnessFunctions
*/
public void calculateEuclideanDistances(LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// first get the mins and maxes for the first front only
LinkedHashMap<String, Double>[] minMax = getMinMax(this, fitnessFunctions, true);
LinkedHashMap<String, Double> mins = minMax[0];
LinkedHashMap<String, Double> maxes = minMax[1];
// convert the mins and maxes to standardized form
for (String key : mins.keySet()) {
// get new standardized min and max. swap values if this fitness function isn't minimizing already
if (fitnessFunctions.get(key).isMaximizingFunction()) { // swap min and max since they've both been inverted | // Path: mrgp-flexgp/src/evogpj/evaluation/FitnessComparisonStandardizer.java
// public class FitnessComparisonStandardizer {
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param individual
// * @param funcName
// * @param fitnessFunctions
// * @return transformed fitness value
// */
// public static Double getFitnessForMinimization(Individual individual,String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = individual.getFitness(funcName);
// if (fitnessFunctions.get(funcName).isMaximizingFunction()) {
// fitness = invert(fitness);
// }
// return fitness;
// }
//
// /**
// * Standardizes the way by which fitnesses are compared. Will always return
// * a fitness score where lower indicates better.
// *
// * @param fitnesses a LinkedHashMap mapping fitness function name to fitness score
// * @param funcName
// * @param fitnessFunctions
// * @return
// */
// public static Double getFitnessForMinimization(LinkedHashMap<String, Double> fitnesses, String funcName, LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// Double fitness = fitnesses.get(funcName);
// return handleInversionForMinimization(fitness, fitnessFunctions.get(funcName));
// }
//
// /**
// * handle Inversion For Minimization
// * @param fitnessValue
// * @param fitnessFunction
// * @return
// */
// private static Double handleInversionForMinimization(Double fitnessValue, FitnessFunction fitnessFunction) {
// if (fitnessFunction.isMaximizingFunction())
// fitnessValue = invert(fitnessValue);
// return fitnessValue;
// }
// /**
// * Invert a fitness value, thus converting from maximization to minimization
// * score, or vice versa
// *
// * @param fitness
// * @return inverted fitness value
// */
// public static Double invert(Double fitness) {
// return (1 - fitness) / (1 + fitness);
// }
// }
//
// Path: mrgp-flexgp/src/evogpj/evaluation/FitnessFunction.java
// public abstract class FitnessFunction {
//
// // used to access this fitness function's position in the
// // gp.Individual.fitnesses HashMap. Each subclass must
// // define this value
// //public static String FITNESS_KEY;
//
// // should this value be maximized (true) or minimized (false)?
// // used by non-dominated sort to convert all fitness functions
// // to minimizers
// // public Boolean isMaximizingFunction;
//
// /**
// * Evaluate a single individual
// *
// * @param pop
// */
//
// /**
// * Evaluate each individual in a population
// *
// * @param pop
// */
// public abstract void evalPop(Population pop);
//
// /**
// * Determine whether the fitness function needs to be minimized or maximized
// * @return flag for minimization or maximization
// */
// public abstract Boolean isMaximizingFunction();
//
// }
// Path: mrgp-flexgp/src/evogpj/gp/Population.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import evogpj.evaluation.FitnessComparisonStandardizer;
import evogpj.evaluation.FitnessFunction;
*/
public Population deepCopy() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return (Population) ois.readObject();
} catch (IOException e) {
System.err.println("IO Exception in deepCopy");
} catch (ClassNotFoundException e) {
System.err.println("Class not found Exception in deepCopy");
}
return null;
}
/**
* Calculates the euclidean distance of all individuals in the first front. Others will keep a distance of Double.MAX_VALUE
* @param fitnessFunctions
*/
public void calculateEuclideanDistances(LinkedHashMap<String, FitnessFunction> fitnessFunctions) {
// first get the mins and maxes for the first front only
LinkedHashMap<String, Double>[] minMax = getMinMax(this, fitnessFunctions, true);
LinkedHashMap<String, Double> mins = minMax[0];
LinkedHashMap<String, Double> maxes = minMax[1];
// convert the mins and maxes to standardized form
for (String key : mins.keySet()) {
// get new standardized min and max. swap values if this fitness function isn't minimizing already
if (fitnessFunctions.get(key).isMaximizingFunction()) { // swap min and max since they've both been inverted | Double standardizedMin = FitnessComparisonStandardizer.getFitnessForMinimization(maxes, key, fitnessFunctions); |
BroadleafCommerce/blc-paypal | services/src/test/java/org/broadleaf/payment/service/gateway/PayPalCheckoutRetryPolicyClassifierTest.java | // Path: services/src/main/java/org/broadleafcommerce/payment/service/gateway/DefaultPayPalCheckoutRetryPolicyClassifier.java
// @RequiredArgsConstructor
// public class DefaultPayPalCheckoutRetryPolicyClassifier
// implements Classifier<Throwable, RetryPolicy> {
//
// @Getter(AccessLevel.PROTECTED)
// private final RetryPolicy retryPolicy;
//
// @Override
// public RetryPolicy classify(Throwable throwable) {
// if (isNetworkError(throwable) || is5xxError(throwable)) {
// return retryPolicy;
// }
//
// return new NeverRetryPolicy();
// }
//
// /**
// * Determines whether or not the given throwable coming from PayPal's SDK is their
// * representation of a network error
// *
// * @param throwable the throwable that is returned by PayPal's SDK
// * @return whether or not the given throwable represents a network error
// */
// protected boolean isNetworkError(Throwable throwable) {
// Throwable cause = throwable.getCause();
// if (cause instanceof PayPalRESTException) {
// PayPalRESTException restException = (PayPalRESTException) cause;
// int httpResponseCode = restException.getResponsecode();
//
// return (408 == httpResponseCode);
// }
//
// return false;
// }
//
// /**
// * Determines whether or not the given throwable coming from PayPal's SDK is their
// * representation of a 5xx error
// *
// * @param throwable the throwable that is returned by PayPal's SDK
// * @return whether or not the given throwable represents a 5xx error
// */
// protected boolean is5xxError(Throwable throwable) {
// Throwable cause = throwable.getCause();
// if (cause instanceof PayPalRESTException) {
// PayPalRESTException restException = (PayPalRESTException) cause;
// int httpResponseCode = restException.getResponsecode();
//
// return is5xxError(httpResponseCode);
// }
//
// return false;
// }
//
// private boolean is5xxError(int httpResponseCode) {
// return (httpResponseCode / 100) == 5;
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.broadleafcommerce.payment.service.gateway.DefaultPayPalCheckoutRetryPolicyClassifier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import com.paypal.base.rest.PayPalRESTException; | /*
* Copyright (C) 2009 - 2020 Broadleaf Commerce
*
* Licensed under the Broadleaf End User License Agreement (EULA), Version 1.1 (the
* "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt).
*
* Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the
* "Custom License") between you and Broadleaf Commerce. You may not use this file except in
* compliance with the applicable license.
*
* NOTICE: All information contained herein is, and remains the property of Broadleaf Commerce, LLC
* The intellectual and technical concepts contained herein are proprietary to Broadleaf Commerce,
* LLC and may be covered by U.S. and Foreign Patents, patents in process, and are protected by
* trade secret or copyright law. Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained from Broadleaf Commerce, LLC.
*/
package org.broadleaf.payment.service.gateway;
@Disabled
public class PayPalCheckoutRetryPolicyClassifierTest {
| // Path: services/src/main/java/org/broadleafcommerce/payment/service/gateway/DefaultPayPalCheckoutRetryPolicyClassifier.java
// @RequiredArgsConstructor
// public class DefaultPayPalCheckoutRetryPolicyClassifier
// implements Classifier<Throwable, RetryPolicy> {
//
// @Getter(AccessLevel.PROTECTED)
// private final RetryPolicy retryPolicy;
//
// @Override
// public RetryPolicy classify(Throwable throwable) {
// if (isNetworkError(throwable) || is5xxError(throwable)) {
// return retryPolicy;
// }
//
// return new NeverRetryPolicy();
// }
//
// /**
// * Determines whether or not the given throwable coming from PayPal's SDK is their
// * representation of a network error
// *
// * @param throwable the throwable that is returned by PayPal's SDK
// * @return whether or not the given throwable represents a network error
// */
// protected boolean isNetworkError(Throwable throwable) {
// Throwable cause = throwable.getCause();
// if (cause instanceof PayPalRESTException) {
// PayPalRESTException restException = (PayPalRESTException) cause;
// int httpResponseCode = restException.getResponsecode();
//
// return (408 == httpResponseCode);
// }
//
// return false;
// }
//
// /**
// * Determines whether or not the given throwable coming from PayPal's SDK is their
// * representation of a 5xx error
// *
// * @param throwable the throwable that is returned by PayPal's SDK
// * @return whether or not the given throwable represents a 5xx error
// */
// protected boolean is5xxError(Throwable throwable) {
// Throwable cause = throwable.getCause();
// if (cause instanceof PayPalRESTException) {
// PayPalRESTException restException = (PayPalRESTException) cause;
// int httpResponseCode = restException.getResponsecode();
//
// return is5xxError(httpResponseCode);
// }
//
// return false;
// }
//
// private boolean is5xxError(int httpResponseCode) {
// return (httpResponseCode / 100) == 5;
// }
//
// }
// Path: services/src/test/java/org/broadleaf/payment/service/gateway/PayPalCheckoutRetryPolicyClassifierTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.broadleafcommerce.payment.service.gateway.DefaultPayPalCheckoutRetryPolicyClassifier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import com.paypal.base.rest.PayPalRESTException;
/*
* Copyright (C) 2009 - 2020 Broadleaf Commerce
*
* Licensed under the Broadleaf End User License Agreement (EULA), Version 1.1 (the
* "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt).
*
* Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the
* "Custom License") between you and Broadleaf Commerce. You may not use this file except in
* compliance with the applicable license.
*
* NOTICE: All information contained herein is, and remains the property of Broadleaf Commerce, LLC
* The intellectual and technical concepts contained herein are proprietary to Broadleaf Commerce,
* LLC and may be covered by U.S. and Foreign Patents, patents in process, and are protected by
* trade secret or copyright law. Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained from Broadleaf Commerce, LLC.
*/
package org.broadleaf.payment.service.gateway;
@Disabled
public class PayPalCheckoutRetryPolicyClassifierTest {
| DefaultPayPalCheckoutRetryPolicyClassifier retryPolicyClassifier; |
BroadleafCommerce/blc-paypal | services/src/main/java/org/broadleafcommerce/payment/service/gateway/PayPalCheckoutRestConfigurationProperties.java | // Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/service/PayPalWebExperienceProfileService.java
// public interface PayPalWebExperienceProfileService {
//
// /**
// * Retrieves the id of the WebProfile to be used when creating a PayPal payment
// *
// * @return
// * @throws PaymentException
// */
// @Nullable
// String getWebExperienceProfileId(PaymentRequest paymentRequest);
//
// }
//
// Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/service/payment/MessageConstants.java
// public class MessageConstants {
//
// public static final String CHECKOUT_COMPLETE = "CheckoutComplete";
// public static final String TOTAL = "Total";
// public static final String ESTIMATEDTOTAL = "EstimatedTotal";
// public static final String AUTHORIZATONID = "AUTHORIZATIONID";
// public static final String CAPTUREID = "CAPTUREID";
// public static final String SALEID = "SALEID";
// public static final String REFUNDID = "REFUNDID";
// public static final String NOTE = "NOTE";
// public static final String PAYERID = "PAYERID";
// public static final String PAYMENTID = "PAYMENTID";
// public static final String PAYERSTATUS = "PAYERSTATUS";
// public static final String ADDRESSSTATUS = "PAYMENTREQUEST_n_ADDRESSSTATUS";
// public static final String DETAILSPAYMENTITEMTOTAL = "PAYMENTREQUEST_n_ITEMAMT";
// public static final String DETAILSPAYMENTSHIPPINGTOTAL = "PAYMENTREQUEST_n_SHIPPINGAMT";
// public static final String DETAILSPAYMENTSHIPPINGDISCOUNT = "PAYMENTREQUEST_n_SHIPDISCAMT";
// public static final String DETAILSPAYMENTTOTALTAX = "PAYMENTREQUEST_n_TAXAMT";
// public static final String DETAILSPAYMENTTRANSACTIONID = "PAYMENTREQUEST_n_TRANSACTIONID";
// public static final String DETAILSPAYMENTALLOWEDMETHOD =
// "PAYMENTREQUEST_n_ALLOWEDPAYMENTMETHOD";
// public static final String BILLINGAGREEMENTID = "BILLING_AGREEMENT_ID";
// public static final String BILLINGECTOKEN = "BILLING_EC_TOKEN";
// public static final String AGREEMENTTOKENID = "AGREEMENT_TOKEN_ID";
// public static final String PAYER_PAYMENTMETHOD_PAYPAL = "paypal";
// public static final String PAYER_INFO_EMAIL = "PAYPAL_PAYER_INFO_EMAIL";
// public static final String PAYER_INFO_FIRST_NAME = "PAYPAL_PAYER_INFO_FIRST_NAME";
// public static final String PAYER_INFO_LAST_NAME = "PAYPAL_PAYER_INFO_LAST_NAME";
// public static final String PLAN_TYPE_MERCHANTINITIATEDBILLING = "MERCHANT_INITIATED_BILLING";
// public static final String MERCHANTPREF_ACCEPTEDPAYMENTTYPE_INSTANT = "INSTANT";
// public static final String HTTP_HEADER_AUTH_ASSERTION = "PayPal-Auth-Assertion";
// public static final String HTTP_HEADER_CLIENT_METADATA_ID = "PayPal-Client-Metadata-Id";
// public static final String IDEMPOTENCY_KEY = "idempotency_key";
// public static final String HTTP_HEADER_REQUEST_ID = "PayPal-Request-Id";
// public static final String HTTP_HEADER_MOCK_RESPONSE = "PayPal-Mock-Response";
// public static final String BN = "PayPal-Partner-Attribution-Id";
// public static final String BNCODE = "BroadleafCommerce_Cart_EC";
// public static final String HTTP_PAYERID = "payerId";
// public static final String HTTP_PAYMENTID = "paymentId";
// public static final String HTTP_TOKEN = "token";
// public static final String HTTP_BILLINGTOKEN = "billingToken";
// public static final String HTTP_REQUEST = "HTTP_REQUEST";
// public static final String ERROR_NAME = "errorName";
// public static final String ERROR_MESSAGE = "errorMessage";
// public static final String ERROR_DEBUG_ID = "errorDebugId";
// public static final String CUSTOM_FIELD = "custom_field";
// public static final String TRANSACTION_STATUS = "TRANSACTION_STATUS";
// public static final String PAYMENT_SUBMITTED_TIME = "PAYMENT_SUBMITTED_TIME";
//
// }
| import javax.annotation.PostConstruct;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.broadleafcommerce.vendor.paypal.service.PayPalWebExperienceProfileService;
import org.broadleafcommerce.vendor.paypal.service.payment.MessageConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.broadleafcommerce.paymentgateway.domain.PaymentRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | * company/entity.
*/
private String clientId;
/**
* The client secret provided by PayPal that is used in API calls to verify the applications
* usage of the client id.
*
* @return The client secret provided by PayPal that is used in API calls to verify the
* applications usage of the client id.
*/
private String clientSecret;
/**
* Simple description of the entity that is charging the customer. For example, this may read as
* "My Test Store".
*
* Note, this is the transaction description that will be listed on the customer's credit card
* statement.
*
* @return Simple description of the entity that is charging the customer
*/
private String paymentDescription;
/**
* Type declaration for the label to be displayed in MiniCart for UX. It is one of the following
* values: - Total - EstimatedTotal
*
* @return String
*/ | // Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/service/PayPalWebExperienceProfileService.java
// public interface PayPalWebExperienceProfileService {
//
// /**
// * Retrieves the id of the WebProfile to be used when creating a PayPal payment
// *
// * @return
// * @throws PaymentException
// */
// @Nullable
// String getWebExperienceProfileId(PaymentRequest paymentRequest);
//
// }
//
// Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/service/payment/MessageConstants.java
// public class MessageConstants {
//
// public static final String CHECKOUT_COMPLETE = "CheckoutComplete";
// public static final String TOTAL = "Total";
// public static final String ESTIMATEDTOTAL = "EstimatedTotal";
// public static final String AUTHORIZATONID = "AUTHORIZATIONID";
// public static final String CAPTUREID = "CAPTUREID";
// public static final String SALEID = "SALEID";
// public static final String REFUNDID = "REFUNDID";
// public static final String NOTE = "NOTE";
// public static final String PAYERID = "PAYERID";
// public static final String PAYMENTID = "PAYMENTID";
// public static final String PAYERSTATUS = "PAYERSTATUS";
// public static final String ADDRESSSTATUS = "PAYMENTREQUEST_n_ADDRESSSTATUS";
// public static final String DETAILSPAYMENTITEMTOTAL = "PAYMENTREQUEST_n_ITEMAMT";
// public static final String DETAILSPAYMENTSHIPPINGTOTAL = "PAYMENTREQUEST_n_SHIPPINGAMT";
// public static final String DETAILSPAYMENTSHIPPINGDISCOUNT = "PAYMENTREQUEST_n_SHIPDISCAMT";
// public static final String DETAILSPAYMENTTOTALTAX = "PAYMENTREQUEST_n_TAXAMT";
// public static final String DETAILSPAYMENTTRANSACTIONID = "PAYMENTREQUEST_n_TRANSACTIONID";
// public static final String DETAILSPAYMENTALLOWEDMETHOD =
// "PAYMENTREQUEST_n_ALLOWEDPAYMENTMETHOD";
// public static final String BILLINGAGREEMENTID = "BILLING_AGREEMENT_ID";
// public static final String BILLINGECTOKEN = "BILLING_EC_TOKEN";
// public static final String AGREEMENTTOKENID = "AGREEMENT_TOKEN_ID";
// public static final String PAYER_PAYMENTMETHOD_PAYPAL = "paypal";
// public static final String PAYER_INFO_EMAIL = "PAYPAL_PAYER_INFO_EMAIL";
// public static final String PAYER_INFO_FIRST_NAME = "PAYPAL_PAYER_INFO_FIRST_NAME";
// public static final String PAYER_INFO_LAST_NAME = "PAYPAL_PAYER_INFO_LAST_NAME";
// public static final String PLAN_TYPE_MERCHANTINITIATEDBILLING = "MERCHANT_INITIATED_BILLING";
// public static final String MERCHANTPREF_ACCEPTEDPAYMENTTYPE_INSTANT = "INSTANT";
// public static final String HTTP_HEADER_AUTH_ASSERTION = "PayPal-Auth-Assertion";
// public static final String HTTP_HEADER_CLIENT_METADATA_ID = "PayPal-Client-Metadata-Id";
// public static final String IDEMPOTENCY_KEY = "idempotency_key";
// public static final String HTTP_HEADER_REQUEST_ID = "PayPal-Request-Id";
// public static final String HTTP_HEADER_MOCK_RESPONSE = "PayPal-Mock-Response";
// public static final String BN = "PayPal-Partner-Attribution-Id";
// public static final String BNCODE = "BroadleafCommerce_Cart_EC";
// public static final String HTTP_PAYERID = "payerId";
// public static final String HTTP_PAYMENTID = "paymentId";
// public static final String HTTP_TOKEN = "token";
// public static final String HTTP_BILLINGTOKEN = "billingToken";
// public static final String HTTP_REQUEST = "HTTP_REQUEST";
// public static final String ERROR_NAME = "errorName";
// public static final String ERROR_MESSAGE = "errorMessage";
// public static final String ERROR_DEBUG_ID = "errorDebugId";
// public static final String CUSTOM_FIELD = "custom_field";
// public static final String TRANSACTION_STATUS = "TRANSACTION_STATUS";
// public static final String PAYMENT_SUBMITTED_TIME = "PAYMENT_SUBMITTED_TIME";
//
// }
// Path: services/src/main/java/org/broadleafcommerce/payment/service/gateway/PayPalCheckoutRestConfigurationProperties.java
import javax.annotation.PostConstruct;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.broadleafcommerce.vendor.paypal.service.PayPalWebExperienceProfileService;
import org.broadleafcommerce.vendor.paypal.service.payment.MessageConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.broadleafcommerce.paymentgateway.domain.PaymentRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
* company/entity.
*/
private String clientId;
/**
* The client secret provided by PayPal that is used in API calls to verify the applications
* usage of the client id.
*
* @return The client secret provided by PayPal that is used in API calls to verify the
* applications usage of the client id.
*/
private String clientSecret;
/**
* Simple description of the entity that is charging the customer. For example, this may read as
* "My Test Store".
*
* Note, this is the transaction description that will be listed on the customer's credit card
* statement.
*
* @return Simple description of the entity that is charging the customer
*/
private String paymentDescription;
/**
* Type declaration for the label to be displayed in MiniCart for UX. It is one of the following
* values: - Total - EstimatedTotal
*
* @return String
*/ | private String totalType = MessageConstants.TOTAL; |
BroadleafCommerce/blc-paypal | services/src/main/java/org/broadleafcommerce/vendor/paypal/api/ReportingTransactions.java | // Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/domain/ReportingTransactionResponse.java
// public class ReportingTransactionResponse extends PayPalModel {
//
// public ReportingTransactionResponse() {
//
// }
//
// private List<TransactionDetail> transaction_details;
//
// private String account_number;
//
// private String start_date;
//
// private String end_date;
//
// private String last_refreshed_datetime;
//
// private Integer page;
//
// private Integer total_items;
//
// private Integer total_pages;
//
// public List<TransactionDetail> getTransaction_details() {
// return this.transaction_details;
// }
//
// public ReportingTransactionResponse setTransaction_details(
// List<TransactionDetail> transaction_details) {
// this.transaction_details = transaction_details;
// return this;
// }
//
// public String getAccount_number() {
// return this.account_number;
// }
//
// public ReportingTransactionResponse setAccount_number(String account_number) {
// this.account_number = account_number;
// return this;
// }
//
// public String getStart_date() {
// return this.start_date;
// }
//
// public ReportingTransactionResponse setStart_date(String start_date) {
// this.start_date = start_date;
// return this;
// }
//
// public String getEnd_date() {
// return this.end_date;
// }
//
// public ReportingTransactionResponse setEnd_date(String end_date) {
// this.end_date = end_date;
// return this;
// }
//
// public String getLast_refreshed_datetime() {
// return this.last_refreshed_datetime;
// }
//
// public ReportingTransactionResponse setLast_refreshed_datetime(String last_refreshed_datetime) {
// this.last_refreshed_datetime = last_refreshed_datetime;
// return this;
// }
//
// public Integer getPage() {
// return this.page;
// }
//
// public ReportingTransactionResponse setPage(Integer page) {
// this.page = page;
// return this;
// }
//
// public Integer getTotal_items() {
// return this.total_items;
// }
//
// public ReportingTransactionResponse setTotal_items(Integer total_items) {
// this.total_items = total_items;
// return this;
// }
//
// public Integer getTotal_pages() {
// return this.total_pages;
// }
//
// public ReportingTransactionResponse setTotal_pages(Integer total_pages) {
// this.total_pages = total_pages;
// return this;
// }
//
//
// }
| import org.broadleafcommerce.vendor.paypal.domain.ReportingTransactionResponse;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.HttpMethod;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.rest.PayPalResource;
import com.paypal.base.rest.RESTUtil;
import java.util.Map; | /*
* Copyright (C) 2009 - 2020 Broadleaf Commerce
*
* Licensed under the Broadleaf End User License Agreement (EULA), Version 1.1 (the
* "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt).
*
* Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the
* "Custom License") between you and Broadleaf Commerce. You may not use this file except in
* compliance with the applicable license.
*
* NOTICE: All information contained herein is, and remains the property of Broadleaf Commerce, LLC
* The intellectual and technical concepts contained herein are proprietary to Broadleaf Commerce,
* LLC and may be covered by U.S. and Foreign Patents, patents in process, and are protected by
* trade secret or copyright law. Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained from Broadleaf Commerce, LLC.
*/
package org.broadleafcommerce.vendor.paypal.api;
/**
* The PayPal REST SDK does not currently contain support for Reporting Transactions using the query
* parameters.
*
* This supports executing the PayPal Sync API Reporting Transactions Please refer to this
* https://developer.paypal.com/docs/api/sync/v1/
*
* @author venkat
*
*/
public class ReportingTransactions extends PayPalResource {
public ReportingTransactions() {
}
/**
* Execute a Reporting Transactions API by passing the required query parameters to the request
* URI.
*
* @param queryParams
* <p>
* Following query parameters are used: start_date, end_date and transaction_amount
* </p>
* @param apiContext {@link APIContext} used for the API call.
* @return
* @throws PayPalRESTException
*/ | // Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/domain/ReportingTransactionResponse.java
// public class ReportingTransactionResponse extends PayPalModel {
//
// public ReportingTransactionResponse() {
//
// }
//
// private List<TransactionDetail> transaction_details;
//
// private String account_number;
//
// private String start_date;
//
// private String end_date;
//
// private String last_refreshed_datetime;
//
// private Integer page;
//
// private Integer total_items;
//
// private Integer total_pages;
//
// public List<TransactionDetail> getTransaction_details() {
// return this.transaction_details;
// }
//
// public ReportingTransactionResponse setTransaction_details(
// List<TransactionDetail> transaction_details) {
// this.transaction_details = transaction_details;
// return this;
// }
//
// public String getAccount_number() {
// return this.account_number;
// }
//
// public ReportingTransactionResponse setAccount_number(String account_number) {
// this.account_number = account_number;
// return this;
// }
//
// public String getStart_date() {
// return this.start_date;
// }
//
// public ReportingTransactionResponse setStart_date(String start_date) {
// this.start_date = start_date;
// return this;
// }
//
// public String getEnd_date() {
// return this.end_date;
// }
//
// public ReportingTransactionResponse setEnd_date(String end_date) {
// this.end_date = end_date;
// return this;
// }
//
// public String getLast_refreshed_datetime() {
// return this.last_refreshed_datetime;
// }
//
// public ReportingTransactionResponse setLast_refreshed_datetime(String last_refreshed_datetime) {
// this.last_refreshed_datetime = last_refreshed_datetime;
// return this;
// }
//
// public Integer getPage() {
// return this.page;
// }
//
// public ReportingTransactionResponse setPage(Integer page) {
// this.page = page;
// return this;
// }
//
// public Integer getTotal_items() {
// return this.total_items;
// }
//
// public ReportingTransactionResponse setTotal_items(Integer total_items) {
// this.total_items = total_items;
// return this;
// }
//
// public Integer getTotal_pages() {
// return this.total_pages;
// }
//
// public ReportingTransactionResponse setTotal_pages(Integer total_pages) {
// this.total_pages = total_pages;
// return this;
// }
//
//
// }
// Path: services/src/main/java/org/broadleafcommerce/vendor/paypal/api/ReportingTransactions.java
import org.broadleafcommerce.vendor.paypal.domain.ReportingTransactionResponse;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.HttpMethod;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.base.rest.PayPalResource;
import com.paypal.base.rest.RESTUtil;
import java.util.Map;
/*
* Copyright (C) 2009 - 2020 Broadleaf Commerce
*
* Licensed under the Broadleaf End User License Agreement (EULA), Version 1.1 (the
* "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt).
*
* Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the
* "Custom License") between you and Broadleaf Commerce. You may not use this file except in
* compliance with the applicable license.
*
* NOTICE: All information contained herein is, and remains the property of Broadleaf Commerce, LLC
* The intellectual and technical concepts contained herein are proprietary to Broadleaf Commerce,
* LLC and may be covered by U.S. and Foreign Patents, patents in process, and are protected by
* trade secret or copyright law. Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained from Broadleaf Commerce, LLC.
*/
package org.broadleafcommerce.vendor.paypal.api;
/**
* The PayPal REST SDK does not currently contain support for Reporting Transactions using the query
* parameters.
*
* This supports executing the PayPal Sync API Reporting Transactions Please refer to this
* https://developer.paypal.com/docs/api/sync/v1/
*
* @author venkat
*
*/
public class ReportingTransactions extends PayPalResource {
public ReportingTransactions() {
}
/**
* Execute a Reporting Transactions API by passing the required query parameters to the request
* URI.
*
* @param queryParams
* <p>
* Following query parameters are used: start_date, end_date and transaction_amount
* </p>
* @param apiContext {@link APIContext} used for the API call.
* @return
* @throws PayPalRESTException
*/ | public ReportingTransactionResponse get(Map<String, String> queryParams, APIContext apiContext) |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
| import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting; | package com.autonomousapps.reactivestopwatch.ui;
public interface StopwatchMvp {
interface View {
void onTick(long tick);
void onStopwatchStarted();
void onStopwatchStopped();
void onStopwatchReset();
| // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
package com.autonomousapps.reactivestopwatch.ui;
public interface StopwatchMvp {
interface View {
void onTick(long tick);
void onStopwatchStarted();
void onStopwatchStopped();
void onStopwatchReset();
| void onNewLap(@NonNull Lap lap); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
| import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting; | package com.autonomousapps.reactivestopwatch.ui;
public interface StopwatchMvp {
interface View {
void onTick(long tick);
void onStopwatchStarted();
void onStopwatchStopped();
void onStopwatchReset();
void onNewLap(@NonNull Lap lap);
/*
* Manual injection for testing
*/
@VisibleForTesting | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
package com.autonomousapps.reactivestopwatch.ui;
public interface StopwatchMvp {
interface View {
void onTick(long tick);
void onStopwatchStarted();
void onStopwatchStopped();
void onStopwatchReset();
void onNewLap(@NonNull Lap lap);
/*
* Manual injection for testing
*/
@VisibleForTesting | void setTimeTeller(@NonNull TimeTeller timeTeller); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
| import com.autonomousapps.common.LogUtil;
import android.app.Application;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable; | package com.autonomousapps;
public abstract class LifecycleLoggingApplication extends Application {
private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
log("onCreate()");
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
log("onTrimMemory(%d)", level);
}
private static void log(@NonNull String msg, @Nullable Object... args) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
// Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
import com.autonomousapps.common.LogUtil;
import android.app.Application;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
package com.autonomousapps;
public abstract class LifecycleLoggingApplication extends Application {
private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
log("onCreate()");
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
log("onTrimMemory(%d)", level);
}
private static void log(@NonNull String msg, @Nullable Object... args) { | LogUtil.v(TAG, msg, args); |
autonomousapps/ReactiveStopwatch | app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractMockedDependenciesTest.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/di/TestStopwatchComponent.java
// @Singleton
// @Component(modules = TestModule.class)
// public interface TestStopwatchComponent extends StopwatchComponent {
//
// void inject(StopwatchFragmentTest test);
//
// // TODO remove once bug is fixed
// void inject(StopwatchFragment fragment);
//
// // TODO remove once bug is fixed
// void inject(StopwatchService service);
// }
| import com.autonomousapps.reactivestopwatch.di.DaggerTestStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.TestStopwatchComponent;
import org.junit.Before;
import android.support.annotation.CallSuper; | package com.autonomousapps.reactivestopwatch.test;
public abstract class AbstractMockedDependenciesTest extends AbstractAnimationDisablingTest {
protected TestStopwatchComponent testComponent;
@Before
@CallSuper
public void setup() throws Exception {
initInjections();
}
private void initInjections() {
testComponent = DaggerTestStopwatchComponent.create(); | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/di/TestStopwatchComponent.java
// @Singleton
// @Component(modules = TestModule.class)
// public interface TestStopwatchComponent extends StopwatchComponent {
//
// void inject(StopwatchFragmentTest test);
//
// // TODO remove once bug is fixed
// void inject(StopwatchFragment fragment);
//
// // TODO remove once bug is fixed
// void inject(StopwatchService service);
// }
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractMockedDependenciesTest.java
import com.autonomousapps.reactivestopwatch.di.DaggerTestStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.TestStopwatchComponent;
import org.junit.Before;
import android.support.annotation.CallSuper;
package com.autonomousapps.reactivestopwatch.test;
public abstract class AbstractMockedDependenciesTest extends AbstractAnimationDisablingTest {
protected TestStopwatchComponent testComponent;
@Before
@CallSuper
public void setup() throws Exception {
initInjections();
}
private void initInjections() {
testComponent = DaggerTestStopwatchComponent.create(); | DaggerUtil.INSTANCE.setComponent(testComponent); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | package com.autonomousapps.reactivestopwatch.ui;
@UiThread
public class StopwatchPresenter implements StopwatchMvp.Presenter {
private static final String TAG = StopwatchPresenter.class.getSimpleName();
| // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
package com.autonomousapps.reactivestopwatch.ui;
@UiThread
public class StopwatchPresenter implements StopwatchMvp.Presenter {
private static final String TAG = StopwatchPresenter.class.getSimpleName();
| private final Stopwatch stopwatch; |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | } else {
getView().onStopwatchStarted();
}
}
@Override
public void resetOrLap() {
Log.d(TAG, "resetOrLap()");
if (isRunning()) {
lap();
} else {
reset();
}
}
private boolean isRunning() {
return stopwatchSubscription != null && !stopwatch.isPaused();
}
private void reset() {
stopwatch.reset();
if (stopwatchSubscription != null) {
stopwatchSubscription.unsubscribe();
stopwatchSubscription = null;
}
getView().onStopwatchReset();
}
private void lap() { | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
} else {
getView().onStopwatchStarted();
}
}
@Override
public void resetOrLap() {
Log.d(TAG, "resetOrLap()");
if (isRunning()) {
lap();
} else {
reset();
}
}
private boolean isRunning() {
return stopwatchSubscription != null && !stopwatch.isPaused();
}
private void reset() {
stopwatch.reset();
if (stopwatchSubscription != null) {
stopwatchSubscription.unsubscribe();
stopwatchSubscription = null;
}
getView().onStopwatchReset();
}
private void lap() { | Lap lap = stopwatch.lap(); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | Log.d(TAG, "resetOrLap()");
if (isRunning()) {
lap();
} else {
reset();
}
}
private boolean isRunning() {
return stopwatchSubscription != null && !stopwatch.isPaused();
}
private void reset() {
stopwatch.reset();
if (stopwatchSubscription != null) {
stopwatchSubscription.unsubscribe();
stopwatchSubscription = null;
}
getView().onStopwatchReset();
}
private void lap() {
Lap lap = stopwatch.lap();
getView().onNewLap(lap);
}
@NonNull
private StopwatchMvp.View getView() {
if (view == null) { | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
Log.d(TAG, "resetOrLap()");
if (isRunning()) {
lap();
} else {
reset();
}
}
private boolean isRunning() {
return stopwatchSubscription != null && !stopwatch.isPaused();
}
private void reset() {
stopwatch.reset();
if (stopwatchSubscription != null) {
stopwatchSubscription.unsubscribe();
stopwatchSubscription = null;
}
getView().onStopwatchReset();
}
private void lap() {
Lap lap = stopwatch.lap();
getView().onNewLap(lap);
}
@NonNull
private StopwatchMvp.View getView() {
if (view == null) { | throw new ViewNotAttachedException(); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/StopwatchApplication.java | // Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
// public abstract class LifecycleLoggingApplication extends Application {
//
// private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
//
// @Override
// public void onCreate() {
// super.onCreate();
// log("onCreate()");
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// log("onTrimMemory(%d)", level);
// }
//
// private static void log(@NonNull String msg, @Nullable Object... args) {
// LogUtil.v(TAG, msg, args);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/ContextModule.java
// @Module
// public class ContextModule {
//
// // Application Context
// private final Context appContext;
//
// public ContextModule(@NonNull Context context) {
// appContext = context;
// }
//
// @Provides
// @Singleton
// Context provideContext() {
// return appContext;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/StopwatchComponent.java
// @Singleton
// @Component(modules = {
// PresenterModule.class
// })
// public interface StopwatchComponent {
//
// void inject(StopwatchFragment stopwatchFragment);
//
// void inject(StopwatchService service);
// }
| import com.autonomousapps.LifecycleLoggingApplication;
import com.autonomousapps.reactivestopwatch.di.ContextModule;
import com.autonomousapps.reactivestopwatch.di.DaggerStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.StopwatchComponent; | package com.autonomousapps.reactivestopwatch;
public class StopwatchApplication extends LifecycleLoggingApplication {
@Override
public void onCreate() {
super.onCreate();
initDagger();
}
private void initDagger() { | // Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
// public abstract class LifecycleLoggingApplication extends Application {
//
// private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
//
// @Override
// public void onCreate() {
// super.onCreate();
// log("onCreate()");
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// log("onTrimMemory(%d)", level);
// }
//
// private static void log(@NonNull String msg, @Nullable Object... args) {
// LogUtil.v(TAG, msg, args);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/ContextModule.java
// @Module
// public class ContextModule {
//
// // Application Context
// private final Context appContext;
//
// public ContextModule(@NonNull Context context) {
// appContext = context;
// }
//
// @Provides
// @Singleton
// Context provideContext() {
// return appContext;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/StopwatchComponent.java
// @Singleton
// @Component(modules = {
// PresenterModule.class
// })
// public interface StopwatchComponent {
//
// void inject(StopwatchFragment stopwatchFragment);
//
// void inject(StopwatchService service);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/StopwatchApplication.java
import com.autonomousapps.LifecycleLoggingApplication;
import com.autonomousapps.reactivestopwatch.di.ContextModule;
import com.autonomousapps.reactivestopwatch.di.DaggerStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.StopwatchComponent;
package com.autonomousapps.reactivestopwatch;
public class StopwatchApplication extends LifecycleLoggingApplication {
@Override
public void onCreate() {
super.onCreate();
initDagger();
}
private void initDagger() { | StopwatchComponent component = DaggerStopwatchComponent.builder() |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/StopwatchApplication.java | // Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
// public abstract class LifecycleLoggingApplication extends Application {
//
// private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
//
// @Override
// public void onCreate() {
// super.onCreate();
// log("onCreate()");
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// log("onTrimMemory(%d)", level);
// }
//
// private static void log(@NonNull String msg, @Nullable Object... args) {
// LogUtil.v(TAG, msg, args);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/ContextModule.java
// @Module
// public class ContextModule {
//
// // Application Context
// private final Context appContext;
//
// public ContextModule(@NonNull Context context) {
// appContext = context;
// }
//
// @Provides
// @Singleton
// Context provideContext() {
// return appContext;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/StopwatchComponent.java
// @Singleton
// @Component(modules = {
// PresenterModule.class
// })
// public interface StopwatchComponent {
//
// void inject(StopwatchFragment stopwatchFragment);
//
// void inject(StopwatchService service);
// }
| import com.autonomousapps.LifecycleLoggingApplication;
import com.autonomousapps.reactivestopwatch.di.ContextModule;
import com.autonomousapps.reactivestopwatch.di.DaggerStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.StopwatchComponent; | package com.autonomousapps.reactivestopwatch;
public class StopwatchApplication extends LifecycleLoggingApplication {
@Override
public void onCreate() {
super.onCreate();
initDagger();
}
private void initDagger() {
StopwatchComponent component = DaggerStopwatchComponent.builder() | // Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
// public abstract class LifecycleLoggingApplication extends Application {
//
// private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
//
// @Override
// public void onCreate() {
// super.onCreate();
// log("onCreate()");
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// log("onTrimMemory(%d)", level);
// }
//
// private static void log(@NonNull String msg, @Nullable Object... args) {
// LogUtil.v(TAG, msg, args);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/ContextModule.java
// @Module
// public class ContextModule {
//
// // Application Context
// private final Context appContext;
//
// public ContextModule(@NonNull Context context) {
// appContext = context;
// }
//
// @Provides
// @Singleton
// Context provideContext() {
// return appContext;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/StopwatchComponent.java
// @Singleton
// @Component(modules = {
// PresenterModule.class
// })
// public interface StopwatchComponent {
//
// void inject(StopwatchFragment stopwatchFragment);
//
// void inject(StopwatchService service);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/StopwatchApplication.java
import com.autonomousapps.LifecycleLoggingApplication;
import com.autonomousapps.reactivestopwatch.di.ContextModule;
import com.autonomousapps.reactivestopwatch.di.DaggerStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.StopwatchComponent;
package com.autonomousapps.reactivestopwatch;
public class StopwatchApplication extends LifecycleLoggingApplication {
@Override
public void onCreate() {
super.onCreate();
initDagger();
}
private void initDagger() {
StopwatchComponent component = DaggerStopwatchComponent.builder() | .contextModule(new ContextModule(this)) |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/StopwatchApplication.java | // Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
// public abstract class LifecycleLoggingApplication extends Application {
//
// private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
//
// @Override
// public void onCreate() {
// super.onCreate();
// log("onCreate()");
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// log("onTrimMemory(%d)", level);
// }
//
// private static void log(@NonNull String msg, @Nullable Object... args) {
// LogUtil.v(TAG, msg, args);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/ContextModule.java
// @Module
// public class ContextModule {
//
// // Application Context
// private final Context appContext;
//
// public ContextModule(@NonNull Context context) {
// appContext = context;
// }
//
// @Provides
// @Singleton
// Context provideContext() {
// return appContext;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/StopwatchComponent.java
// @Singleton
// @Component(modules = {
// PresenterModule.class
// })
// public interface StopwatchComponent {
//
// void inject(StopwatchFragment stopwatchFragment);
//
// void inject(StopwatchService service);
// }
| import com.autonomousapps.LifecycleLoggingApplication;
import com.autonomousapps.reactivestopwatch.di.ContextModule;
import com.autonomousapps.reactivestopwatch.di.DaggerStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.StopwatchComponent; | package com.autonomousapps.reactivestopwatch;
public class StopwatchApplication extends LifecycleLoggingApplication {
@Override
public void onCreate() {
super.onCreate();
initDagger();
}
private void initDagger() {
StopwatchComponent component = DaggerStopwatchComponent.builder()
.contextModule(new ContextModule(this))
.build(); | // Path: app/src/main/java/com/autonomousapps/LifecycleLoggingApplication.java
// public abstract class LifecycleLoggingApplication extends Application {
//
// private static final String TAG = LifecycleLoggingApplication.class.getSimpleName();
//
// @Override
// public void onCreate() {
// super.onCreate();
// log("onCreate()");
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// log("onTrimMemory(%d)", level);
// }
//
// private static void log(@NonNull String msg, @Nullable Object... args) {
// LogUtil.v(TAG, msg, args);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/ContextModule.java
// @Module
// public class ContextModule {
//
// // Application Context
// private final Context appContext;
//
// public ContextModule(@NonNull Context context) {
// appContext = context;
// }
//
// @Provides
// @Singleton
// Context provideContext() {
// return appContext;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/StopwatchComponent.java
// @Singleton
// @Component(modules = {
// PresenterModule.class
// })
// public interface StopwatchComponent {
//
// void inject(StopwatchFragment stopwatchFragment);
//
// void inject(StopwatchService service);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/StopwatchApplication.java
import com.autonomousapps.LifecycleLoggingApplication;
import com.autonomousapps.reactivestopwatch.di.ContextModule;
import com.autonomousapps.reactivestopwatch.di.DaggerStopwatchComponent;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.di.StopwatchComponent;
package com.autonomousapps.reactivestopwatch;
public class StopwatchApplication extends LifecycleLoggingApplication {
@Override
public void onCreate() {
super.onCreate();
initDagger();
}
private void initDagger() {
StopwatchComponent component = DaggerStopwatchComponent.builder()
.contextModule(new ContextModule(this))
.build(); | DaggerUtil.INSTANCE.setComponent(component); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription; | package com.autonomousapps.reactivestopwatch.service;
public class StopwatchService extends LifecycleLoggingService {
private static final String TAG = StopwatchService.class.getSimpleName();
@Inject
@Named("local") | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
package com.autonomousapps.reactivestopwatch.service;
public class StopwatchService extends LifecycleLoggingService {
private static final String TAG = StopwatchService.class.getSimpleName();
@Inject
@Named("local") | Stopwatch stopwatch; |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription; | package com.autonomousapps.reactivestopwatch.service;
public class StopwatchService extends LifecycleLoggingService {
private static final String TAG = StopwatchService.class.getSimpleName();
@Inject
@Named("local")
Stopwatch stopwatch;
private final CompositeSubscription subscriptions = new CompositeSubscription();
boolean isRunning = false;
@Override
public void onCreate() {
super.onCreate(); | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
package com.autonomousapps.reactivestopwatch.service;
public class StopwatchService extends LifecycleLoggingService {
private static final String TAG = StopwatchService.class.getSimpleName();
@Inject
@Named("local")
Stopwatch stopwatch;
private final CompositeSubscription subscriptions = new CompositeSubscription();
boolean isRunning = false;
@Override
public void onCreate() {
super.onCreate(); | DaggerUtil.INSTANCE.getStopwatchComponent().inject(this); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription; | super.onCreate();
DaggerUtil.INSTANCE.getStopwatchComponent().inject(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY; // TODO which?
}
@Override
public void onDestroy() {
subscriptions.clear();
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
/**
* If {@link #stopwatch} is no longer running and all clients are unbound, stop service.
*/
@Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
if (!isRunning) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
super.onCreate();
DaggerUtil.INSTANCE.getStopwatchComponent().inject(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY; // TODO which?
}
@Override
public void onDestroy() {
subscriptions.clear();
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
/**
* If {@link #stopwatch} is no longer running and all clients are unbound, stop service.
*/
@Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
if (!isRunning) { | LogUtil.v(TAG + "_lifecycle", "stopSelf()"); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
| import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription; | setIsRunning(true);
}
private void onTick(long tick) {
try {
listener.onTick(tick);
} catch (RemoteException e) {
// TODO: more robust error handling
LogUtil.e(TAG, "RemoteException calling listener::onTick: " + e.getLocalizedMessage());
}
}
@Override
public void togglePause() throws RemoteException {
stopwatch.togglePause(); // TODO not idempotent. Should do nothing if not started/paused
setIsRunning(!isPaused());
}
@Override
public boolean isPaused() throws RemoteException {
return stopwatch.isPaused();
}
@Override
public void reset() throws RemoteException {
stopwatch.reset();
setIsRunning(false);
}
@Override | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
setIsRunning(true);
}
private void onTick(long tick) {
try {
listener.onTick(tick);
} catch (RemoteException e) {
// TODO: more robust error handling
LogUtil.e(TAG, "RemoteException calling listener::onTick: " + e.getLocalizedMessage());
}
}
@Override
public void togglePause() throws RemoteException {
stopwatch.togglePause(); // TODO not idempotent. Should do nothing if not started/paused
setIsRunning(!isPaused());
}
@Override
public boolean isPaused() throws RemoteException {
return stopwatch.isPaused();
}
@Override
public void reset() throws RemoteException {
stopwatch.reset();
setIsRunning(false);
}
@Override | public Lap lap() throws RemoteException { |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/service/LifecycleLoggingService.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
| import com.autonomousapps.common.LogUtil;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString; | package com.autonomousapps.reactivestopwatch.service;
public abstract class LifecycleLoggingService extends Service {
private static final String TAG = LifecycleLoggingService.class.getSimpleName();
@Override
public int onStartCommand(Intent intent, int flags, int startId) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/LifecycleLoggingService.java
import com.autonomousapps.common.LogUtil;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString;
package com.autonomousapps.reactivestopwatch.service;
public abstract class LifecycleLoggingService extends Service {
private static final String TAG = LifecycleLoggingService.class.getSimpleName();
@Override
public int onStartCommand(Intent intent, int flags, int startId) { | log("onStartCommand(%s, %d, %d)", asString(intent), flags, startId); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/service/LifecycleLoggingService.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
| import com.autonomousapps.common.LogUtil;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString; | super.onDestroy();
log("onDestroy()");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
log("onBind(%s)", asString(intent));
return null;
}
@Override
public boolean onUnbind(Intent intent) {
log("onUnbind(%s)", asString(intent));
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
log("onRebind(%s)", asString(intent));
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
log("onTrimMemory(%d)", level);
}
private static void log(@NonNull String msg, @Nullable Object... args) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/LifecycleLoggingService.java
import com.autonomousapps.common.LogUtil;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString;
super.onDestroy();
log("onDestroy()");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
log("onBind(%s)", asString(intent));
return null;
}
@Override
public boolean onUnbind(Intent intent) {
log("onUnbind(%s)", asString(intent));
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
log("onRebind(%s)", asString(intent));
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
log("onTrimMemory(%d)", level);
}
private static void log(@NonNull String msg, @Nullable Object... args) { | LogUtil.v(TAG, msg, args); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/time/StopwatchImpl.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
| import com.autonomousapps.common.LogUtil;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject; | package com.autonomousapps.reactivestopwatch.time;
public class StopwatchImpl extends AbstractStopwatch {
private static final String TAG = StopwatchImpl.class.getSimpleName();
static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
private Scheduler scheduler = Schedulers.computation();
private final List<Lap> laps = new ArrayList<>();
private Observable<Long> timerObservable = null;
private final PublishSubject<Void> stop = PublishSubject.create();
private volatile boolean isPaused = false;
private volatile long startTime = 0L;
private long pausedTime = 0L;
private final TimeProvider timeProvider;
@Inject
StopwatchImpl(@NonNull TimeProvider timeProvider) {
this.timeProvider = timeProvider;
}
@NonNull
@Override
public Observable<Long> start() {
if (timerObservable != null) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/StopwatchImpl.java
import com.autonomousapps.common.LogUtil;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
package com.autonomousapps.reactivestopwatch.time;
public class StopwatchImpl extends AbstractStopwatch {
private static final String TAG = StopwatchImpl.class.getSimpleName();
static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
private Scheduler scheduler = Schedulers.computation();
private final List<Lap> laps = new ArrayList<>();
private Observable<Long> timerObservable = null;
private final PublishSubject<Void> stop = PublishSubject.create();
private volatile boolean isPaused = false;
private volatile long startTime = 0L;
private long pausedTime = 0L;
private final TimeProvider timeProvider;
@Inject
StopwatchImpl(@NonNull TimeProvider timeProvider) {
this.timeProvider = timeProvider;
}
@NonNull
@Override
public Observable<Long> start() {
if (timerObservable != null) { | LogUtil.d(TAG, "start(). Returning original Observable"); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/LifecycleLoggingActivity.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
| import com.autonomousapps.common.LogUtil;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString; | package com.autonomousapps.reactivestopwatch.ui;
public abstract class LifecycleLoggingActivity extends Activity {
private static final String TAG = LifecycleLoggingActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/LifecycleLoggingActivity.java
import com.autonomousapps.common.LogUtil;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString;
package com.autonomousapps.reactivestopwatch.ui;
public abstract class LifecycleLoggingActivity extends Activity {
private static final String TAG = LifecycleLoggingActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | log("onCreate(%s)", asString(savedInstanceState)); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/LifecycleLoggingActivity.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
| import com.autonomousapps.common.LogUtil;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString; | protected void onRestart() {
super.onRestart();
log("onRestart()");
}
@Override
protected void onResume() {
super.onResume();
log("onResume()");
}
@Override
protected void onPause() {
log("onPause()");
super.onPause();
}
@Override
protected void onStop() {
log("onStop()");
super.onStop();
}
@Override
protected void onDestroy() {
log("onDestroy()");
super.onDestroy();
}
private static void log(@NonNull String msg, @Nullable Object... args) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/LifecycleLoggingActivity.java
import com.autonomousapps.common.LogUtil;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import static com.autonomousapps.common.LogUtil.asString;
protected void onRestart() {
super.onRestart();
log("onRestart()");
}
@Override
protected void onResume() {
super.onResume();
log("onResume()");
}
@Override
protected void onPause() {
log("onPause()");
super.onPause();
}
@Override
protected void onStop() {
log("onStop()");
super.onStop();
}
@Override
protected void onDestroy() {
log("onDestroy()");
super.onDestroy();
}
private static void log(@NonNull String msg, @Nullable Object... args) { | LogUtil.v(TAG, msg, args); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/di/PresenterModule.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
// @UiThread
// public class StopwatchPresenter implements StopwatchMvp.Presenter {
//
// private static final String TAG = StopwatchPresenter.class.getSimpleName();
//
// private final Stopwatch stopwatch;
//
// private StopwatchMvp.View view;
//
// private Subscription stopwatchSubscription = null;
//
// private Scheduler subscribingScheduler = Schedulers.computation();
// private Scheduler observingScheduler = AndroidSchedulers.mainThread();
//
// @Inject
// StopwatchPresenter(@NonNull @Named("remote") Stopwatch stopwatch) {
// this.stopwatch = stopwatch;
// }
//
// @Override
// public void attachView(@NonNull StopwatchMvp.View view) {
// Log.d(TAG, "attachView()");
// this.view = view;
// stopwatch.onUiShown();
// }
//
// @Override
// public void detachView() {
// Log.d(TAG, "detachView()");
// view = null;
// stopwatch.onUiHidden();
// }
//
// @Override
// public void startOrStop() {
// Log.d(TAG, "startOrStop()");
//
// if (stopwatchSubscription == null) {
// start();
// } else {
// togglePause();
// }
// }
//
// private void start() {
// Log.d(TAG, "start()");
//
// getView().onStopwatchStarted();
//
// stopwatchSubscription = stopwatch.start()
// .onBackpressureDrop()
// .subscribeOn(subscribingScheduler)
// .observeOn(observingScheduler)
// .filter(ignored -> isAttached())
// .subscribe(new Subscriber<Long>() {
// @Override
// public void onCompleted() {
// Log.d(TAG, "onCompleted()");
// }
//
// @Override
// public void onError(Throwable e) {
// Log.e(TAG, "onError: " + e.getLocalizedMessage());
// e.printStackTrace();
// }
//
// @Override
// public void onNext(Long tick) {
// getView().onTick(tick);
// request(1L); // "reactive pull backpressure". See https://github.com/ReactiveX/RxJava/wiki/Backpressure
// }
// });
// }
//
// private void togglePause() {
// Log.d(TAG, "togglePause()");
//
// stopwatch.togglePause();
//
// if (stopwatch.isPaused()) {
// getView().onStopwatchStopped();
// } else {
// getView().onStopwatchStarted();
// }
// }
//
// @Override
// public void resetOrLap() {
// Log.d(TAG, "resetOrLap()");
//
// if (isRunning()) {
// lap();
// } else {
// reset();
// }
// }
//
// private boolean isRunning() {
// return stopwatchSubscription != null && !stopwatch.isPaused();
// }
//
// private void reset() {
// stopwatch.reset();
// if (stopwatchSubscription != null) {
// stopwatchSubscription.unsubscribe();
// stopwatchSubscription = null;
// }
// getView().onStopwatchReset();
// }
//
// private void lap() {
// Lap lap = stopwatch.lap();
// getView().onNewLap(lap);
// }
//
// @NonNull
// private StopwatchMvp.View getView() {
// if (view == null) {
// throw new ViewNotAttachedException();
// }
// return view;
// }
//
// private boolean isAttached() {
// return view != null;
// }
//
// @VisibleForTesting
// void setTestScheduler(@NonNull Scheduler scheduler) {
// subscribingScheduler = scheduler;
// observingScheduler = scheduler;
// }
// }
| import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import com.autonomousapps.reactivestopwatch.ui.StopwatchPresenter;
import dagger.Binds;
import dagger.Module; | package com.autonomousapps.reactivestopwatch.di;
@Module(includes = {
StopwatchModule.class
})
abstract class PresenterModule {
@Binds | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
// @UiThread
// public class StopwatchPresenter implements StopwatchMvp.Presenter {
//
// private static final String TAG = StopwatchPresenter.class.getSimpleName();
//
// private final Stopwatch stopwatch;
//
// private StopwatchMvp.View view;
//
// private Subscription stopwatchSubscription = null;
//
// private Scheduler subscribingScheduler = Schedulers.computation();
// private Scheduler observingScheduler = AndroidSchedulers.mainThread();
//
// @Inject
// StopwatchPresenter(@NonNull @Named("remote") Stopwatch stopwatch) {
// this.stopwatch = stopwatch;
// }
//
// @Override
// public void attachView(@NonNull StopwatchMvp.View view) {
// Log.d(TAG, "attachView()");
// this.view = view;
// stopwatch.onUiShown();
// }
//
// @Override
// public void detachView() {
// Log.d(TAG, "detachView()");
// view = null;
// stopwatch.onUiHidden();
// }
//
// @Override
// public void startOrStop() {
// Log.d(TAG, "startOrStop()");
//
// if (stopwatchSubscription == null) {
// start();
// } else {
// togglePause();
// }
// }
//
// private void start() {
// Log.d(TAG, "start()");
//
// getView().onStopwatchStarted();
//
// stopwatchSubscription = stopwatch.start()
// .onBackpressureDrop()
// .subscribeOn(subscribingScheduler)
// .observeOn(observingScheduler)
// .filter(ignored -> isAttached())
// .subscribe(new Subscriber<Long>() {
// @Override
// public void onCompleted() {
// Log.d(TAG, "onCompleted()");
// }
//
// @Override
// public void onError(Throwable e) {
// Log.e(TAG, "onError: " + e.getLocalizedMessage());
// e.printStackTrace();
// }
//
// @Override
// public void onNext(Long tick) {
// getView().onTick(tick);
// request(1L); // "reactive pull backpressure". See https://github.com/ReactiveX/RxJava/wiki/Backpressure
// }
// });
// }
//
// private void togglePause() {
// Log.d(TAG, "togglePause()");
//
// stopwatch.togglePause();
//
// if (stopwatch.isPaused()) {
// getView().onStopwatchStopped();
// } else {
// getView().onStopwatchStarted();
// }
// }
//
// @Override
// public void resetOrLap() {
// Log.d(TAG, "resetOrLap()");
//
// if (isRunning()) {
// lap();
// } else {
// reset();
// }
// }
//
// private boolean isRunning() {
// return stopwatchSubscription != null && !stopwatch.isPaused();
// }
//
// private void reset() {
// stopwatch.reset();
// if (stopwatchSubscription != null) {
// stopwatchSubscription.unsubscribe();
// stopwatchSubscription = null;
// }
// getView().onStopwatchReset();
// }
//
// private void lap() {
// Lap lap = stopwatch.lap();
// getView().onNewLap(lap);
// }
//
// @NonNull
// private StopwatchMvp.View getView() {
// if (view == null) {
// throw new ViewNotAttachedException();
// }
// return view;
// }
//
// private boolean isAttached() {
// return view != null;
// }
//
// @VisibleForTesting
// void setTestScheduler(@NonNull Scheduler scheduler) {
// subscribingScheduler = scheduler;
// observingScheduler = scheduler;
// }
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/PresenterModule.java
import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import com.autonomousapps.reactivestopwatch.ui.StopwatchPresenter;
import dagger.Binds;
import dagger.Module;
package com.autonomousapps.reactivestopwatch.di;
@Module(includes = {
StopwatchModule.class
})
abstract class PresenterModule {
@Binds | public abstract StopwatchMvp.Presenter bindStopwatchPresenter(StopwatchPresenter stopwatchPresenter); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/di/PresenterModule.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
// @UiThread
// public class StopwatchPresenter implements StopwatchMvp.Presenter {
//
// private static final String TAG = StopwatchPresenter.class.getSimpleName();
//
// private final Stopwatch stopwatch;
//
// private StopwatchMvp.View view;
//
// private Subscription stopwatchSubscription = null;
//
// private Scheduler subscribingScheduler = Schedulers.computation();
// private Scheduler observingScheduler = AndroidSchedulers.mainThread();
//
// @Inject
// StopwatchPresenter(@NonNull @Named("remote") Stopwatch stopwatch) {
// this.stopwatch = stopwatch;
// }
//
// @Override
// public void attachView(@NonNull StopwatchMvp.View view) {
// Log.d(TAG, "attachView()");
// this.view = view;
// stopwatch.onUiShown();
// }
//
// @Override
// public void detachView() {
// Log.d(TAG, "detachView()");
// view = null;
// stopwatch.onUiHidden();
// }
//
// @Override
// public void startOrStop() {
// Log.d(TAG, "startOrStop()");
//
// if (stopwatchSubscription == null) {
// start();
// } else {
// togglePause();
// }
// }
//
// private void start() {
// Log.d(TAG, "start()");
//
// getView().onStopwatchStarted();
//
// stopwatchSubscription = stopwatch.start()
// .onBackpressureDrop()
// .subscribeOn(subscribingScheduler)
// .observeOn(observingScheduler)
// .filter(ignored -> isAttached())
// .subscribe(new Subscriber<Long>() {
// @Override
// public void onCompleted() {
// Log.d(TAG, "onCompleted()");
// }
//
// @Override
// public void onError(Throwable e) {
// Log.e(TAG, "onError: " + e.getLocalizedMessage());
// e.printStackTrace();
// }
//
// @Override
// public void onNext(Long tick) {
// getView().onTick(tick);
// request(1L); // "reactive pull backpressure". See https://github.com/ReactiveX/RxJava/wiki/Backpressure
// }
// });
// }
//
// private void togglePause() {
// Log.d(TAG, "togglePause()");
//
// stopwatch.togglePause();
//
// if (stopwatch.isPaused()) {
// getView().onStopwatchStopped();
// } else {
// getView().onStopwatchStarted();
// }
// }
//
// @Override
// public void resetOrLap() {
// Log.d(TAG, "resetOrLap()");
//
// if (isRunning()) {
// lap();
// } else {
// reset();
// }
// }
//
// private boolean isRunning() {
// return stopwatchSubscription != null && !stopwatch.isPaused();
// }
//
// private void reset() {
// stopwatch.reset();
// if (stopwatchSubscription != null) {
// stopwatchSubscription.unsubscribe();
// stopwatchSubscription = null;
// }
// getView().onStopwatchReset();
// }
//
// private void lap() {
// Lap lap = stopwatch.lap();
// getView().onNewLap(lap);
// }
//
// @NonNull
// private StopwatchMvp.View getView() {
// if (view == null) {
// throw new ViewNotAttachedException();
// }
// return view;
// }
//
// private boolean isAttached() {
// return view != null;
// }
//
// @VisibleForTesting
// void setTestScheduler(@NonNull Scheduler scheduler) {
// subscribingScheduler = scheduler;
// observingScheduler = scheduler;
// }
// }
| import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import com.autonomousapps.reactivestopwatch.ui.StopwatchPresenter;
import dagger.Binds;
import dagger.Module; | package com.autonomousapps.reactivestopwatch.di;
@Module(includes = {
StopwatchModule.class
})
abstract class PresenterModule {
@Binds | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenter.java
// @UiThread
// public class StopwatchPresenter implements StopwatchMvp.Presenter {
//
// private static final String TAG = StopwatchPresenter.class.getSimpleName();
//
// private final Stopwatch stopwatch;
//
// private StopwatchMvp.View view;
//
// private Subscription stopwatchSubscription = null;
//
// private Scheduler subscribingScheduler = Schedulers.computation();
// private Scheduler observingScheduler = AndroidSchedulers.mainThread();
//
// @Inject
// StopwatchPresenter(@NonNull @Named("remote") Stopwatch stopwatch) {
// this.stopwatch = stopwatch;
// }
//
// @Override
// public void attachView(@NonNull StopwatchMvp.View view) {
// Log.d(TAG, "attachView()");
// this.view = view;
// stopwatch.onUiShown();
// }
//
// @Override
// public void detachView() {
// Log.d(TAG, "detachView()");
// view = null;
// stopwatch.onUiHidden();
// }
//
// @Override
// public void startOrStop() {
// Log.d(TAG, "startOrStop()");
//
// if (stopwatchSubscription == null) {
// start();
// } else {
// togglePause();
// }
// }
//
// private void start() {
// Log.d(TAG, "start()");
//
// getView().onStopwatchStarted();
//
// stopwatchSubscription = stopwatch.start()
// .onBackpressureDrop()
// .subscribeOn(subscribingScheduler)
// .observeOn(observingScheduler)
// .filter(ignored -> isAttached())
// .subscribe(new Subscriber<Long>() {
// @Override
// public void onCompleted() {
// Log.d(TAG, "onCompleted()");
// }
//
// @Override
// public void onError(Throwable e) {
// Log.e(TAG, "onError: " + e.getLocalizedMessage());
// e.printStackTrace();
// }
//
// @Override
// public void onNext(Long tick) {
// getView().onTick(tick);
// request(1L); // "reactive pull backpressure". See https://github.com/ReactiveX/RxJava/wiki/Backpressure
// }
// });
// }
//
// private void togglePause() {
// Log.d(TAG, "togglePause()");
//
// stopwatch.togglePause();
//
// if (stopwatch.isPaused()) {
// getView().onStopwatchStopped();
// } else {
// getView().onStopwatchStarted();
// }
// }
//
// @Override
// public void resetOrLap() {
// Log.d(TAG, "resetOrLap()");
//
// if (isRunning()) {
// lap();
// } else {
// reset();
// }
// }
//
// private boolean isRunning() {
// return stopwatchSubscription != null && !stopwatch.isPaused();
// }
//
// private void reset() {
// stopwatch.reset();
// if (stopwatchSubscription != null) {
// stopwatchSubscription.unsubscribe();
// stopwatchSubscription = null;
// }
// getView().onStopwatchReset();
// }
//
// private void lap() {
// Lap lap = stopwatch.lap();
// getView().onNewLap(lap);
// }
//
// @NonNull
// private StopwatchMvp.View getView() {
// if (view == null) {
// throw new ViewNotAttachedException();
// }
// return view;
// }
//
// private boolean isAttached() {
// return view != null;
// }
//
// @VisibleForTesting
// void setTestScheduler(@NonNull Scheduler scheduler) {
// subscribingScheduler = scheduler;
// observingScheduler = scheduler;
// }
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/PresenterModule.java
import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import com.autonomousapps.reactivestopwatch.ui.StopwatchPresenter;
import dagger.Binds;
import dagger.Module;
package com.autonomousapps.reactivestopwatch.di;
@Module(includes = {
StopwatchModule.class
})
abstract class PresenterModule {
@Binds | public abstract StopwatchMvp.Presenter bindStopwatchPresenter(StopwatchPresenter stopwatchPresenter); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/time/RemoteStopwatch.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
// public class StopwatchService extends LifecycleLoggingService {
//
// private static final String TAG = StopwatchService.class.getSimpleName();
//
// @Inject
// @Named("local")
// Stopwatch stopwatch;
//
// private final CompositeSubscription subscriptions = new CompositeSubscription();
//
// boolean isRunning = false;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DaggerUtil.INSTANCE.getStopwatchComponent().inject(this);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// super.onStartCommand(intent, flags, startId);
//
// return START_NOT_STICKY; // TODO which?
// }
//
// @Override
// public void onDestroy() {
// subscriptions.clear();
// super.onDestroy();
// }
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return binder;
// }
//
// /**
// * If {@link #stopwatch} is no longer running and all clients are unbound, stop service.
// */
// @Override
// public boolean onUnbind(Intent intent) {
// super.onUnbind(intent);
// if (!isRunning) {
// LogUtil.v(TAG + "_lifecycle", "stopSelf()");
// stopSelf();
// }
//
// return false; // False by default. True calls onRebind in future
// }
//
// void setIsRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
//
// private final IStopwatchService.Stub binder = new IStopwatchService.Stub() {
//
// private IStopwatchTickListener listener;
//
// @Override
// public void start(IStopwatchTickListener listener) throws RemoteException {
// this.listener = listener;
//
// Subscription subscription = stopwatch.start().subscribe(this::onTick);
// subscriptions.add(subscription);
//
// setIsRunning(true);
// }
//
// private void onTick(long tick) {
// try {
// listener.onTick(tick);
// } catch (RemoteException e) {
// // TODO: more robust error handling
// LogUtil.e(TAG, "RemoteException calling listener::onTick: " + e.getLocalizedMessage());
// }
// }
//
// @Override
// public void togglePause() throws RemoteException {
// stopwatch.togglePause(); // TODO not idempotent. Should do nothing if not started/paused
// setIsRunning(!isPaused());
// }
//
// @Override
// public boolean isPaused() throws RemoteException {
// return stopwatch.isPaused();
// }
//
// @Override
// public void reset() throws RemoteException {
// stopwatch.reset();
// setIsRunning(false);
// }
//
// @Override
// public Lap lap() throws RemoteException {
// return stopwatch.lap();
// }
//
// @Override
// public void close() {
// stopwatch.close();
// }
// };
// }
| import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.service.IStopwatchService;
import com.autonomousapps.reactivestopwatch.service.IStopwatchTickListener;
import com.autonomousapps.reactivestopwatch.service.StopwatchService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription; | package com.autonomousapps.reactivestopwatch.time;
// Inspiration from http://www.donnfelker.com/rxjava-with-aidl-services/
// This also represents an implementation of the Adapter pattern.
public class RemoteStopwatch implements Stopwatch {
private static final String TAG = RemoteStopwatch.class.getSimpleName();
private final Context context;
private IStopwatchService remoteService;
private BehaviorSubject<IStopwatchService> serviceConnectionSubject = BehaviorSubject.create();
private CompositeSubscription subscriptions;
@Inject
RemoteStopwatch(@NonNull Context context) {
this.context = context;
subscriptions = new CompositeSubscription();
startService();
}
// I want the service to continue running even when unbound, so I start it first
private void startService() { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
// public class StopwatchService extends LifecycleLoggingService {
//
// private static final String TAG = StopwatchService.class.getSimpleName();
//
// @Inject
// @Named("local")
// Stopwatch stopwatch;
//
// private final CompositeSubscription subscriptions = new CompositeSubscription();
//
// boolean isRunning = false;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DaggerUtil.INSTANCE.getStopwatchComponent().inject(this);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// super.onStartCommand(intent, flags, startId);
//
// return START_NOT_STICKY; // TODO which?
// }
//
// @Override
// public void onDestroy() {
// subscriptions.clear();
// super.onDestroy();
// }
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return binder;
// }
//
// /**
// * If {@link #stopwatch} is no longer running and all clients are unbound, stop service.
// */
// @Override
// public boolean onUnbind(Intent intent) {
// super.onUnbind(intent);
// if (!isRunning) {
// LogUtil.v(TAG + "_lifecycle", "stopSelf()");
// stopSelf();
// }
//
// return false; // False by default. True calls onRebind in future
// }
//
// void setIsRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
//
// private final IStopwatchService.Stub binder = new IStopwatchService.Stub() {
//
// private IStopwatchTickListener listener;
//
// @Override
// public void start(IStopwatchTickListener listener) throws RemoteException {
// this.listener = listener;
//
// Subscription subscription = stopwatch.start().subscribe(this::onTick);
// subscriptions.add(subscription);
//
// setIsRunning(true);
// }
//
// private void onTick(long tick) {
// try {
// listener.onTick(tick);
// } catch (RemoteException e) {
// // TODO: more robust error handling
// LogUtil.e(TAG, "RemoteException calling listener::onTick: " + e.getLocalizedMessage());
// }
// }
//
// @Override
// public void togglePause() throws RemoteException {
// stopwatch.togglePause(); // TODO not idempotent. Should do nothing if not started/paused
// setIsRunning(!isPaused());
// }
//
// @Override
// public boolean isPaused() throws RemoteException {
// return stopwatch.isPaused();
// }
//
// @Override
// public void reset() throws RemoteException {
// stopwatch.reset();
// setIsRunning(false);
// }
//
// @Override
// public Lap lap() throws RemoteException {
// return stopwatch.lap();
// }
//
// @Override
// public void close() {
// stopwatch.close();
// }
// };
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/RemoteStopwatch.java
import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.service.IStopwatchService;
import com.autonomousapps.reactivestopwatch.service.IStopwatchTickListener;
import com.autonomousapps.reactivestopwatch.service.StopwatchService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription;
package com.autonomousapps.reactivestopwatch.time;
// Inspiration from http://www.donnfelker.com/rxjava-with-aidl-services/
// This also represents an implementation of the Adapter pattern.
public class RemoteStopwatch implements Stopwatch {
private static final String TAG = RemoteStopwatch.class.getSimpleName();
private final Context context;
private IStopwatchService remoteService;
private BehaviorSubject<IStopwatchService> serviceConnectionSubject = BehaviorSubject.create();
private CompositeSubscription subscriptions;
@Inject
RemoteStopwatch(@NonNull Context context) {
this.context = context;
subscriptions = new CompositeSubscription();
startService();
}
// I want the service to continue running even when unbound, so I start it first
private void startService() { | Intent serviceIntent = new Intent(context, StopwatchService.class); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/time/RemoteStopwatch.java | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
// public class StopwatchService extends LifecycleLoggingService {
//
// private static final String TAG = StopwatchService.class.getSimpleName();
//
// @Inject
// @Named("local")
// Stopwatch stopwatch;
//
// private final CompositeSubscription subscriptions = new CompositeSubscription();
//
// boolean isRunning = false;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DaggerUtil.INSTANCE.getStopwatchComponent().inject(this);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// super.onStartCommand(intent, flags, startId);
//
// return START_NOT_STICKY; // TODO which?
// }
//
// @Override
// public void onDestroy() {
// subscriptions.clear();
// super.onDestroy();
// }
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return binder;
// }
//
// /**
// * If {@link #stopwatch} is no longer running and all clients are unbound, stop service.
// */
// @Override
// public boolean onUnbind(Intent intent) {
// super.onUnbind(intent);
// if (!isRunning) {
// LogUtil.v(TAG + "_lifecycle", "stopSelf()");
// stopSelf();
// }
//
// return false; // False by default. True calls onRebind in future
// }
//
// void setIsRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
//
// private final IStopwatchService.Stub binder = new IStopwatchService.Stub() {
//
// private IStopwatchTickListener listener;
//
// @Override
// public void start(IStopwatchTickListener listener) throws RemoteException {
// this.listener = listener;
//
// Subscription subscription = stopwatch.start().subscribe(this::onTick);
// subscriptions.add(subscription);
//
// setIsRunning(true);
// }
//
// private void onTick(long tick) {
// try {
// listener.onTick(tick);
// } catch (RemoteException e) {
// // TODO: more robust error handling
// LogUtil.e(TAG, "RemoteException calling listener::onTick: " + e.getLocalizedMessage());
// }
// }
//
// @Override
// public void togglePause() throws RemoteException {
// stopwatch.togglePause(); // TODO not idempotent. Should do nothing if not started/paused
// setIsRunning(!isPaused());
// }
//
// @Override
// public boolean isPaused() throws RemoteException {
// return stopwatch.isPaused();
// }
//
// @Override
// public void reset() throws RemoteException {
// stopwatch.reset();
// setIsRunning(false);
// }
//
// @Override
// public Lap lap() throws RemoteException {
// return stopwatch.lap();
// }
//
// @Override
// public void close() {
// stopwatch.close();
// }
// };
// }
| import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.service.IStopwatchService;
import com.autonomousapps.reactivestopwatch.service.IStopwatchTickListener;
import com.autonomousapps.reactivestopwatch.service.StopwatchService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription; |
@Inject
RemoteStopwatch(@NonNull Context context) {
this.context = context;
subscriptions = new CompositeSubscription();
startService();
}
// I want the service to continue running even when unbound, so I start it first
private void startService() {
Intent serviceIntent = new Intent(context, StopwatchService.class);
context.startService(serviceIntent);
}
@Override
public void onUiShown() {
Intent serviceIntent = new Intent(context, StopwatchService.class);
context.bindService(serviceIntent, remoteServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onUiHidden() {
context.unbindService(remoteServiceConnection);
subscriptions.clear();
remoteService = null;
}
private final ServiceConnection remoteServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) { | // Path: app/src/main/java/com/autonomousapps/common/LogUtil.java
// public class LogUtil {
//
// public static void v(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.v(tag, String.format(msg, args));
// }
//
// public static void d(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.d(tag, String.format(msg, args));
// }
//
// public static void e(@NonNull String tag, @NonNull String msg, @Nullable Object... args) {
// Log.e(tag, String.format(msg, args));
// }
//
// @NonNull
// public static String asString(@Nullable Object obj) {
// return obj != null ? obj.toString() : "null";
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/service/StopwatchService.java
// public class StopwatchService extends LifecycleLoggingService {
//
// private static final String TAG = StopwatchService.class.getSimpleName();
//
// @Inject
// @Named("local")
// Stopwatch stopwatch;
//
// private final CompositeSubscription subscriptions = new CompositeSubscription();
//
// boolean isRunning = false;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DaggerUtil.INSTANCE.getStopwatchComponent().inject(this);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// super.onStartCommand(intent, flags, startId);
//
// return START_NOT_STICKY; // TODO which?
// }
//
// @Override
// public void onDestroy() {
// subscriptions.clear();
// super.onDestroy();
// }
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return binder;
// }
//
// /**
// * If {@link #stopwatch} is no longer running and all clients are unbound, stop service.
// */
// @Override
// public boolean onUnbind(Intent intent) {
// super.onUnbind(intent);
// if (!isRunning) {
// LogUtil.v(TAG + "_lifecycle", "stopSelf()");
// stopSelf();
// }
//
// return false; // False by default. True calls onRebind in future
// }
//
// void setIsRunning(boolean isRunning) {
// this.isRunning = isRunning;
// }
//
// private final IStopwatchService.Stub binder = new IStopwatchService.Stub() {
//
// private IStopwatchTickListener listener;
//
// @Override
// public void start(IStopwatchTickListener listener) throws RemoteException {
// this.listener = listener;
//
// Subscription subscription = stopwatch.start().subscribe(this::onTick);
// subscriptions.add(subscription);
//
// setIsRunning(true);
// }
//
// private void onTick(long tick) {
// try {
// listener.onTick(tick);
// } catch (RemoteException e) {
// // TODO: more robust error handling
// LogUtil.e(TAG, "RemoteException calling listener::onTick: " + e.getLocalizedMessage());
// }
// }
//
// @Override
// public void togglePause() throws RemoteException {
// stopwatch.togglePause(); // TODO not idempotent. Should do nothing if not started/paused
// setIsRunning(!isPaused());
// }
//
// @Override
// public boolean isPaused() throws RemoteException {
// return stopwatch.isPaused();
// }
//
// @Override
// public void reset() throws RemoteException {
// stopwatch.reset();
// setIsRunning(false);
// }
//
// @Override
// public Lap lap() throws RemoteException {
// return stopwatch.lap();
// }
//
// @Override
// public void close() {
// stopwatch.close();
// }
// };
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/RemoteStopwatch.java
import com.autonomousapps.common.LogUtil;
import com.autonomousapps.reactivestopwatch.service.IStopwatchService;
import com.autonomousapps.reactivestopwatch.service.IStopwatchTickListener;
import com.autonomousapps.reactivestopwatch.service.StopwatchService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription;
@Inject
RemoteStopwatch(@NonNull Context context) {
this.context = context;
subscriptions = new CompositeSubscription();
startService();
}
// I want the service to continue running even when unbound, so I start it first
private void startService() {
Intent serviceIntent = new Intent(context, StopwatchService.class);
context.startService(serviceIntent);
}
@Override
public void onUiShown() {
Intent serviceIntent = new Intent(context, StopwatchService.class);
context.bindService(serviceIntent, remoteServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onUiHidden() {
context.unbindService(remoteServiceConnection);
subscriptions.clear();
remoteService = null;
}
private final ServiceConnection remoteServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) { | LogUtil.d(TAG, "onServiceConnected()"); |
autonomousapps/ReactiveStopwatch | app/src/androidTest/java/com/autonomousapps/reactivestopwatch/di/TestModule.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
| import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
import static org.mockito.Mockito.mock; | package com.autonomousapps.reactivestopwatch.di;
@Module
class TestModule {
| // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/di/TestModule.java
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
import static org.mockito.Mockito.mock;
package com.autonomousapps.reactivestopwatch.di;
@Module
class TestModule {
| private final StopwatchMvp.Presenter mockStopwatchPresenter; |
autonomousapps/ReactiveStopwatch | app/src/androidTest/java/com/autonomousapps/reactivestopwatch/di/TestModule.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
| import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
import static org.mockito.Mockito.mock; | package com.autonomousapps.reactivestopwatch.di;
@Module
class TestModule {
private final StopwatchMvp.Presenter mockStopwatchPresenter; | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Stopwatch.java
// public interface Stopwatch extends AutoCloseable {
//
// /**
// * TODO
// */
// void onUiShown();
//
// /**
// * TODO
// */
// void onUiHidden();
//
// /**
// * Starts the stopwatch.
// *
// * @return an Observable with each item emitted being the time, in milliseconds, since the stopwatch was started.
// */
// @NonNull
// Observable<Long> start();
//
// /**
// * Pauses or unpauses, depending on the current state of the stopwatch.
// */
// void togglePause();
//
// /**
// * @return true if the stopwatch is paused; false otherwise.
// */
// boolean isPaused();
//
// /**
// * Resets the stopwatch.
// */
// void reset();
//
// /**
// * Calculates a {@link Lap} with duration and end time.
// *
// * @return the lap just created.
// */
// @NonNull
// Lap lap();
//
// @Override
// void close(); // AutoCloseable
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchMvp.java
// public interface StopwatchMvp {
//
// interface View {
//
// void onTick(long tick);
//
// void onStopwatchStarted();
//
// void onStopwatchStopped();
//
// void onStopwatchReset();
//
// void onNewLap(@NonNull Lap lap);
//
// /*
// * Manual injection for testing
// */
// @VisibleForTesting
// void setTimeTeller(@NonNull TimeTeller timeTeller);
// }
//
// interface Presenter {
//
// void attachView(@NonNull View view);
//
// void detachView();
//
// void startOrStop();
//
// void resetOrLap();
// }
// }
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/di/TestModule.java
import com.autonomousapps.reactivestopwatch.time.Stopwatch;
import com.autonomousapps.reactivestopwatch.ui.StopwatchMvp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
import static org.mockito.Mockito.mock;
package com.autonomousapps.reactivestopwatch.di;
@Module
class TestModule {
private final StopwatchMvp.Presenter mockStopwatchPresenter; | private final Stopwatch mockStopwatch; |
autonomousapps/ReactiveStopwatch | app/src/test/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenterTest.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/StopwatchImpl.java
// public class StopwatchImpl extends AbstractStopwatch {
//
// private static final String TAG = StopwatchImpl.class.getSimpleName();
//
// static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
//
// private Scheduler scheduler = Schedulers.computation();
//
// private final List<Lap> laps = new ArrayList<>();
//
// private Observable<Long> timerObservable = null;
// private final PublishSubject<Void> stop = PublishSubject.create();
// private volatile boolean isPaused = false;
//
// private volatile long startTime = 0L;
// private long pausedTime = 0L;
//
// private final TimeProvider timeProvider;
//
// @Inject
// StopwatchImpl(@NonNull TimeProvider timeProvider) {
// this.timeProvider = timeProvider;
// }
//
// @NonNull
// @Override
// public Observable<Long> start() {
// if (timerObservable != null) {
// LogUtil.d(TAG, "start(). Returning original Observable");
// return timerObservable;
// }
//
// LogUtil.d(TAG, "start(). Returning new Observable");
//
// startTime = timeProvider.now();
//
// // Using Observable.interval() to produce events as fast as possible
// timerObservable = Observable.interval(1, TIME_UNIT, scheduler)
// .onBackpressureDrop()
// .takeUntil(stop)
// .filter(ignored -> isNotPaused())
// .map(ignored -> timeProvider.now() - startTime);
//
// return timerObservable;
// }
//
// private boolean isNotPaused() {
// return !isPaused;
// }
//
// @Override
// public void togglePause() {
// LogUtil.d(TAG, "togglePause()");
//
// isPaused = !isPaused;
// if (isPaused) {
// pausedTime = timeProvider.now();
// } else {
// startTime += timeProvider.now() - pausedTime;
// }
// }
//
// @Override
// public boolean isPaused() {
// LogUtil.d(TAG, "isPaused()=%s", isPaused);
//
// return isPaused;
// }
//
// @Override
// public void reset() {
// LogUtil.d(TAG, "reset()");
//
// isPaused = false;
// stop.onNext(null);
// timerObservable = null;
// }
//
// // TODO do I need the list of laps?
// @NonNull
// @Override
// public Lap lap() {
// LogUtil.d(TAG, "lap()");
//
// long lastEndTime = 0L;
// int lastIndex = laps.size() - 1;
// if (lastIndex >= 0) {
// Lap lastLap = laps.get(lastIndex);
// lastEndTime = lastLap.endTime();
// }
// long now = timeProvider.now();
// Lap lap = Lap.create(now - lastEndTime, now);
// laps.add(lap);
// return lap;
// }
//
// @VisibleForTesting
// void setScheduler(@NonNull Scheduler testScheduler) {
// scheduler = testScheduler;
// }
// }
| import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.StopwatchImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import rx.Observable;
import rx.schedulers.TestScheduler;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; | package com.autonomousapps.reactivestopwatch.ui;
@RunWith(MockitoJUnitRunner.class)
public class StopwatchPresenterTest {
| // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/mvp/ViewNotAttachedException.java
// public class ViewNotAttachedException extends RuntimeException {
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/StopwatchImpl.java
// public class StopwatchImpl extends AbstractStopwatch {
//
// private static final String TAG = StopwatchImpl.class.getSimpleName();
//
// static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
//
// private Scheduler scheduler = Schedulers.computation();
//
// private final List<Lap> laps = new ArrayList<>();
//
// private Observable<Long> timerObservable = null;
// private final PublishSubject<Void> stop = PublishSubject.create();
// private volatile boolean isPaused = false;
//
// private volatile long startTime = 0L;
// private long pausedTime = 0L;
//
// private final TimeProvider timeProvider;
//
// @Inject
// StopwatchImpl(@NonNull TimeProvider timeProvider) {
// this.timeProvider = timeProvider;
// }
//
// @NonNull
// @Override
// public Observable<Long> start() {
// if (timerObservable != null) {
// LogUtil.d(TAG, "start(). Returning original Observable");
// return timerObservable;
// }
//
// LogUtil.d(TAG, "start(). Returning new Observable");
//
// startTime = timeProvider.now();
//
// // Using Observable.interval() to produce events as fast as possible
// timerObservable = Observable.interval(1, TIME_UNIT, scheduler)
// .onBackpressureDrop()
// .takeUntil(stop)
// .filter(ignored -> isNotPaused())
// .map(ignored -> timeProvider.now() - startTime);
//
// return timerObservable;
// }
//
// private boolean isNotPaused() {
// return !isPaused;
// }
//
// @Override
// public void togglePause() {
// LogUtil.d(TAG, "togglePause()");
//
// isPaused = !isPaused;
// if (isPaused) {
// pausedTime = timeProvider.now();
// } else {
// startTime += timeProvider.now() - pausedTime;
// }
// }
//
// @Override
// public boolean isPaused() {
// LogUtil.d(TAG, "isPaused()=%s", isPaused);
//
// return isPaused;
// }
//
// @Override
// public void reset() {
// LogUtil.d(TAG, "reset()");
//
// isPaused = false;
// stop.onNext(null);
// timerObservable = null;
// }
//
// // TODO do I need the list of laps?
// @NonNull
// @Override
// public Lap lap() {
// LogUtil.d(TAG, "lap()");
//
// long lastEndTime = 0L;
// int lastIndex = laps.size() - 1;
// if (lastIndex >= 0) {
// Lap lastLap = laps.get(lastIndex);
// lastEndTime = lastLap.endTime();
// }
// long now = timeProvider.now();
// Lap lap = Lap.create(now - lastEndTime, now);
// laps.add(lap);
// return lap;
// }
//
// @VisibleForTesting
// void setScheduler(@NonNull Scheduler testScheduler) {
// scheduler = testScheduler;
// }
// }
// Path: app/src/test/java/com/autonomousapps/reactivestopwatch/ui/StopwatchPresenterTest.java
import com.autonomousapps.reactivestopwatch.mvp.ViewNotAttachedException;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.time.StopwatchImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import rx.Observable;
import rx.schedulers.TestScheduler;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
package com.autonomousapps.reactivestopwatch.ui;
@RunWith(MockitoJUnitRunner.class)
public class StopwatchPresenterTest {
| @Mock StopwatchImpl stopwatch; |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragment.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
| import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick; | package com.autonomousapps.reactivestopwatch.ui;
public class StopwatchFragment extends Fragment implements StopwatchMvp.View {
public static String TAG = StopwatchFragment.class.getSimpleName();
@BindView(R.id.stopwatch) | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragment.java
import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
package com.autonomousapps.reactivestopwatch.ui;
public class StopwatchFragment extends Fragment implements StopwatchMvp.View {
public static String TAG = StopwatchFragment.class.getSimpleName();
@BindView(R.id.stopwatch) | TimeTeller timeTeller; |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragment.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
| import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick; | package com.autonomousapps.reactivestopwatch.ui;
public class StopwatchFragment extends Fragment implements StopwatchMvp.View {
public static String TAG = StopwatchFragment.class.getSimpleName();
@BindView(R.id.stopwatch)
TimeTeller timeTeller;
@BindView(R.id.btn_reset_lap)
Button resetLapButton;
@BindView(R.id.btn_start_stop)
Button startStopButton;
@Inject StopwatchMvp.Presenter presenter;
public StopwatchFragment() {
}
public static StopwatchFragment newInstance() {
return new StopwatchFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
| // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragment.java
import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
package com.autonomousapps.reactivestopwatch.ui;
public class StopwatchFragment extends Fragment implements StopwatchMvp.View {
public static String TAG = StopwatchFragment.class.getSimpleName();
@BindView(R.id.stopwatch)
TimeTeller timeTeller;
@BindView(R.id.btn_reset_lap)
Button resetLapButton;
@BindView(R.id.btn_start_stop)
Button startStopButton;
@Inject StopwatchMvp.Presenter presenter;
public StopwatchFragment() {
}
public static StopwatchFragment newInstance() {
return new StopwatchFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
| DaggerUtil.INSTANCE.getStopwatchComponent().inject(this); |
autonomousapps/ReactiveStopwatch | app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragment.java | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
| import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick; |
private long lastTimeLogged = -1L;
// Because of backpressure, this will log AT MOST every second
private void logEverySecond(long timeInMillis) { // TODO use TimeUnit instead of assuming callers are passing correct units?
if (timeInMillis % 1000L == 0L && timeInMillis != lastTimeLogged) {
lastTimeLogged = timeInMillis; // sometimes we get two consecutive ticks with the same time.
Log.d(TAG, "onTick(): " + timeInMillis);
}
}
@Override
public void onStopwatchStarted() {
setStartStopButtonText(R.string.stop);
setResetLapButton(R.string.lap);
}
@Override
public void onStopwatchStopped() {
setStartStopButtonText(R.string.start);
setResetLapButton(R.string.reset);
}
@Override
public void onStopwatchReset() {
timeTeller.tellTime(0L);
setStartStopButtonText(R.string.start);
}
@Override | // Path: app/src/main/java/com/autonomousapps/reactivestopwatch/di/DaggerUtil.java
// public enum DaggerUtil {
// INSTANCE;
//
// private StopwatchComponent stopwatchComponent;
//
// @NonNull
// public StopwatchComponent getStopwatchComponent() {
// checkNotNull();
// return stopwatchComponent;
// }
//
// private void checkNotNull() {
// if (stopwatchComponent == null) {
// throw new IllegalStateException("StopwatchComponent is null. setComponent() must be called first!");
// }
// }
//
// public void setComponent(@NonNull StopwatchComponent component) {
// stopwatchComponent = component;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/time/Lap.java
// @AutoValue
// public abstract class Lap implements Parcelable {
//
// static final Lap BAD_LAP = create(-1L, -1L);
//
// public static Lap create(long duration, long endTime) {
// return new AutoValue_Lap(duration, endTime);
// }
//
// abstract long duration();
//
// abstract long endTime();
//
// // Manual Parcelable implementation because auto-value-parcel does not work with AIDL yet.
// // Tools bug: https://code.google.com/p/android/issues/detail?id=224480
// public static final Parcelable.Creator<Lap> CREATOR = new
// Parcelable.Creator<Lap>() {
// public Lap createFromParcel(Parcel in) {
// return Lap.create(in);
// }
//
// public Lap[] newArray(int size) {
// return new Lap[size];
// }
// };
//
// private static Lap create(Parcel in) {
// return Lap.create(in.readLong(), in.readLong());
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeLong(duration());
// out.writeLong(endTime());
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragment.java
import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.di.DaggerUtil;
import com.autonomousapps.reactivestopwatch.time.Lap;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
private long lastTimeLogged = -1L;
// Because of backpressure, this will log AT MOST every second
private void logEverySecond(long timeInMillis) { // TODO use TimeUnit instead of assuming callers are passing correct units?
if (timeInMillis % 1000L == 0L && timeInMillis != lastTimeLogged) {
lastTimeLogged = timeInMillis; // sometimes we get two consecutive ticks with the same time.
Log.d(TAG, "onTick(): " + timeInMillis);
}
}
@Override
public void onStopwatchStarted() {
setStartStopButtonText(R.string.stop);
setResetLapButton(R.string.lap);
}
@Override
public void onStopwatchStopped() {
setStartStopButtonText(R.string.start);
setResetLapButton(R.string.reset);
}
@Override
public void onStopwatchReset() {
timeTeller.tellTime(0L);
setStartStopButtonText(R.string.start);
}
@Override | public void onNewLap(@NonNull Lap lap) { |
autonomousapps/ReactiveStopwatch | app/src/androidTest/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragmentTest.java | // Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractMockedDependenciesTest.java
// public abstract class AbstractMockedDependenciesTest extends AbstractAnimationDisablingTest {
//
// protected TestStopwatchComponent testComponent;
//
// @Before
// @CallSuper
// public void setup() throws Exception {
// initInjections();
// }
//
// private void initInjections() {
// testComponent = DaggerTestStopwatchComponent.create();
// DaggerUtil.INSTANCE.setComponent(testComponent);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/CommonEspressoCalls.java
// public static ViewInteraction verifyViewIsDisplayedWithTextIgnoreCase(@NonNull String text) {
// return onView(withText(equalToIgnoringCase(text))).check(matches(isDisplayed()));
// }
| import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.test.AbstractMockedDependenciesTest;
import com.autonomousapps.reactivestopwatch.test.annotations.CommitStage;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.test.rule.ActivityTestRule;
import javax.inject.Inject;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static com.autonomousapps.reactivestopwatch.test.CommonEspressoCalls.verifyViewIsDisplayedWithTextIgnoreCase;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; | package com.autonomousapps.reactivestopwatch.ui;
@CommitStage
public class StopwatchFragmentTest extends AbstractMockedDependenciesTest {
private static final String START_TEXT = "start";
private static final String STOP_TEXT = "stop";
private static final String RESET_TEXT = "reset";
private static final String LAP_TEXT = "lap";
@Inject StopwatchMvp.Presenter stopwatchPresenter;
private StopwatchMvp.View view = null;
| // Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractMockedDependenciesTest.java
// public abstract class AbstractMockedDependenciesTest extends AbstractAnimationDisablingTest {
//
// protected TestStopwatchComponent testComponent;
//
// @Before
// @CallSuper
// public void setup() throws Exception {
// initInjections();
// }
//
// private void initInjections() {
// testComponent = DaggerTestStopwatchComponent.create();
// DaggerUtil.INSTANCE.setComponent(testComponent);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/CommonEspressoCalls.java
// public static ViewInteraction verifyViewIsDisplayedWithTextIgnoreCase(@NonNull String text) {
// return onView(withText(equalToIgnoringCase(text))).check(matches(isDisplayed()));
// }
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragmentTest.java
import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.test.AbstractMockedDependenciesTest;
import com.autonomousapps.reactivestopwatch.test.annotations.CommitStage;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.test.rule.ActivityTestRule;
import javax.inject.Inject;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static com.autonomousapps.reactivestopwatch.test.CommonEspressoCalls.verifyViewIsDisplayedWithTextIgnoreCase;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
package com.autonomousapps.reactivestopwatch.ui;
@CommitStage
public class StopwatchFragmentTest extends AbstractMockedDependenciesTest {
private static final String START_TEXT = "start";
private static final String STOP_TEXT = "stop";
private static final String RESET_TEXT = "reset";
private static final String LAP_TEXT = "lap";
@Inject StopwatchMvp.Presenter stopwatchPresenter;
private StopwatchMvp.View view = null;
| private TimeTeller mockTimeTeller; |
autonomousapps/ReactiveStopwatch | app/src/androidTest/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragmentTest.java | // Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractMockedDependenciesTest.java
// public abstract class AbstractMockedDependenciesTest extends AbstractAnimationDisablingTest {
//
// protected TestStopwatchComponent testComponent;
//
// @Before
// @CallSuper
// public void setup() throws Exception {
// initInjections();
// }
//
// private void initInjections() {
// testComponent = DaggerTestStopwatchComponent.create();
// DaggerUtil.INSTANCE.setComponent(testComponent);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/CommonEspressoCalls.java
// public static ViewInteraction verifyViewIsDisplayedWithTextIgnoreCase(@NonNull String text) {
// return onView(withText(equalToIgnoringCase(text))).check(matches(isDisplayed()));
// }
| import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.test.AbstractMockedDependenciesTest;
import com.autonomousapps.reactivestopwatch.test.annotations.CommitStage;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.test.rule.ActivityTestRule;
import javax.inject.Inject;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static com.autonomousapps.reactivestopwatch.test.CommonEspressoCalls.verifyViewIsDisplayedWithTextIgnoreCase;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; | private void setupMockView() {
doAnswer(invocation -> view = (StopwatchMvp.View) invocation.getArguments()[0])
.when(stopwatchPresenter).attachView(any(StopwatchMvp.View.class));
doAnswer(invocation -> view = null)
.when(stopwatchPresenter).detachView();
}
private void verifyUi() throws Exception {
onView(withId(R.id.stopwatch)).check(matches(isDisplayed()));
onView(withId(R.id.btn_reset_lap)).check(matches(isDisplayed()));
onView(withId(R.id.btn_start_stop)).check(matches(isDisplayed()));
}
private void launchApp() {
activityRule.launchActivity(new Intent());
mockTimeTeller = mock(TimeTeller.class);
view.setTimeTeller(mockTimeTeller);
}
@Test
public void onTickShouldUpdateTime() throws Throwable {
onMainThreadDo(() -> view.onTick(1000L));
verify(mockTimeTeller).tellTime(1000L);
}
@Test
public void onStartedShouldChangeText() throws Throwable {
onMainThreadDo(() -> view.onStopwatchStarted());
| // Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractMockedDependenciesTest.java
// public abstract class AbstractMockedDependenciesTest extends AbstractAnimationDisablingTest {
//
// protected TestStopwatchComponent testComponent;
//
// @Before
// @CallSuper
// public void setup() throws Exception {
// initInjections();
// }
//
// private void initInjections() {
// testComponent = DaggerTestStopwatchComponent.create();
// DaggerUtil.INSTANCE.setComponent(testComponent);
// }
// }
//
// Path: app/src/main/java/com/autonomousapps/reactivestopwatch/view/TimeTeller.java
// public interface TimeTeller {
//
// /**
// * Sets the current time to {@param timeInMillis}.
// */
// void tellTime(long timeInMillis);
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/CommonEspressoCalls.java
// public static ViewInteraction verifyViewIsDisplayedWithTextIgnoreCase(@NonNull String text) {
// return onView(withText(equalToIgnoringCase(text))).check(matches(isDisplayed()));
// }
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/ui/StopwatchFragmentTest.java
import com.autonomousapps.reactivestopwatch.R;
import com.autonomousapps.reactivestopwatch.test.AbstractMockedDependenciesTest;
import com.autonomousapps.reactivestopwatch.test.annotations.CommitStage;
import com.autonomousapps.reactivestopwatch.view.TimeTeller;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.test.rule.ActivityTestRule;
import javax.inject.Inject;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static com.autonomousapps.reactivestopwatch.test.CommonEspressoCalls.verifyViewIsDisplayedWithTextIgnoreCase;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
private void setupMockView() {
doAnswer(invocation -> view = (StopwatchMvp.View) invocation.getArguments()[0])
.when(stopwatchPresenter).attachView(any(StopwatchMvp.View.class));
doAnswer(invocation -> view = null)
.when(stopwatchPresenter).detachView();
}
private void verifyUi() throws Exception {
onView(withId(R.id.stopwatch)).check(matches(isDisplayed()));
onView(withId(R.id.btn_reset_lap)).check(matches(isDisplayed()));
onView(withId(R.id.btn_start_stop)).check(matches(isDisplayed()));
}
private void launchApp() {
activityRule.launchActivity(new Intent());
mockTimeTeller = mock(TimeTeller.class);
view.setTimeTeller(mockTimeTeller);
}
@Test
public void onTickShouldUpdateTime() throws Throwable {
onMainThreadDo(() -> view.onTick(1000L));
verify(mockTimeTeller).tellTime(1000L);
}
@Test
public void onStartedShouldChangeText() throws Throwable {
onMainThreadDo(() -> view.onStopwatchStarted());
| verifyViewIsDisplayedWithTextIgnoreCase(STOP_TEXT); |
autonomousapps/ReactiveStopwatch | app/src/androidTest/java/com/autonomousapps/reactivestopwatch/ui/StopwatchAcceptanceTest.java | // Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractAnimationDisablingTest.java
// public abstract class AbstractAnimationDisablingTest {
//
// @BeforeClass
// public static void disableAnimations() {
// SystemAnimations.disableAll(InstrumentationRegistry.getTargetContext());
// }
//
// @AfterClass
// public static void enableAnimations() {
// SystemAnimations.enableAll(InstrumentationRegistry.getTargetContext());
// }
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/Timer.java
// public class Timer {
//
// private final long start;
//
// public Timer() {
// start = System.currentTimeMillis();
// }
//
// public long elapsedTime() {
// return System.currentTimeMillis() - start;
// }
// }
| import com.autonomousapps.reactivestopwatch.test.AbstractAnimationDisablingTest;
import com.autonomousapps.reactivestopwatch.test.Timer;
import com.autonomousapps.reactivestopwatch.test.annotations.AcceptanceStage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.annotation.NonNull;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.BySelector;
import android.support.test.uiautomator.Configurator;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.Until;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat; | Intent intent = context.getPackageManager().getLaunchIntentForPackage(APPLICATION_PACKAGE);
// intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
return intent;
}
/*
* Uses package manager to find the package name of the device launcher. Usually this package
* is "com.android.launcher" but can be different at times. This is a generic solution which
* works on all platforms.
*/
private static String getLauncherPackageName() {
// Create launcher Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
// Use PackageManager to get the launcher package name
PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();
ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return resolveInfo.activityInfo.packageName;
}
@Test
public void stopwatchShouldBeAccurate() throws Exception {
final long WAIT = 2000L;
// Check precondition
assertThat(stopwatchTime(), is("00:00:00.0"));
// Press 'start'
startStopwatch(); | // Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/AbstractAnimationDisablingTest.java
// public abstract class AbstractAnimationDisablingTest {
//
// @BeforeClass
// public static void disableAnimations() {
// SystemAnimations.disableAll(InstrumentationRegistry.getTargetContext());
// }
//
// @AfterClass
// public static void enableAnimations() {
// SystemAnimations.enableAll(InstrumentationRegistry.getTargetContext());
// }
// }
//
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/test/Timer.java
// public class Timer {
//
// private final long start;
//
// public Timer() {
// start = System.currentTimeMillis();
// }
//
// public long elapsedTime() {
// return System.currentTimeMillis() - start;
// }
// }
// Path: app/src/androidTest/java/com/autonomousapps/reactivestopwatch/ui/StopwatchAcceptanceTest.java
import com.autonomousapps.reactivestopwatch.test.AbstractAnimationDisablingTest;
import com.autonomousapps.reactivestopwatch.test.Timer;
import com.autonomousapps.reactivestopwatch.test.annotations.AcceptanceStage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.annotation.NonNull;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.BySelector;
import android.support.test.uiautomator.Configurator;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.Until;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
Intent intent = context.getPackageManager().getLaunchIntentForPackage(APPLICATION_PACKAGE);
// intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
return intent;
}
/*
* Uses package manager to find the package name of the device launcher. Usually this package
* is "com.android.launcher" but can be different at times. This is a generic solution which
* works on all platforms.
*/
private static String getLauncherPackageName() {
// Create launcher Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
// Use PackageManager to get the launcher package name
PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();
ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return resolveInfo.activityInfo.packageName;
}
@Test
public void stopwatchShouldBeAccurate() throws Exception {
final long WAIT = 2000L;
// Check precondition
assertThat(stopwatchTime(), is("00:00:00.0"));
// Press 'start'
startStopwatch(); | Timer timer = new Timer(); |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/utils/LocationUtils.java | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
| import android.location.Location;
import com.vehiclerental.contracts.BranchContract;
import java.util.List;
import io.nlopez.smartlocation.location.providers.LocationGooglePlayServicesProvider; | /**
* CarRental
*
* This file provides multiple location abstraction methods in order to get the nearest branch to the user
*/
package com.vehiclerental.utils;
public class LocationUtils {
//Constants used in the calculation
private final static double EARTH_RADIUS_IN_KM = 6371;
/**
* Returns the nearest branch to the user position
* This is not a particularly powerful algorithm but the number of branch is expected to be small at this time
*
* @param currentLocation user location
* @param branchContractList list of branches
* @return the nearest branch
*/ | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
// Path: app/src/main/java/com/vehiclerental/utils/LocationUtils.java
import android.location.Location;
import com.vehiclerental.contracts.BranchContract;
import java.util.List;
import io.nlopez.smartlocation.location.providers.LocationGooglePlayServicesProvider;
/**
* CarRental
*
* This file provides multiple location abstraction methods in order to get the nearest branch to the user
*/
package com.vehiclerental.utils;
public class LocationUtils {
//Constants used in the calculation
private final static double EARTH_RADIUS_IN_KM = 6371;
/**
* Returns the nearest branch to the user position
* This is not a particularly powerful algorithm but the number of branch is expected to be small at this time
*
* @param currentLocation user location
* @param branchContractList list of branches
* @return the nearest branch
*/ | public static BranchContract getNearestBranch(Location currentLocation, List<BranchContract> branchContractList) { |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/apiClient/socketImplementation/SocketClient.java | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
| import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.vehiclerental.CarRentalApplication;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.ssl.SSLSocket; | /**
* CarRental
*
* This file provides an abstraction of the native secure socket client
*/
package com.vehiclerental.apiClient.socketImplementation;
public class SocketClient {
/**
* Process given request and return results
*
* @param url the server url
* @param port the server port
* @param request the given request
* @return the deserialized response if the request succeeded, null otherwise
* @throws IOException
* @throws ClassNotFoundException
*/
public static SocketResponseMessage doRequest(String url, int port, SocketRequestMessage request) throws IOException, ClassNotFoundException {
SSLSocket socket;
try { | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
// Path: app/src/main/java/com/vehiclerental/apiClient/socketImplementation/SocketClient.java
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.vehiclerental.CarRentalApplication;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.ssl.SSLSocket;
/**
* CarRental
*
* This file provides an abstraction of the native secure socket client
*/
package com.vehiclerental.apiClient.socketImplementation;
public class SocketClient {
/**
* Process given request and return results
*
* @param url the server url
* @param port the server port
* @param request the given request
* @return the deserialized response if the request succeeded, null otherwise
* @throws IOException
* @throws ClassNotFoundException
*/
public static SocketResponseMessage doRequest(String url, int port, SocketRequestMessage request) throws IOException, ClassNotFoundException {
SSLSocket socket;
try { | socket = (SSLSocket) CarRentalApplication.getSslContext().getSocketFactory().createSocket(url, port); |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/utils/StaticDataUtils.java | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
| import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import com.vehiclerental.contracts.BranchContract;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /**
* CarRental
*
* This file provides a simple access to all the static (or nearly static) data of the system
*
* This includes:
* - The vehicle types
* - The vehicle statuses
* - The branch list (which is only loaded once)
*/
package com.vehiclerental.utils;
public class StaticDataUtils {
//Data structures to provide an easy access to the static data
private static ArrayList<String> vehicleTypes;
private static ArrayList<String> vehicleStatuses; | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
// Path: app/src/main/java/com/vehiclerental/utils/StaticDataUtils.java
import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import com.vehiclerental.contracts.BranchContract;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* CarRental
*
* This file provides a simple access to all the static (or nearly static) data of the system
*
* This includes:
* - The vehicle types
* - The vehicle statuses
* - The branch list (which is only loaded once)
*/
package com.vehiclerental.utils;
public class StaticDataUtils {
//Data structures to provide an easy access to the static data
private static ArrayList<String> vehicleTypes;
private static ArrayList<String> vehicleStatuses; | private static Map<String, BranchContract> branchContractMap; |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/utils/StaticDataUtils.java | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
| import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import com.vehiclerental.contracts.BranchContract;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /**
* CarRental
*
* This file provides a simple access to all the static (or nearly static) data of the system
*
* This includes:
* - The vehicle types
* - The vehicle statuses
* - The branch list (which is only loaded once)
*/
package com.vehiclerental.utils;
public class StaticDataUtils {
//Data structures to provide an easy access to the static data
private static ArrayList<String> vehicleTypes;
private static ArrayList<String> vehicleStatuses;
private static Map<String, BranchContract> branchContractMap;
/**
* Registers all the available vehicle types in memory
*/
private static void initializeVehicleTypes() {
vehicleTypes = new ArrayList<>(); | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
// Path: app/src/main/java/com/vehiclerental/utils/StaticDataUtils.java
import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import com.vehiclerental.contracts.BranchContract;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* CarRental
*
* This file provides a simple access to all the static (or nearly static) data of the system
*
* This includes:
* - The vehicle types
* - The vehicle statuses
* - The branch list (which is only loaded once)
*/
package com.vehiclerental.utils;
public class StaticDataUtils {
//Data structures to provide an easy access to the static data
private static ArrayList<String> vehicleTypes;
private static ArrayList<String> vehicleStatuses;
private static Map<String, BranchContract> branchContractMap;
/**
* Registers all the available vehicle types in memory
*/
private static void initializeVehicleTypes() {
vehicleTypes = new ArrayList<>(); | vehicleTypes.add(0, CarRentalApplication.getAppContext().getString(R.string.small_car_type)); |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/preferences/PreferencesManager.java | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/UserContract.java
// public class UserContract {
// public int id;
// public boolean isStaff;
// public String fullName;
// public String emailAddress;
// public String phoneNumber;
// }
//
// Path: app/src/main/java/com/vehiclerental/utils/SerializationUtils.java
// public class SerializationUtils {
//
// //Static gson object
// private static Gson gsonObject = new Gson();
//
// /**
// * Serialize the provided object to a json string
// *
// * @param object the object to serialize
// * @param <T> the generic object type
// * @return the serialized json string
// */
// public static <T> String serialize(T object) {
// return gsonObject.toJson(object);
// }
//
// /**
// * Deserialize the provided string into the given type
// *
// * @param serialized the serialized json string
// * @param type the expected object type
// * @param <T> the generic object type
// * @return the deserialized object
// */
// public static <T> T deserialize(String serialized, Type type) {
// return gsonObject.fromJson(serialized, type);
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.preference.PreferenceManager;
import com.vehiclerental.contracts.BranchContract;
import com.vehiclerental.contracts.UserContract;
import com.vehiclerental.utils.SerializationUtils; | /**
* CarRental
*
* This file provides preference manager, it is an abstraction layer for the SharedPreferences system, which also provides an in-memory cache
*
* At the moment the file is not too large, but if more preferences were to be added, other files should be created to avoid a bloated class
*/
package com.vehiclerental.preferences;
public class PreferencesManager {
//SharedPreferences storage keys
private static final String PREF_USER_LABEL = "logged_user";
private static final String PREF_PASSWORD_LABEL = "password_user";
private static final String PREF_BRANCH_LABEL = "current_branch";
private static final String PREF_IP_ADDRESS_LABEL = "server_ip";
private static final String PREF_PORT_LABEL = "server_port";
//Default values for the connection system
private static final String DEFAULT_IP_ADDRESS = "161.73.147.225";
private static final int DEFAULT_PORT = 5106;
//In-Memory cache, avoids a reload from the shared preferences every time | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/UserContract.java
// public class UserContract {
// public int id;
// public boolean isStaff;
// public String fullName;
// public String emailAddress;
// public String phoneNumber;
// }
//
// Path: app/src/main/java/com/vehiclerental/utils/SerializationUtils.java
// public class SerializationUtils {
//
// //Static gson object
// private static Gson gsonObject = new Gson();
//
// /**
// * Serialize the provided object to a json string
// *
// * @param object the object to serialize
// * @param <T> the generic object type
// * @return the serialized json string
// */
// public static <T> String serialize(T object) {
// return gsonObject.toJson(object);
// }
//
// /**
// * Deserialize the provided string into the given type
// *
// * @param serialized the serialized json string
// * @param type the expected object type
// * @param <T> the generic object type
// * @return the deserialized object
// */
// public static <T> T deserialize(String serialized, Type type) {
// return gsonObject.fromJson(serialized, type);
// }
// }
// Path: app/src/main/java/com/vehiclerental/preferences/PreferencesManager.java
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.preference.PreferenceManager;
import com.vehiclerental.contracts.BranchContract;
import com.vehiclerental.contracts.UserContract;
import com.vehiclerental.utils.SerializationUtils;
/**
* CarRental
*
* This file provides preference manager, it is an abstraction layer for the SharedPreferences system, which also provides an in-memory cache
*
* At the moment the file is not too large, but if more preferences were to be added, other files should be created to avoid a bloated class
*/
package com.vehiclerental.preferences;
public class PreferencesManager {
//SharedPreferences storage keys
private static final String PREF_USER_LABEL = "logged_user";
private static final String PREF_PASSWORD_LABEL = "password_user";
private static final String PREF_BRANCH_LABEL = "current_branch";
private static final String PREF_IP_ADDRESS_LABEL = "server_ip";
private static final String PREF_PORT_LABEL = "server_port";
//Default values for the connection system
private static final String DEFAULT_IP_ADDRESS = "161.73.147.225";
private static final int DEFAULT_PORT = 5106;
//In-Memory cache, avoids a reload from the shared preferences every time | private static UserContract currentUser; |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/preferences/PreferencesManager.java | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/UserContract.java
// public class UserContract {
// public int id;
// public boolean isStaff;
// public String fullName;
// public String emailAddress;
// public String phoneNumber;
// }
//
// Path: app/src/main/java/com/vehiclerental/utils/SerializationUtils.java
// public class SerializationUtils {
//
// //Static gson object
// private static Gson gsonObject = new Gson();
//
// /**
// * Serialize the provided object to a json string
// *
// * @param object the object to serialize
// * @param <T> the generic object type
// * @return the serialized json string
// */
// public static <T> String serialize(T object) {
// return gsonObject.toJson(object);
// }
//
// /**
// * Deserialize the provided string into the given type
// *
// * @param serialized the serialized json string
// * @param type the expected object type
// * @param <T> the generic object type
// * @return the deserialized object
// */
// public static <T> T deserialize(String serialized, Type type) {
// return gsonObject.fromJson(serialized, type);
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.preference.PreferenceManager;
import com.vehiclerental.contracts.BranchContract;
import com.vehiclerental.contracts.UserContract;
import com.vehiclerental.utils.SerializationUtils; | /**
* CarRental
*
* This file provides preference manager, it is an abstraction layer for the SharedPreferences system, which also provides an in-memory cache
*
* At the moment the file is not too large, but if more preferences were to be added, other files should be created to avoid a bloated class
*/
package com.vehiclerental.preferences;
public class PreferencesManager {
//SharedPreferences storage keys
private static final String PREF_USER_LABEL = "logged_user";
private static final String PREF_PASSWORD_LABEL = "password_user";
private static final String PREF_BRANCH_LABEL = "current_branch";
private static final String PREF_IP_ADDRESS_LABEL = "server_ip";
private static final String PREF_PORT_LABEL = "server_port";
//Default values for the connection system
private static final String DEFAULT_IP_ADDRESS = "161.73.147.225";
private static final int DEFAULT_PORT = 5106;
//In-Memory cache, avoids a reload from the shared preferences every time
private static UserContract currentUser; | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/UserContract.java
// public class UserContract {
// public int id;
// public boolean isStaff;
// public String fullName;
// public String emailAddress;
// public String phoneNumber;
// }
//
// Path: app/src/main/java/com/vehiclerental/utils/SerializationUtils.java
// public class SerializationUtils {
//
// //Static gson object
// private static Gson gsonObject = new Gson();
//
// /**
// * Serialize the provided object to a json string
// *
// * @param object the object to serialize
// * @param <T> the generic object type
// * @return the serialized json string
// */
// public static <T> String serialize(T object) {
// return gsonObject.toJson(object);
// }
//
// /**
// * Deserialize the provided string into the given type
// *
// * @param serialized the serialized json string
// * @param type the expected object type
// * @param <T> the generic object type
// * @return the deserialized object
// */
// public static <T> T deserialize(String serialized, Type type) {
// return gsonObject.fromJson(serialized, type);
// }
// }
// Path: app/src/main/java/com/vehiclerental/preferences/PreferencesManager.java
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.preference.PreferenceManager;
import com.vehiclerental.contracts.BranchContract;
import com.vehiclerental.contracts.UserContract;
import com.vehiclerental.utils.SerializationUtils;
/**
* CarRental
*
* This file provides preference manager, it is an abstraction layer for the SharedPreferences system, which also provides an in-memory cache
*
* At the moment the file is not too large, but if more preferences were to be added, other files should be created to avoid a bloated class
*/
package com.vehiclerental.preferences;
public class PreferencesManager {
//SharedPreferences storage keys
private static final String PREF_USER_LABEL = "logged_user";
private static final String PREF_PASSWORD_LABEL = "password_user";
private static final String PREF_BRANCH_LABEL = "current_branch";
private static final String PREF_IP_ADDRESS_LABEL = "server_ip";
private static final String PREF_PORT_LABEL = "server_port";
//Default values for the connection system
private static final String DEFAULT_IP_ADDRESS = "161.73.147.225";
private static final int DEFAULT_PORT = 5106;
//In-Memory cache, avoids a reload from the shared preferences every time
private static UserContract currentUser; | private static BranchContract currentBranch; |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/preferences/PreferencesManager.java | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/UserContract.java
// public class UserContract {
// public int id;
// public boolean isStaff;
// public String fullName;
// public String emailAddress;
// public String phoneNumber;
// }
//
// Path: app/src/main/java/com/vehiclerental/utils/SerializationUtils.java
// public class SerializationUtils {
//
// //Static gson object
// private static Gson gsonObject = new Gson();
//
// /**
// * Serialize the provided object to a json string
// *
// * @param object the object to serialize
// * @param <T> the generic object type
// * @return the serialized json string
// */
// public static <T> String serialize(T object) {
// return gsonObject.toJson(object);
// }
//
// /**
// * Deserialize the provided string into the given type
// *
// * @param serialized the serialized json string
// * @param type the expected object type
// * @param <T> the generic object type
// * @return the deserialized object
// */
// public static <T> T deserialize(String serialized, Type type) {
// return gsonObject.fromJson(serialized, type);
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.preference.PreferenceManager;
import com.vehiclerental.contracts.BranchContract;
import com.vehiclerental.contracts.UserContract;
import com.vehiclerental.utils.SerializationUtils; | /**
* CarRental
*
* This file provides preference manager, it is an abstraction layer for the SharedPreferences system, which also provides an in-memory cache
*
* At the moment the file is not too large, but if more preferences were to be added, other files should be created to avoid a bloated class
*/
package com.vehiclerental.preferences;
public class PreferencesManager {
//SharedPreferences storage keys
private static final String PREF_USER_LABEL = "logged_user";
private static final String PREF_PASSWORD_LABEL = "password_user";
private static final String PREF_BRANCH_LABEL = "current_branch";
private static final String PREF_IP_ADDRESS_LABEL = "server_ip";
private static final String PREF_PORT_LABEL = "server_port";
//Default values for the connection system
private static final String DEFAULT_IP_ADDRESS = "161.73.147.225";
private static final int DEFAULT_PORT = 5106;
//In-Memory cache, avoids a reload from the shared preferences every time
private static UserContract currentUser;
private static BranchContract currentBranch;
private static String userPassword;
private static String ipAddress;
private static Integer port;
/**
* Returns the SharedPreferences for the given context
*
* @param ctx current context
* @return SharedPreferences instance
*/
private static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
/**
* Updates the current branch
*
* @param ctx current context
* @param contract newly selected branch
*/
public static void setCurrentBranch(Context ctx, BranchContract contract) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit(); | // Path: app/src/main/java/com/vehiclerental/contracts/BranchContract.java
// public class BranchContract {
// public int id;
// public String name;
// public double latitude;
// public double longitude;
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/UserContract.java
// public class UserContract {
// public int id;
// public boolean isStaff;
// public String fullName;
// public String emailAddress;
// public String phoneNumber;
// }
//
// Path: app/src/main/java/com/vehiclerental/utils/SerializationUtils.java
// public class SerializationUtils {
//
// //Static gson object
// private static Gson gsonObject = new Gson();
//
// /**
// * Serialize the provided object to a json string
// *
// * @param object the object to serialize
// * @param <T> the generic object type
// * @return the serialized json string
// */
// public static <T> String serialize(T object) {
// return gsonObject.toJson(object);
// }
//
// /**
// * Deserialize the provided string into the given type
// *
// * @param serialized the serialized json string
// * @param type the expected object type
// * @param <T> the generic object type
// * @return the deserialized object
// */
// public static <T> T deserialize(String serialized, Type type) {
// return gsonObject.fromJson(serialized, type);
// }
// }
// Path: app/src/main/java/com/vehiclerental/preferences/PreferencesManager.java
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.preference.PreferenceManager;
import com.vehiclerental.contracts.BranchContract;
import com.vehiclerental.contracts.UserContract;
import com.vehiclerental.utils.SerializationUtils;
/**
* CarRental
*
* This file provides preference manager, it is an abstraction layer for the SharedPreferences system, which also provides an in-memory cache
*
* At the moment the file is not too large, but if more preferences were to be added, other files should be created to avoid a bloated class
*/
package com.vehiclerental.preferences;
public class PreferencesManager {
//SharedPreferences storage keys
private static final String PREF_USER_LABEL = "logged_user";
private static final String PREF_PASSWORD_LABEL = "password_user";
private static final String PREF_BRANCH_LABEL = "current_branch";
private static final String PREF_IP_ADDRESS_LABEL = "server_ip";
private static final String PREF_PORT_LABEL = "server_port";
//Default values for the connection system
private static final String DEFAULT_IP_ADDRESS = "161.73.147.225";
private static final int DEFAULT_PORT = 5106;
//In-Memory cache, avoids a reload from the shared preferences every time
private static UserContract currentUser;
private static BranchContract currentBranch;
private static String userPassword;
private static String ipAddress;
private static Integer port;
/**
* Returns the SharedPreferences for the given context
*
* @param ctx current context
* @return SharedPreferences instance
*/
private static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
/**
* Updates the current branch
*
* @param ctx current context
* @param contract newly selected branch
*/
public static void setCurrentBranch(Context ctx, BranchContract contract) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit(); | editor.putString(PREF_BRANCH_LABEL, SerializationUtils.serialize(contract)); |